diff --git a/app/lib/features/chat/conversation/chat_thread_controller.dart b/app/lib/features/chat/conversation/chat_thread_controller.dart index 5c96ff3e..b4a6d6c9 100644 --- a/app/lib/features/chat/conversation/chat_thread_controller.dart +++ b/app/lib/features/chat/conversation/chat_thread_controller.dart @@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../data/chat_repository.dart'; import '../domain/chat_account_usage.dart'; +import '../domain/chat_live_frames.dart'; import '../domain/chat_sessions.dart'; import '../domain/chat_shown_items.dart'; import '../domain/chat_transcript.dart'; @@ -61,6 +62,7 @@ class ChatThreadController extends ChangeNotifier { StreamSubscription? _subscription; final _transcriptChanges = ChangeNotifier(); final ChatServerQueue _queue = ChatServerQueue(); + final ChatLiveFrames _live = ChatLiveFrames(); /// The per-turn change summaries the transcript's change chips show. final ChatTurnDiffs turnDiffs = ChatTurnDiffs(); @@ -280,10 +282,20 @@ class ChatThreadController extends ChangeNotifier { } Future _readNewest(int token, {required bool replaceHeldTurn}) async { + // Deltas of a reply streaming during the read: the page holds the reply + // up to its own point, and those after it are folded back on top. + final frames = _live.beginRead(); try { final page = await _repository.history(sessionId, limit: 200); - if (!_owned(token)) return; + if (!_owned(token)) { + _live.abandon(frames); + return; + } turnDiffs.apply(page['turnDiffs'], sessionId); + final inPage = { + for (final message in (page['messages'] as List? ?? const [])) + if (message is Map) message['id'], + }; if (replaceHeldTurn) { _messages = (page['messages'] as List? ?? const []) .whereType() @@ -297,15 +309,25 @@ class ChatThreadController extends ChangeNotifier { _applyPage(refreshCachedChatHistory(_messages, page, untouched)); } else { // A live frame may have arrived while the page was loading; merge it - // over the held transcript instead of replacing it. - _applyPage(mergeChatHistory({'messages': _messages}, page)); + // over the held transcript instead of replacing it. The page's order + // leads: a reply that streamed during the read stays below its prompt. + _applyPage( + mergeChatHistory({'messages': _messages}, page, older: true), + ); } + _messages = _live.settle( + frames, + page, + _messages, + replaced: (id) => replaceHeldTurn || inPage.contains(id), + ); _untouchedCached = null; _authoritative = true; _loaded = true; _loading = false; _error = null; } catch (error) { + _live.abandon(frames); if (!_owned(token)) return; // A refused read is not an empty successful history: the reason stays // visible and the held transcript is kept. @@ -416,6 +438,8 @@ class ChatThreadController extends ChangeNotifier { ); return; } + // A delta a history page already included is not added again. + if (!_live.admit(body)) return; final current = _thread; final next = applyChatEvent(current, body); if (identical(next, current)) return; diff --git a/app/lib/features/chat/data/chat_repository.dart b/app/lib/features/chat/data/chat_repository.dart index 3ad40fc9..bb408656 100644 --- a/app/lib/features/chat/data/chat_repository.dart +++ b/app/lib/features/chat/data/chat_repository.dart @@ -163,6 +163,9 @@ class ChatRepository { 'nextCursor': '${page['next_cursor'] ?? ''}', 'hasMore': page['has_more'] == true, 'turnDiffs': ?turnDiffs, + // A streaming reply's text so far (see chat_live_frames.dart). + if (page['live_seq'] is int) 'liveSeq': page['live_seq'], + if (page['live_parts'] is List) 'liveParts': page['live_parts'], }; } return { diff --git a/app/lib/features/chat/domain/chat_live_frames.dart b/app/lib/features/chat/domain/chat_live_frames.dart new file mode 100644 index 00000000..d62aa7b1 --- /dev/null +++ b/app/lib/features/chat/domain/chat_live_frames.dart @@ -0,0 +1,84 @@ +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); + + /// Whether [frame] should be folded into the held transcript, recording it + /// for every read in flight. A frame with no number is always folded. + bool admit(JsonMap frame) { + final seq = frame['seq']; + if (seq is! int) return true; + if (seq <= _included) return false; + _included = seq; + for (final read in _reads) { + read.add(frame); + } + return true; + } + + /// [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 frame in frames) { + final seq = frame['seq']; + if (seq is! int || seq <= liveSeq) 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']); + } +} diff --git a/app/test/features/chat/conversation/chat_thread_mid_reply_test.dart b/app/test/features/chat/conversation/chat_thread_mid_reply_test.dart new file mode 100644 index 00000000..a6113ccc --- /dev/null +++ b/app/test/features/chat/conversation/chat_thread_mid_reply_test.dart @@ -0,0 +1,152 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart'; + +import 'chat_thread_fixtures.dart'; + +// A chat opened (or reconnected) while a reply streams used to show the reply +// with its first part cut off: history did not hold the block still streaming, +// and only the deltas after the read arrived. The newest page now carries the +// block's text so far and the number of the last delta it includes. + +JsonMap seqFrame(String text, int seq, {String messageId = 'a'}) => { + ...chatTextFrame(text, messageId: messageId), + 'seq': seq, +}; + +JsonMap livePage(List messages, int liveSeq, List parts) { + final page = chatPage(messages); + final body = page['chat_history'] as JsonMap; + body['live_seq'] = liveSeq; + body['live_parts'] = parts; + return page; +} + +void main() { + late FakeChatGateway gateway; + late ChatThreadController controller; + + setUp(() { + gateway = FakeChatGateway(); + controller = ChatThreadController(gateway, 's'); + }); + + tearDown(() { + controller.dispose(); + gateway.close(); + }); + + List texts() => [ + for (final part in controller.messages.last['parts'] as List) + (part as Map)['text'], + ]; + + test('opening mid-reply shows the reply from its beginning', () async { + final reply = Completer(); + gateway.history = (_) => reply.future; + final loading = controller.load(); + await pumpEventQueue(); + // Deltas arrive while the page is read: the first is in the page, the + // second came after the page's point. + gateway.emitEvent(seqFrame('part. ', 11)); + gateway.emitEvent(seqFrame('And more.', 12)); + await pumpEventQueue(); + reply.complete( + livePage( + [ + chatMessage('u', 'user'), + chatMessage( + 'a', + 'assistant', + parts: [ + {'type': 'reasoning', 'id': 'r', 'text': 'Thinking.'}, + {'type': 'text', 'id': 'p', 'text': 'The first part. '}, + ], + ), + ], + 11, + ['p'], + ), + ); + await loading; + expect(texts(), ['Thinking.', 'The first part. And more.']); + + // A delta the page included can still be on its way: it is not repeated. + gateway.emitEvent(seqFrame('part. ', 11)); + gateway.emitEvent(seqFrame(' Done.', 13)); + await pumpEventQueue(); + expect(texts(), ['Thinking.', 'The first part. And more. Done.']); + }); + + test( + 'a resync mid-reply keeps the reply whole, including a new message', + () async { + gateway.history = (_) async => chatPage([chatMessage('u', 'user')]); + await controller.load(); + gateway.emitEvent(seqFrame('The first', 1)); + await pumpEventQueue(); + + final reply = Completer(); + gateway.history = (_) => reply.future; + final resync = controller.resync(); + await pumpEventQueue(); + gateway.emitEvent(seqFrame(' part.', 2)); + gateway.emitEvent(seqFrame('Next', 3, messageId: 'b')); + await pumpEventQueue(); + reply.complete( + livePage( + [ + chatMessage('u', 'user'), + chatMessage( + 'a', + 'assistant', + parts: [ + {'type': 'text', 'id': 'p', 'text': 'The first part.'}, + ], + ), + ], + 2, + ['p'], + ), + ); + await resync; + final ids = [for (final message in controller.messages) message['id']]; + expect(ids, ['u', 'a', 'b']); + expect( + ((controller.messages[1]['parts'] as List).single as Map)['text'], + 'The first part.', + ); + expect(texts(), ['Next']); + }, + ); + + test('a part the page holds complete is not extended again', () async { + final reply = Completer(); + gateway.history = (_) => reply.future; + final loading = controller.load(); + await pumpEventQueue(); + gateway.emitEvent(seqFrame(' tail', 8)); + await pumpEventQueue(); + // The block completed and was written between the page's live point and + // the file read, so the page holds it whole rather than as live text. + reply.complete( + livePage( + [ + chatMessage( + 'a', + 'assistant', + parts: [ + {'type': 'text', 'id': 'p', 'text': 'Whole text tail'}, + ], + ), + ], + 7, + const [], + ), + ); + await loading; + expect(texts(), ['Whole text tail']); + }); +}