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))