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 messages, this.cursor = '', this.hasMore = false, }) : messages = List.unmodifiable(messages); final List 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 _entries = LinkedHashMap(); int _messageCount = 0; /// The cached sessions, least recently used first. List 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; } }