import '../../../core/api_gateway.dart'; /// Merge chronological history pages by message id. Incoming authoritative /// copies replace held copies without changing their order; cursor is opaque. JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) { final held = (previous['messages'] as List? ?? const []) .whereType() .map((m) => Map.from(m)) .toList(); final incoming = (page['messages'] as List? ?? const []) .whereType() .map((m) => Map.from(m)) .toList(); final latest = {}; for (final message in incoming) { if (message['id'] != null) latest[message['id']] = message; } final combined = older ? [...incoming, ...held] : [...held, ...incoming]; final seen = {}; final messages = []; for (final message in combined) { final id = message['id']; if (id != null && !seen.add(id)) continue; messages.add(id == null ? message : latest[id] ?? message); } return { 'messages': messages, 'nextCursor': '${page['nextCursor'] ?? ''}', 'hasMore': page['hasMore'] == true, 'loaded': true, 'loading': false, }; } /// Consecutive assistant messages form one answer turn. All part fields (also /// future/unknown protocol types) are preserved in original order. List transcriptRows(List messages) { final rows = []; String? key; final parts = []; void flush() { if (key != null && parts.isNotEmpty) { rows.add({ 'kind': 'assistant', 'key': key, 'parts': List.of(parts), }); } key = null; parts.clear(); } for (final message in messages) { if (message['role'] == 'assistant') { key ??= '${message['id'] ?? ''}'; for (final part in (message['parts'] as List? ?? const [])) { if (part is Map) parts.add(Map.from(part)); } } else { flush(); rows.add({'kind': 'user', 'key': message['id'], 'message': message}); } } flush(); return rows; } /// Replace a local optimistic user row when its server echo identifies the /// same operation/native message; otherwise append once by authoritative id. List reconcileChatUser(List messages, JsonMap remote) { final operation = remote['operation_id']; final nativeId = remote['native_message_id']; final id = remote['id']; final index = messages.indexWhere( (message) => (operation != null && message['operation_id'] == operation) || (nativeId != null && message['native_message_id'] == nativeId) || (id != null && message['id'] == id), ); if (index < 0) return [...messages, remote]; final result = List.of(messages); result[index] = remote; return result; } /// Fold a live chat frame into an immutable thread snapshot. Text and reasoning /// deltas append by part id, tool snapshots merge without dropping prior fields, /// and step frames update turn activity. Frames for another session are ignored. JsonMap applyChatEvent(JsonMap thread, JsonMap frame) { final session = thread['sessionId']; if (session != null && frame['session_id'] != null && session != frame['session_id']) { return thread; } final messages = (thread['messages'] as List? ?? const []) .whereType() .map((m) => Map.from(m)) .toList(); final kind = frame['kind']; if (kind == 'user') { final part = frame['part']; final text = part is Map ? part['text'] : null; final id = frame['message_id']; if (text is! String || text.isEmpty || id == null || messages.any( (m) => m['id'] == id || (frame['operation_id'] != null && m['operation_id'] == frame['operation_id']), )) { return thread; } messages.add({ 'id': id, 'session_id': frame['session_id'], 'role': 'user', 'client': frame['client'], 'operation_id': frame['operation_id'], 'parts': [ {'type': 'text', 'text': text}, ...(frame['attachments'] is List ? frame['attachments'] as List : const []), ], }); return {...thread, 'messages': messages}; } if (kind == 'text' || kind == 'reasoning' || kind == 'tool') { final incoming = frame['part']; if (incoming is! Map || incoming['id'] == null) return thread; final messageId = frame['message_id']; var index = messages.indexWhere( (m) => m['id'] == messageId && m['role'] == 'assistant', ); if (index < 0) { messages.add({ 'id': messageId, 'session_id': frame['session_id'], 'role': 'assistant', 'parts': [], }); index = messages.length - 1; } final message = messages[index]; final parts = (message['parts'] as List? ?? const []) .whereType() .map((p) => Map.from(p)) .toList(); final partIndex = parts.indexWhere( (p) => p['id'] == incoming['id'] && p['type'] == kind, ); if (kind == 'text' || kind == 'reasoning') { final delta = frame['delta']; if (delta is! String || delta.isEmpty) return thread; if (partIndex < 0) { parts.add({'type': kind, 'id': incoming['id'], 'text': delta}); } else { parts[partIndex] = { ...parts[partIndex], 'text': '${parts[partIndex]['text'] ?? ''}$delta', }; } } else if (partIndex < 0) { parts.add(Map.from(incoming)); } else { final merged = { ...parts[partIndex], ...Map.from(incoming), }; if (parts[partIndex]['state'] is Map && incoming['state'] is Map) { merged['state'] = { ...Map.from(parts[partIndex]['state'] as Map), ...Map.from(incoming['state'] as Map), }; } parts[partIndex] = merged; } messages[index] = {...message, 'parts': parts}; return {...thread, 'messages': messages, 'running': true}; } if (kind == 'step' && frame['step'] is Map) { final step = frame['step'] as Map; if (step['intermediate'] == true) return thread; return { ...thread, 'running': step['status'] != 'ended', 'nativeTurnId': step['status'] == 'ended' ? '' : (step['turn_id'] ?? thread['nativeTurnId'] ?? ''), }; } return thread; } /// Queue serialized sends per session; operation ids survive retries/replays. class QueuedChatSend { QueuedChatSend({ required this.operationId, required this.text, this.files = const [], }); final String operationId; final String text; final List files; /// Retry the same immutable intent with the same idempotency key. QueuedChatSend retry() => QueuedChatSend( operationId: operationId, text: text, files: List.unmodifiable(files), ); } class ChatSendQueue { final Map> _sessions = {}; List forSession(String sessionId) => List.unmodifiable(_sessions[sessionId] ?? const []); bool enqueue(String sessionId, QueuedChatSend send) { final queue = _sessions.putIfAbsent(sessionId, () => []); if (queue.any((item) => item.operationId == send.operationId)) return false; queue.add(send); return true; } QueuedChatSend? takeNext(String sessionId) { final queue = _sessions[sessionId]; if (queue == null || queue.isEmpty) return null; final result = queue.removeAt(0); if (queue.isEmpty) _sessions.remove(sessionId); return result; } }