Show a reopened chat's last transcript while it refreshes

ChatScreen keeps a bounded in-memory cache of recently left transcripts
(16 chats / 4000 messages, LRU). A reopened chat is seeded from it with no
loading state, still re-subscribes and re-reads, and the newest page replaces
the cached copy while live frames received during the read are kept. /close
removes the entry; only transcripts backed by a successful read on the
current connection are written.

Adds tool/chat_reopen_probe.mjs and an optional history delay in the loopback
fixture. Measurement shows a second cost the cache does not remove: opening at
the end of the top-anchored transcript lays out every row (notes).
This commit is contained in:
2026-10-24 18:14:27 +01:00
parent ef575898f2
commit 0a19ef229f
12 changed files with 887 additions and 8 deletions
@@ -7,6 +7,7 @@ import '../data/chat_repository.dart';
import '../domain/chat_sessions.dart';
import '../domain/chat_transcript.dart';
import 'chat_thread_cards.dart';
import 'chat_transcript_cache.dart';
/// One open conversation's transcript and live turn state.
///
@@ -20,8 +21,27 @@ import 'chat_thread_cards.dart';
///
/// Approval requests and question forms are recorded cards rather than
/// messages; [ChatThreadCards] owns their frames, answers and send gates.
///
/// A [cached] transcript from an earlier visit is shown at once instead of a
/// loading state, but it is only a starting point: [load] still subscribes and
/// reads, and the newest page replaces every cached message no live frame has
/// changed since (see [refreshCachedChatHistory]).
class ChatThreadController extends ChangeNotifier {
ChatThreadController(this.gateway, this.sessionId) {
ChatThreadController(
this.gateway,
this.sessionId, {
ChatTranscriptSnapshot? cached,
}) {
if (cached != null) {
_messages = cached.messages;
_cursor = cached.cursor;
_hasMore = cached.hasMore;
_loaded = true;
_untouchedCached = {
for (final message in cached.messages)
if (message['id'] != null) message['id'] as Object,
};
}
_subscription = gateway.frames.listen(_onFrame);
}
@@ -55,6 +75,28 @@ class ChatThreadController extends ChangeNotifier {
bool _resyncing = false;
bool _resyncAgain = false;
/// Ids of cached messages that no frame or read has confirmed yet; null once
/// a read replaced the cached transcript, or when there was none.
Set<Object>? _untouchedCached;
/// True while the held transcript came from a successful read on the current
/// connection; a socket gap clears it until the repair's read succeeds.
bool _authoritative = false;
/// Whether this visit opened on a cached transcript that no read has
/// replaced yet.
bool get showingCached => _untouchedCached != null;
/// The transcript to keep for a later visit, or null when the held one is
/// not backed by a successful read on the current connection.
ChatTranscriptSnapshot? get snapshot => _authoritative
? ChatTranscriptSnapshot(
messages: _messages,
cursor: _cursor,
hasMore: _hasMore,
)
: null;
List<JsonMap> get messages => _messages;
/// Usage-only snapshots refresh Info, not the expensive transcript tree.
@@ -167,6 +209,7 @@ class ChatThreadController extends ChangeNotifier {
_running = false;
_nativeTurnId = '';
_liveAssistantMessageId = null;
_authoritative = false;
_notify();
await _attach(force: true);
if (!_owned(token)) return;
@@ -184,11 +227,17 @@ class ChatThreadController extends ChangeNotifier {
.toList();
_cursor = '${page['nextCursor'] ?? ''}';
_hasMore = page['hasMore'] == true;
} else if (_untouchedCached case final untouched?) {
// The cached transcript was a placeholder: the page decides what it
// still holds, and live arrivals since reopening are kept after it.
_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));
}
_untouchedCached = null;
_authoritative = true;
_loaded = true;
_loading = false;
_error = null;
@@ -255,6 +304,9 @@ class ChatThreadController extends ChangeNotifier {
final current = _thread;
final next = applyChatEvent(current, body);
if (identical(next, current)) return;
// A frame for a cached message is fresh state the next read must not drop.
final changed = body['message_id'];
if (changed != null) _untouchedCached?.remove(changed);
_messages = (next['messages'] as List? ?? const [])
.whereType<Map>()
.map((message) => Map<String, dynamic>.from(message))
@@ -25,6 +25,7 @@ import 'chat_models.dart';
import 'chat_row_keys.dart';
import 'chat_scroll.dart';
import 'chat_thread_controller.dart';
import 'chat_transcript_cache.dart';
import 'chat_permission_card_model.dart';
import 'chat_permission_group.dart';
import 'chat_transcript_card.dart';
@@ -53,6 +54,7 @@ class ChatThreadView extends StatefulWidget {
this.newOperationId,
this.attachmentPicker,
this.scrollPositions,
this.transcripts,
this.initialNotice,
this.onCreatedSession,
this.onSessionRenamed,
@@ -107,6 +109,12 @@ class ChatThreadView extends StatefulWidget {
/// the operator left it. Null keeps the view stateless across visits.
final ChatScrollStore? scrollPositions;
/// The destination's recently left transcripts. A conversation found here
/// opens on that transcript instead of a loading state while its newest page
/// is read; leaving writes back the transcript the last successful read
/// produced. Null opens every visit from the server alone.
final ChatTranscriptCache? transcripts;
@override
State<ChatThreadView> createState() => _ChatThreadViewState();
}
@@ -180,8 +188,40 @@ class _ChatThreadViewState extends State<ChatThreadView> {
/// counted against it for the jump control's arrival count.
String? _newestAtRelease;
ChatThreadController _attach() =>
ChatThreadController(widget.gateway, widget.sessionId)..load();
ChatThreadController _attach() => ChatThreadController(
widget.gateway,
widget.sessionId,
cached: widget.transcripts?.read(widget.sessionId),
)..load();
/// `/close` finished this conversation; its transcript is not kept.
bool _closed = false;
/// A cached transcript is from before this visit's subscription, like one
/// held across a socket gap: no running turn or compaction is drawn from it
/// until a read or frame replaces it.
void _adoptCachedTranscript() {
_preGapMessages = _controller.showingCached ? _controller.messages : null;
}
/// 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) {
if (cache == null) return;
if (_closed) {
cache.remove(sessionId);
return;
}
final snapshot = _controller.snapshot;
if (snapshot != null) cache.write(sessionId, snapshot);
}
void _sessionClosed() {
_closed = true;
widget.transcripts?.remove(widget.sessionId);
widget.onSessionClosed?.call();
}
ChatComposerController _attachComposer() => ChatComposerController(
widget.gateway,
@@ -282,7 +322,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
openCreatedSession:
onCreated ?? (created, notice) => _showCommandNotice(notice),
onRenamed: widget.onSessionRenamed,
onClosed: widget.onSessionClosed,
onClosed: _sessionClosed,
newOperationId: widget.newOperationId,
);
}
@@ -291,6 +331,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
void initState() {
super.initState();
_savedOffset = widget.scrollPositions?.read(widget.sessionId);
_adoptCachedTranscript();
_seedCommandNotice();
}
@@ -301,14 +342,19 @@ class _ChatThreadViewState extends State<ChatThreadView> {
oldWidget.sessionId != widget.sessionId) {
// The conversation being left keeps the position the operator chose.
_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);
}
_controller.dispose();
_composer.dispose();
_closed = false;
_controller = _attach();
_composer = _attachComposer();
_rowKeys = ChatRowKeys();
_dismissals = ChatNoticeDismissals();
_reconnecting = false;
_preGapMessages = null;
_adoptCachedTranscript();
_syncGeneration++;
_commandNotices.clear();
_seedCommandNotice();
@@ -355,6 +401,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
@override
void dispose() {
_persistPosition();
_saveTranscript(widget.transcripts, widget.sessionId);
_scroll.dispose();
_composer.dispose();
_controller.dispose();
@@ -0,0 +1,71 @@
import 'dart:collection';
import '../../../core/api_gateway.dart';
/// The newest transcript one conversation view held when it was left.
///
/// It is a starting point for the next visit, never a final state: a reopened
/// conversation still subscribes and reads its newest page, which replaces it.
class ChatTranscriptSnapshot {
ChatTranscriptSnapshot({
required List<JsonMap> messages,
this.cursor = '',
this.hasMore = false,
}) : messages = List.unmodifiable(messages);
final List<JsonMap> messages;
/// The server's opaque older-page cursor that matched [messages].
final String cursor;
final bool hasMore;
}
/// Transcripts of recently left conversations, kept in memory by the chat
/// destination for the rest of the app session, like its scroll positions.
///
/// 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
/// disk, so a restarted app opens every conversation from the server.
class ChatTranscriptCache {
ChatTranscriptCache({this.maxSessions = 16, this.maxMessages = 4000});
final int maxSessions;
final int maxMessages;
/// Least recently used first.
final LinkedHashMap<String, ChatTranscriptSnapshot> _entries =
LinkedHashMap();
int _messageCount = 0;
/// The cached sessions, least recently used first.
List<String> get sessionIds => List.unmodifiable(_entries.keys);
int get messageCount => _messageCount;
/// The transcript [sessionId] was left with, marking it recently used.
ChatTranscriptSnapshot? read(String sessionId) {
final snapshot = _entries.remove(sessionId);
if (snapshot != null) _entries[sessionId] = snapshot;
return snapshot;
}
void write(String sessionId, ChatTranscriptSnapshot snapshot) {
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);
}
}
void remove(String sessionId) {
final removed = _entries.remove(sessionId);
if (removed != null) _messageCount -= removed.messages.length;
}
void clear() {
_entries.clear();
_messageCount = 0;
}
}
@@ -32,6 +32,29 @@ JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) {
};
}
/// Replaces a transcript that opened from this visit's cached copy with the
/// newest authoritative page.
///
/// [held] is what the view shows: the cached messages plus anything a live
/// frame or a local send added or changed since the conversation reopened.
/// [untouchedCached] names the cached messages nothing has changed since; they
/// are not evidence of the current state, so the page alone decides whether
/// they still exist. The page's messages lead in its order with its copies
/// winning, then live arrivals the page does not hold yet follow in their own
/// order, so a frame received during the read is never dropped.
JsonMap refreshCachedChatHistory(
List<JsonMap> held,
JsonMap page,
Set<Object> untouchedCached,
) {
final live = [
for (final message in held)
if (message['id'] == null || !untouchedCached.contains(message['id']))
message,
];
return mergeChatHistory({'messages': live}, page, older: true);
}
/// Consecutive assistant messages form one answer turn. All part fields (also
/// future/unknown protocol types) are preserved in original order.
///
+14
View File
@@ -11,6 +11,7 @@ import '../../core/api_gateway.dart';
import 'conversation/chat_models.dart';
import 'conversation/chat_scroll.dart';
import 'conversation/chat_thread_view.dart';
import 'conversation/chat_transcript_cache.dart';
import 'data/chat_repository.dart';
import 'ui/sessions/chat_sessions_controller.dart';
import 'ui/sessions/chat_sessions_screen.dart';
@@ -72,6 +73,11 @@ class _ChatScreenState extends State<ChatScreen> {
/// conversation view, so Back and a reopened chat return to the same place.
final ChatScrollStore _scrollPositions = MemoryChatScrollStore();
/// Transcripts of recently left chats for this visit, so a reopened chat
/// shows its last transcript at once while it re-subscribes and re-reads.
/// Bounded and in memory only; see [ChatTranscriptCache].
final ChatTranscriptCache _transcripts = ChatTranscriptCache();
/// The line a just-created conversation opens on, tied to the selection
/// `/new` made. Leaving that conversation drops it, so a later reopen is an
/// ordinary visit.
@@ -171,6 +177,13 @@ class _ChatScreenState extends State<ChatScreen> {
/// On a phone the open chat is a real page above the main screen.
final DetailPageHost _page = DetailPageHost();
@override
void didUpdateWidget(covariant ChatScreen oldWidget) {
super.didUpdateWidget(oldWidget);
// Transcripts read through another gateway belong to that server.
if (oldWidget.gateway != widget.gateway) _transcripts.clear();
}
@override
void dispose() {
_page.dispose();
@@ -189,6 +202,7 @@ class _ChatScreenState extends State<ChatScreen> {
session: row,
syncToken: widget.syncToken,
scrollPositions: _scrollPositions,
transcripts: _transcripts,
initialNotice: start != null && start.id == selected
? start.notice
: null,