import '../../../core/api_gateway.dart'; import 'chat_transcript.dart'; /// Joins a history read with the live reply that streams during it. /// /// A harness that numbers its text and reasoning deltas (`seq`) puts a /// streaming block's text so far into the newest history page, under the /// block's live part id, and reports the last delta the page includes /// (`liveSeq`) and which parts it added (`liveParts`). Without this a client /// that read history mid-reply (opening the chat, a reconnect, a resync) only /// ever got the deltas after its read, and the reply's first part was missing. /// /// [ChatLiveFrames] records the numbered frames that arrive while a read is in /// flight and, once the page is applied, folds back the ones the page does not /// include. It also drops a frame already included in a page, which can still /// be on its way when the page arrives. class ChatLiveFrames { final List> _reads = []; int _included = 0; /// Starts recording for one read; pass the result to [settle]. List beginRead() { final frames = []; _reads.add(frames); return frames; } /// Stops recording for a read that will not be applied. void abandon(List frames) => _reads.remove(frames); /// The part of [frame] to fold into the held transcript, recording it for /// every read in flight, or null when a page already included all of it. A /// frame with no number is always folded whole; a joined frame whose first /// deltas were already included is trimmed to the rest. JsonMap? admit(JsonMap frame) { final seq = frame['seq']; if (seq is! int) return frame; if (seq <= _included) return null; final admitted = chatDeltasAfter(frame, _included); if (admitted == null) return null; _included = seq; for (final read in _reads) { read.add(admitted); } return admitted; } /// [messages] after applying [page]: frames recorded during the read that /// the page does not include are folded onto the page's copies. [replaced] /// says whether a message's held copy was replaced by the page (frames for a /// held copy that was kept are already in it). List settle( List frames, JsonMap page, List messages, { required bool Function(Object? messageId) replaced, }) { _reads.remove(frames); final liveSeq = page['liveSeq']; if (liveSeq is! int) return messages; if (liveSeq > _included) _included = liveSeq; final live = {...(page['liveParts'] as List? ?? const [])}; final pageParts = >{}; for (final message in (page['messages'] as List? ?? const [])) { if (message is! Map) continue; pageParts[message['id']] = { for (final part in (message['parts'] as List? ?? const [])) if (part is Map) part['id'], }; } var thread = {'messages': messages}; for (final recorded in frames) { final seq = recorded['seq']; if (seq is! int || seq <= liveSeq) continue; final frame = chatDeltasAfter(recorded, liveSeq); if (frame == null) continue; final messageId = frame['message_id']; if (!replaced(messageId)) continue; final part = frame['part']; final partId = part is Map ? part['id'] : null; final held = pageParts[messageId]; // A part the page holds whole (not as live text) is already complete. if (held != null && held.contains(partId) && !live.contains(partId)) { continue; } thread = applyChatEvent(thread, frame); } return chatMessageList(thread['messages']); } } /// [frame] without the numbered deltas up to [included]. /// /// A server joins consecutive deltas of one part while a slow client's queue /// is backed up: the joined frame's `seq_from`..`seq` names the deltas it holds /// and `delta_lens` each one's length in UTF-16 code units. When a history page /// already holds a prefix of them, only the rest is new. A plain frame (or one /// wholly past [included]) is returned unchanged; null means nothing in it is /// new. JsonMap? chatDeltasAfter(JsonMap frame, int included) { final seq = frame['seq']; if (seq is! int) return frame; if (seq <= included) return null; final from = frame['seq_from']; final lens = frame['delta_lens']; if (from is! int || from > included || lens is! List) return frame; final delta = frame['delta']; if (delta is! String || lens.length != seq - from + 1) return frame; var cut = 0; for (var i = 0; i <= included - from; i++) { final length = lens[i]; if (length is! int || length < 0) return frame; cut += length; } if (cut >= delta.length) return null; return { ...frame, 'delta': delta.substring(cut), 'seq_from': included + 1, 'delta_lens': lens.sublist(included - from + 1), }; }