import 'dart:async'; import 'package:flutter/widgets.dart'; import '../../core/api_gateway.dart'; import '../../core/servers/chat/chat_identity.dart'; import '../../core/servers/chat/federated_chat_gateway.dart'; import 'conversation/chat_efforts.dart'; import 'conversation/chat_models.dart'; import 'conversation/chat_row_widgets.dart'; import 'conversation/chat_scroll.dart'; import 'conversation/chat_transcript_cache.dart'; import 'conversation/composer_focus_request.dart'; import 'data/chat_repository.dart'; import 'ui/sessions/chat_sessions_body.dart'; import 'ui/sessions/chat_sessions_controller.dart'; /// What open chats share for one server, wherever they are shown (the Chat /// destination's tiling or a floating window): the session list, the rows /// opened so far, model switches the server accepted, transcript positions /// and caches, and composer focus requests. /// /// It notifies when a row a conversation is drawn from changes. class ChatRuntime extends ChangeNotifier { ChatRuntime({required ApiGateway gateway, this.serverKey = ''}) : _gateway = gateway, sessions = ChatSessionsController(ChatRepository(gateway)) { sessions.onSessionReplaced = (previousId, session) { for (final listener in _replaced.toList()) { listener(previousId, session); } }; } /// The server (or set of servers) these chats belong to; windows carry it. final String serverKey; /// Advances when the socket is replaced, for chats shown outside the Chat /// destination. final ValueNotifier syncToken = ValueNotifier(0); final List _replaced = []; /// Calls [listener] when another device moved a chat to a new session. void addSessionReplacedListener( void Function(String previousId, JsonMap session) listener, ) => _replaced.add(listener); void removeSessionReplacedListener( void Function(String previousId, JsonMap session) listener, ) => _replaced.remove(listener); final Map _viewKeys = {}; /// The key of [sessionId]'s live view, so it can move between the tiling /// and a window without being rebuilt. GlobalKey viewKey(String sessionId) => _viewKeys.putIfAbsent( sessionId, () => GlobalKey(debugLabel: 'chat view $sessionId'), ); ApiGateway _gateway; /// The gateway chats are read through. Transcripts read through another /// gateway belong to that server, so replacing it drops them. ApiGateway get gateway => _gateway; set gateway(ApiGateway value) { if (identical(_gateway, value)) return; _gateway = value; transcripts.clear(); } /// The gateway for one chat: its own server's on a federated gateway. ApiGateway gatewayFor(String sessionId) { final gateway = _gateway; return gateway is FederatedChatGateway ? gateway.forChat(sessionId) : gateway; } /// The id of the server [sessionId] lives on, or empty. String serverIdFor(String sessionId) => '${rowFor(sessionId)?['_server_id'] ?? parseFederatedChatId(sessionId)?.server ?? ''}'; /// The list's controller, shared with the mounted list screen. The list /// screen refreshes it on mount and swaps its repository when the socket /// is replaced. final ChatSessionsController sessions; /// The list's folded sections, so Next chat counts the rows the list /// draws. final ChatSectionFolds folds = ChatSectionFolds(); /// Rows opened so far, used for the title and the recorded model facts. /// The mounted list also reports its loaded rows, so a routed id (a deep /// link) resolves the same row without a second list request. final Map opened = {}; /// Each row as the list last reported it (without its live `running`), so /// [adoptRows] adopts only what a re-read changed. final Map _listed = {}; /// Model switches the server accepted after a row was opened. The row that /// opened the conversation may still carry the pre-switch model, so these /// win, including when the same chat is reopened. final Map _acceptedModels = {}; /// Transcript positions, so Back and a reopened chat return to the same /// place. final ChatScrollStore scrollPositions = MemoryChatScrollStore(); /// Transcripts of recently left chats, 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(); /// Puts the keyboard in an opened chat's composer once it is built. final ChatComposerFocusRequests composerFocus = ChatComposerFocusRequests(); /// 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. ({String id, String notice})? startNotice; /// The row to open for [id], with an accepted model folded in. JsonMap? rowFor(String id) { final row = opened[id] ?? _listed[id]; final accepted = _acceptedModels[id]; if (row == null || accepted == null) return row; return { ...row, 'model': accepted.model, 'model_provider': accepted.provider, 'model_selection': accepted.selection, }; } /// [id]'s title as shown on a pane or window, else the id. String titleFor(String id) => '${rowFor(id)?['title'] ?? id}'; void modelChanged(String id, ChatModelSelection applied) { _acceptedModels[id] = applied; notifyListeners(); } /// An accepted mode switch updates the opened row, so reopening the chat /// shows it before the list re-reads. Returns false when [id] has no /// opened row. bool modeChanged(String id, String mode, String name) { final row = opened[id]; if (row == null) return false; opened[id] = {...row, 'mode': mode, 'mode_name': name}; notifyListeners(); return true; } /// An accepted thinking level updates the opened row like a mode switch. bool effortChanged(String id, ChatEffortState state) { final row = opened[id]; if (row == null) return false; opened[id] = state.applyTo(row); notifyListeners(); return true; } /// An accepted mode switch also re-reads the list, so a listing already /// in flight from before the switch is superseded rather than adopted over /// the accepted mode. void acceptMode(String id, String mode, String name) { if (modeChanged(id, mode, name)) unawaited(sessions.refresh()); } void acceptEffort(String id, ChatEffortState state) { if (effortChanged(id, state)) unawaited(sessions.refresh()); } /// `/rename` was accepted: the opened row follows the shared title and the /// list re-reads it. void acceptRename(String id, String title) { renamed(id, title); unawaited(sessions.refresh()); } /// `/rename` was accepted for [id]: the opened row follows the title. void renamed(String id, String title) { final row = opened[id]; if (row == null) return; opened[id] = {...row, 'title': title}; notifyListeners(); } /// The chat [previousId] moved to the new session [session] (`/new`): it /// opens under its new id on the server's row, which carries every shared /// field (an omitted one is unset, so the old row is not merged in), on /// [notice]. A model switch accepted for the old id moves with the chat. void movedToSession(String previousId, JsonMap session, String notice) { final id = '${session['id'] ?? ''}'; final accepted = _acceptedModels[previousId]; if (accepted != null) _acceptedModels[id] = accepted; startNotice = (id: id, notice: notice); opened[id] = {...session}..remove('running'); } /// Adopts the list's loaded [rows] for [selected], for every chat in /// [retained] and for every opened row. Only a listed row that changed /// since the list last reported it is adopted, so an unchanged (or still /// loading) listing never reverts a mode or model just accepted. Fields /// only the opened row carries (a create's instruction status) are kept. /// The list's live `running` flag is ignored: the conversation tracks its /// own turn, and following it would rebuild the open thread at every turn. void adoptRows( List rows, { required String? selected, required Set retained, }) { final next = {}; for (final row in rows) { final id = '${row['id'] ?? ''}'; if (id.isEmpty) continue; final listed = {...row}..remove('running'); final previous = _listed[id]; _listed[id] = listed; final was = opened[id]; if (was == null && id != selected && !retained.contains(id)) continue; if (was != null && chatJsonEquals(previous, listed)) continue; final adopted = {...?was, ...listed}; if (was != null && was.containsKey('running')) { adopted['running'] = was['running']; } if (!chatJsonEquals(was, adopted)) next[id] = adopted; } if (next.isEmpty) return; opened.addAll(next); notifyListeners(); } @override void dispose() { _replaced.clear(); syncToken.dispose(); sessions.dispose(); folds.dispose(); composerFocus.dispose(); super.dispose(); } }