forkConversation method

Future<String> forkConversation({
  1. required String parentSessionId,
  2. required int atMessageIndex,
  3. String? reason,
})

Fork a conversation at a specific message index.

Implementation

Future<String> forkConversation({
  required String parentSessionId,
  required int atMessageIndex,
  String? reason,
}) async {
  final messages = await loadConversation(parentSessionId);
  if (messages == null || atMessageIndex >= messages.length) {
    throw ArgumentError('Invalid message index or session not found.');
  }

  // Create new session with messages up to the fork point
  final forkId = 'fork-${DateTime.now().millisecondsSinceEpoch}';
  final forkedMessages = messages.sublist(0, atMessageIndex + 1);

  await saveConversation(
    sessionId: forkId,
    messages: forkedMessages,
    model: 'unknown',
    turns: [],
    title: 'Fork of $parentSessionId',
  );

  // Save fork metadata
  final forkPoint = ForkPoint(
    parentSessionId: parentSessionId,
    messageIndex: atMessageIndex,
    forkSessionId: forkId,
    forkedAt: DateTime.now(),
    reason: reason,
  );
  final forkFile = File(p.join(_sessionsDir, forkId, 'fork.json'));
  await forkFile.writeAsString(
    const JsonEncoder.withIndent('  ').convert(forkPoint.toJson()),
  );

  return forkId;
}