cf4579ab15
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 <noreply@anthropic.com>
135 lines
4.8 KiB
Dart
135 lines
4.8 KiB
Dart
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.
|
|
///
|
|
/// 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.
|
|
///
|
|
/// 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
|
|
/// 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();
|
|
final Map<String, StreamSubscription<JsonMap>> _follows = {};
|
|
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;
|
|
}
|
|
|
|
/// 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<JsonMap>? frames,
|
|
}) {
|
|
remove(sessionId);
|
|
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<String, dynamic>.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);
|
|
}
|
|
}
|
|
}
|