insertMessageChain method

Future<void> insertMessageChain(
  1. Transcript messages, {
  2. bool isSidechain = false,
  3. String? agentId,
  4. String? startingParentUuid,
})

Insert a chain of messages into the transcript.

Implementation

Future<void> insertMessageChain(
  Transcript messages, {
  bool isSidechain = false,
  String? agentId,
  String? startingParentUuid,
}) async {
  String? parentUuid = startingParentUuid;

  // First user/assistant message materializes the session file.
  if (_sessionFile == null &&
      messages.any((m) => m['type'] == 'user' || m['type'] == 'assistant')) {
    await _materializeSessionFile();
  }

  for (final message in messages) {
    final isCompactBoundary =
        message['type'] == 'system' &&
        message['subtype'] == 'compact_boundary';

    // Build transcript entry.
    final entry = <String, dynamic>{
      'parentUuid': isCompactBoundary ? null : parentUuid,
      if (isCompactBoundary && parentUuid != null)
        'logicalParentUuid': parentUuid,
      'isSidechain': isSidechain,
      'agentId': ?agentId,
      ...message,
      'sessionId': _sessionId,
      'cwd': cwd,
      'version': 'flutter-port',
    };

    await _appendEntry(LogEntry(type: entry['type'] as String, data: entry));

    // Update parent chain (skip progress messages).
    if (message['type'] != 'progress') {
      parentUuid = message['uuid'] as String?;
    }
  }

  // Cache last user prompt for metadata.
  if (!isSidechain) {
    final text = _getFirstMeaningfulText(messages);
    if (text != null) {
      final flat = text.replaceAll('\n', ' ').trim();
      currentSessionLastPrompt = flat.length > 200
          ? '${flat.substring(0, 200).trim()}\u2026'
          : flat;
    }
  }
}