From cf4579ab15f6d6235d164c78c688746cf94abf27 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 14:43:52 +0000 Subject: [PATCH] App: keep a left chat's cached transcript following its live frames A left conversation stays subscribed on the server for the rest of the connection, but the cached transcript was frozen when it was left. A reply that arrived in the background only appeared after the reopened view's subscribe and newest-page read (~1-2s over the network on large chats). The cache now folds the session's chat events into the kept transcript, so the reply is drawn the moment the chat opens; the page still replaces it. Co-Authored-By: Claude Opus 5.5 --- .../chat/conversation/chat_thread_view.dart | 22 ++++- .../conversation/chat_transcript_cache.dart | 75 ++++++++++++-- .../conversation/chat_thread_scroll_test.dart | 28 ++++++ .../chat_transcript_cache_test.dart | 97 +++++++++++++++++++ 4 files changed, 211 insertions(+), 11 deletions(-) diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 0d09896b..67c75627 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -580,15 +580,23 @@ class _ChatThreadViewState extends State with ChatFindHost { /// Keeps the transcript being left for the next visit. Only one backed by a /// successful read on the current connection is written; otherwise the - /// earlier entry stays, and every visit re-reads anyway. - void _saveTranscript(ChatTranscriptCache? cache, String sessionId) { + /// earlier entry stays, and every visit re-reads anyway. The session stays + /// subscribed on [gateway]'s connection, so the kept transcript follows its + /// frames and a reply that arrives meanwhile is there on reopening. + void _saveTranscript( + ChatTranscriptCache? cache, + String sessionId, + ApiGateway gateway, + ) { if (cache == null) return; if (_closed) { cache.remove(sessionId); return; } final snapshot = _controller.snapshot; - if (snapshot != null) cache.write(sessionId, snapshot); + if (snapshot != null) { + cache.write(sessionId, snapshot, frames: gateway.frames); + } } void _sessionClosed() { @@ -758,7 +766,11 @@ class _ChatThreadViewState extends State with ChatFindHost { _persistPosition(oldWidget.sessionId); // A transcript from another server is not this one's to keep. if (oldWidget.gateway == widget.gateway) { - _saveTranscript(oldWidget.transcripts, oldWidget.sessionId); + _saveTranscript( + oldWidget.transcripts, + oldWidget.sessionId, + oldWidget.gateway, + ); } else { _images = ChatAttachmentImages(widget.gateway); } @@ -849,7 +861,7 @@ class _ChatThreadViewState extends State with ChatFindHost { // reply another pane is reading carries on. unawaited(speechController.stopScope(widget.sessionId)); _persistPosition(); - _saveTranscript(widget.transcripts, widget.sessionId); + _saveTranscript(widget.transcripts, widget.sessionId, widget.gateway); widget.paneCommands?.removeListener(_takeCommands); widget.paneCommands?.setFinished(widget.sessionId, false); disposeFind(); diff --git a/app/lib/features/chat/conversation/chat_transcript_cache.dart b/app/lib/features/chat/conversation/chat_transcript_cache.dart index d19ece24..3b850a07 100644 --- a/app/lib/features/chat/conversation/chat_transcript_cache.dart +++ b/app/lib/features/chat/conversation/chat_transcript_cache.dart @@ -1,6 +1,8 @@ +import 'dart:async'; import 'dart:collection'; import '../../../core/api_gateway.dart'; +import '../domain/chat_transcript.dart'; /// The newest transcript one conversation view held when it was left. /// @@ -23,6 +25,12 @@ class ChatTranscriptSnapshot { /// Transcripts of recently left conversations, kept in memory by the chat /// destination for the rest of the app session, like its scroll positions. /// +/// A left conversation stays subscribed on the server for the rest of the +/// connection (there is no `chat_unsubscribe`), so its live frames keep +/// arriving. A transcript written with its gateway's `frames` folds them in, +/// so a reopened conversation already shows the replies that arrived while +/// it was in the background instead of only after its re-read. +/// /// Bounded twice: at most [maxSessions] conversations and [maxMessages] held /// messages in total, evicting the least recently used first. A transcript /// larger than [maxMessages] on its own is not kept. Nothing is written to @@ -36,6 +44,7 @@ class ChatTranscriptCache { /// Least recently used first. final LinkedHashMap _entries = LinkedHashMap(); + final Map> _follows = {}; int _messageCount = 0; /// The cached sessions, least recently used first. @@ -49,23 +58,77 @@ class ChatTranscriptCache { return snapshot; } - void write(String sessionId, ChatTranscriptSnapshot snapshot) { + /// Keeps [snapshot] for [sessionId]. With [frames] (the session's gateway + /// frames), the session's live chat events keep folding into it until it + /// is replaced, removed or evicted. + void write( + String sessionId, + ChatTranscriptSnapshot snapshot, { + Stream? frames, + }) { remove(sessionId); - if (snapshot.messages.length > maxMessages) return; - _entries[sessionId] = snapshot; - _messageCount += snapshot.messages.length; - while (_entries.length > maxSessions || _messageCount > maxMessages) { - remove(_entries.keys.first); + if (!_store(sessionId, snapshot)) return; + if (frames != null) { + _follows[sessionId] = frames.listen( + (envelope) => _fold(sessionId, envelope), + ); } } void remove(String sessionId) { + unawaited(_follows.remove(sessionId)?.cancel()); final removed = _entries.remove(sessionId); if (removed != null) _messageCount -= removed.messages.length; } void clear() { + for (final follow in _follows.values) { + unawaited(follow.cancel()); + } + _follows.clear(); _entries.clear(); _messageCount = 0; } + + /// Puts [snapshot] last (most recently used) and enforces the bounds; + /// false when it is too large to keep at all. + bool _store(String sessionId, ChatTranscriptSnapshot snapshot) { + if (snapshot.messages.length > maxMessages) return false; + _entries[sessionId] = snapshot; + _messageCount += snapshot.messages.length; + while (_entries.length > maxSessions || _messageCount > maxMessages) { + remove(_entries.keys.first); + } + return _entries.containsKey(sessionId); + } + + /// Folds one live chat event for [sessionId] into its kept transcript, in + /// place (its recency is unchanged). A reopened view still treats every + /// kept message as a placeholder its newest page replaces. + void _fold(String sessionId, JsonMap envelope) { + if (envelope['type'] != 'chat_event') return; + final body = envelope['chat_event']; + if (body is! Map || body['session_id'] != sessionId) return; + final held = _entries[sessionId]; + if (held == null) return; + final thread = {'sessionId': sessionId, 'messages': held.messages}; + final next = applyChatEvent(thread, Map.from(body)); + if (identical(next['messages'], held.messages)) return; + final messages = chatMessageList(next['messages']); + _messageCount += messages.length - held.messages.length; + _entries[sessionId] = ChatTranscriptSnapshot( + messages: messages, + cursor: held.cursor, + hasMore: held.hasMore, + ); + if (messages.length > maxMessages) { + remove(sessionId); + return; + } + while (_messageCount > maxMessages) { + final oldest = _entries.keys.first; + if (oldest == sessionId) break; + remove(oldest); + } + } } diff --git a/app/test/features/chat/conversation/chat_thread_scroll_test.dart b/app/test/features/chat/conversation/chat_thread_scroll_test.dart index 3f9bee52..a6517d83 100644 --- a/app/test/features/chat/conversation/chat_thread_scroll_test.dart +++ b/app/test/features/chat/conversation/chat_thread_scroll_test.dart @@ -246,6 +246,34 @@ void main() { expect(reopened.position.pixels, closeTo(saved, 1)); }); + testWidgets('a left conversation keeps folding its replies into the cache', ( + tester, + ) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => tallPage(); + final transcripts = ChatTranscriptCache(); + await tester.pumpWidget( + host( + ChatThreadView( + gateway: gateway, + sessionId: 's', + transcripts: transcripts, + onBack: () {}, + ), + ), + ); + await tester.pumpAndSettle(); + await tester.pumpWidget(host(const SizedBox())); + + // The session stays subscribed, so its reply still arrives. + gateway.emitEvent(chatTextFrame('reply while away', messageId: 'late')); + await tester.pump(); + final held = transcripts.read('s')!.messages; + expect(held.last['id'], 'late'); + expect((held.last['parts'] as List).single['text'], 'reply while away'); + }); + testWidgets('a conversation that fits its viewport offers no control', ( tester, ) async { diff --git a/app/test/features/chat/conversation/chat_transcript_cache_test.dart b/app/test/features/chat/conversation/chat_transcript_cache_test.dart index 280e9f98..76cbfb3a 100644 --- a/app/test/features/chat/conversation/chat_transcript_cache_test.dart +++ b/app/test/features/chat/conversation/chat_transcript_cache_test.dart @@ -79,6 +79,103 @@ void main() { }); }); + group('a transcript left while its session stays subscribed', () { + late FakeChatGateway gateway; + + setUp(() => gateway = FakeChatGateway()); + tearDown(() => gateway.close()); + + ChatTranscriptSnapshot left() => ChatTranscriptSnapshot( + messages: [ + _text('u1', 'user', 'question'), + _text('a1', 'assistant', 'first answer'), + ], + cursor: 'older', + hasMore: true, + ); + + test('folds the replies that arrive in the background', () async { + final cache = ChatTranscriptCache(); + cache.write('s', left(), frames: gateway.frames); + cache.write('other', _snapshot(1)); + + gateway.emitEvent(chatTextFrame('new ', messageId: 'a2')); + gateway.emitEvent(chatTextFrame('reply', messageId: 'a2')); + // Another session's frame and a non-event envelope change nothing. + gateway.emitEvent(chatTextFrame('elsewhere', session: 'x')); + gateway.emitRaw({'type': 'chat_queue', 'chat_queue': {}}); + await pumpEventQueue(); + + final held = cache.read('s')!; + expect(_ids(held.messages), ['u1', 'a1', 'a2']); + expect((held.messages.last['parts'] as List).single['text'], 'new reply'); + expect(held.cursor, 'older'); + expect(held.hasMore, isTrue); + expect(cache.messageCount, 4); + }); + + test('stops following once replaced, removed or cleared', () async { + final cache = ChatTranscriptCache(); + cache.write('s', left(), frames: gateway.frames); + cache.write('s', left()); + gateway.emitEvent(chatTextFrame('ignored', messageId: 'a2')); + await pumpEventQueue(); + expect(_ids(cache.read('s')!.messages), ['u1', 'a1']); + + cache.write('s', left(), frames: gateway.frames); + cache.remove('s'); + cache.write('t', left(), frames: gateway.frames); + cache.clear(); + gateway.emitEvent(chatTextFrame('ignored', messageId: 'a2')); + await pumpEventQueue(); + expect(cache.sessionIds, isEmpty); + expect(cache.messageCount, 0); + }); + + test('a growing transcript keeps the message bound', () async { + final cache = ChatTranscriptCache(maxMessages: 4); + cache.write('old', _snapshot(2, prefix: 'o')); + cache.write('s', left(), frames: gateway.frames); + gateway.emitEvent(chatTextFrame('reply', messageId: 'a2')); + await pumpEventQueue(); + expect(cache.sessionIds, ['s']); + expect(cache.messageCount, 3); + }); + + test('a reopened controller shows the background reply before its read ' + 'returns, and the page still replaces it', () async { + final cache = ChatTranscriptCache(); + cache.write('s', left(), frames: gateway.frames); + gateway.emitEvent(chatTextFrame('background reply', messageId: 'a2')); + await pumpEventQueue(); + + final controller = ChatThreadController( + gateway, + 's', + cached: cache.read('s'), + ); + addTearDown(controller.dispose); + expect(_ids(controller.messages), ['u1', 'a1', 'a2']); + + final load = controller.load(); + await pumpEventQueue(); + expect(_ids(controller.messages), ['u1', 'a1', 'a2']); + gateway.historyRequests.single.complete( + chatPage([ + _text('u1', 'user', 'question'), + _text('a1', 'assistant', 'first answer'), + _text('a2', 'assistant', 'recorded reply'), + ]), + ); + await load; + expect(_ids(controller.messages), ['u1', 'a1', 'a2']); + expect( + (controller.messages.last['parts'] as List).single['text'], + 'recorded reply', + ); + }); + }); + test('refreshCachedChatHistory lets the page decide and keeps live ' 'arrivals', () { final held = [