diff --git a/app/lib/features/chat/chat_runtime.dart b/app/lib/features/chat/chat_runtime.dart new file mode 100644 index 00000000..7f43fb30 --- /dev/null +++ b/app/lib/features/chat/chat_runtime.dart @@ -0,0 +1,191 @@ +import 'package:flutter/foundation.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}) + : _gateway = gateway, + sessions = ChatSessionsController(ChatRepository(gateway)); + + 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; + } + + /// `/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() { + sessions.dispose(); + folds.dispose(); + composerFocus.dispose(); + super.dispose(); + } +} diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index ce5f131b..cc6d16aa 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -1,5 +1,5 @@ +import 'chat_runtime.dart'; import 'workspace/federated_workspace_store.dart'; -import '../../core/servers/chat/chat_identity.dart'; import '../../core/servers/chat/federated_chat_gateway.dart'; import '../../core/servers/server_context.dart'; import '../../shell/destination.dart'; @@ -40,13 +40,9 @@ import 'workspace/chat_center_stage_keys.dart'; import 'workspace/chat_pane_move_actions.dart'; import 'workspace/chat_workspace_entrance.dart'; import 'ui/sessions/chat_adaptive.dart'; -import 'conversation/chat_row_widgets.dart'; -import 'conversation/chat_scroll.dart'; import 'conversation/chat_thread_view.dart'; -import 'conversation/chat_transcript_cache.dart'; import 'conversation/composer_focus_request.dart'; import 'conversation/composer_selection_focus.dart'; -import 'data/chat_repository.dart'; import 'domain/chat_commands.dart'; import 'domain/chat_cycle.dart'; import '../terminal/terminal_scope.dart'; @@ -80,11 +76,16 @@ class ChatScreen extends StatefulWidget { this.onWorkspaceEmpty, this.onAvailableSessionsChanged, this.persistWorkspace = false, + this.runtime, }); final ApiGateway gateway; final bool persistWorkspace; + /// The chats' shared state, kept by the app beyond this screen; the screen + /// keeps its own for the visit when null. + final ChatRuntime? runtime; + /// The chat session the current route names, or null for the list. final String? initialSessionId; @@ -103,53 +104,23 @@ class ChatScreen extends StatefulWidget { class _ChatScreenState extends State with _ChatScreenWorkspace, _ChatScreenKeys, _ChatScreenFloat { - /// 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; this destination lists created rows and re-reads after a - /// conversation's command changes a session. - late final ChatSessionsController _sessions = ChatSessionsController( - ChatRepository(widget.gateway), - )..onSessionReplaced = _replacedElsewhere; + /// The chats' shared state: the list, opened rows, accepted models, + /// transcript positions and caches (see [ChatRuntime]). + late final ChatRuntime _runtime = + widget.runtime ?? ChatRuntime(gateway: widget.gateway); - /// Rows this visit has opened, used for the native 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. + ChatSessionsController get _sessions => _runtime.sessions; @override - final Map _openedSessions = {}; - - /// Each row as the list last reported it (without its live `running`), so - /// [_adoptRows] adopts only what a re-read changed. - final Map _listedRows = {}; - - /// 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 - /// for the rest of this visit, including when the same chat is reopened. - final Map _acceptedModels = {}; - - /// Transcript positions for this visit. It lives with the destination, not a - /// 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. - ({String id, String notice})? _startNotice; + Map get _openedSessions => _runtime.opened; String? _standaloneSelection; /// Ctrl+1…Ctrl+9 put the keyboard in the opened chat's composer; choosing a /// chat does too where [chatSelectionFocusesComposer] allows. @override - final ChatComposerFocusRequests _composerFocus = ChatComposerFocusRequests(); + ChatComposerFocusRequests get _composerFocus => _runtime.composerFocus; - /// The list's folded sections, kept here so Next chat counts the rows the - /// list draws. - final ChatSectionFolds _folds = ChatSectionFolds(); + ChatSectionFolds get _folds => _runtime.folds; /// Whether the last build offered Next chat, so a list change rebuilds only /// when that changes. @@ -165,6 +136,10 @@ class _ChatScreenState extends State @override void initState() { super.initState(); + _runtime + ..gateway = widget.gateway + ..addListener(_runtimeChanged); + _sessions.onSessionReplaced = _replacedElsewhere; final initial = widget.initialSessionId; if (initial != null && initial.isNotEmpty) { _workspace.open(initial); @@ -184,6 +159,11 @@ class _ChatScreenState extends State _folds.addListener(_nextChanged); } + /// A row an open conversation is drawn from changed. + void _runtimeChanged() { + if (mounted) setState(() {}); + } + /// The chat after [id] as the list draws it (Starred, then Chats by /// directory, then Closed, skipping folded sections), wrapping around. The /// embedded list has no search field, so no query narrows it. @@ -255,7 +235,7 @@ class _ChatScreenState extends State _openedSessions[id] = session; _workspaceVisible = true; _workspace.open(id); - if (_startNotice?.id != id) _startNotice = null; + if (_runtime.startNotice?.id != id) _runtime.startNotice = null; final select = widget.onSessionSelected; if (select != null) { if (_publishedWorkspaceSession != id) { @@ -289,23 +269,16 @@ class _ChatScreenState extends State /// shared field (an omitted one is unset, so the old row is not merged in). /// A model switch accepted here in this visit moved with the chat. void _followNewSession(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); - _openedSessions[id] = {...session}..remove('running'); + _runtime.movedToSession(previousId, session, notice); _forgetRecentSession(previousId); - _workspace.replaceSession(previousId, id); + _workspace.replaceSession(previousId, '${session['id'] ?? ''}'); if (_workspace.paneCount == 0) _open(session); } /// `/rename` was accepted for [id]: the opened row follows the shared title /// and the list re-reads it. void _renamed(String id, String title) { - final row = _openedSessions[id]; - if (row != null) { - setState(() => _openedSessions[id] = {...row, 'title': title}); - } + _runtime.renamed(id, title); unawaited(_sessions.refresh()); } @@ -348,31 +321,15 @@ class _ChatScreenState extends State if (row['closed_at'] == null && row['closed'] != true) '${row['id'] ?? ''}', }); - final selected = _selected; - final retained = _workspace.panes.map((pane) => pane.sessionId).toSet(); - final next = {}; - for (final row in rows) { - final id = '${row['id'] ?? ''}'; - if (id.isEmpty) continue; - final listed = {...row}..remove('running'); - final previous = _listedRows[id]; - _listedRows[id] = listed; - final opened = _openedSessions[id]; - if (opened == null && id != selected && !retained.contains(id)) continue; - if (opened != null && chatJsonEquals(previous, listed)) continue; - final adopted = {...?opened, ...listed}; - if (opened != null && opened.containsKey('running')) { - adopted['running'] = opened['running']; - } - if (!chatJsonEquals(opened, adopted)) next[id] = adopted; - } - if (next.isEmpty) return; - setState(() => _openedSessions.addAll(next)); + _runtime.adoptRows( + rows, + selected: _selected, + retained: _workspace.panes.map((pane) => pane.sessionId).toSet(), + ); } void _modelChanged(String id, ChatModelSelection applied) { - if (!mounted) return; - setState(() => _acceptedModels[id] = applied); + if (mounted) _runtime.modelChanged(id, applied); } /// An accepted mode switch updates the opened row, so reopening the chat in @@ -380,41 +337,24 @@ class _ChatScreenState extends State /// a listing already in flight from before the switch is superseded rather /// than adopted over the accepted mode. void _modeChanged(String id, String mode, String name) { - final row = _openedSessions[id]; - if (!mounted || row == null) return; - setState( - () => _openedSessions[id] = {...row, 'mode': mode, 'mode_name': name}, - ); + if (!mounted || !_runtime.modeChanged(id, mode, name)) return; unawaited(_sessions.refresh()); } /// An accepted thinking level updates the opened row like a mode switch. void _effortChanged(String id, ChatEffortState state) { - final row = _openedSessions[id]; - if (!mounted || row == null) return; - setState(() => _openedSessions[id] = state.applyTo(row)); + if (!mounted || !_runtime.effortChanged(id, state)) return; unawaited(_sessions.refresh()); } - /// The row to open for [id], with an accepted model folded in. @override - JsonMap? _rowFor(String id) { - final row = _openedSessions[id] ?? _listedRows[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, - }; - } + JsonMap? _rowFor(String id) => _runtime.rowFor(id); @override void _back() { _workspaceVisible = false; _publishedWorkspaceSession = null; - _startNotice = null; + _runtime.startNotice = null; _composerFocus.cancel(); if (_workspace.paneCount == 0) widget.onWorkspaceEmpty?.call(); final back = widget.onBack; @@ -454,7 +394,7 @@ class _ChatScreenState extends State } } // Transcripts read through another gateway belong to that server. - if (oldWidget.gateway != widget.gateway) _transcripts.clear(); + _runtime.gateway = widget.gateway; } @override @@ -468,9 +408,13 @@ class _ChatScreenState extends State _workspace.dispose(); _sessions.removeListener(_nextChanged); _sessions.removeListener(_availableSessionsChanged); - _sessions.dispose(); - _folds.dispose(); - _composerFocus.dispose(); + _folds.removeListener(_nextChanged); + _runtime.removeListener(_runtimeChanged); + if (widget.runtime == null) { + _runtime.dispose(); + } else { + _sessions.onSessionReplaced = null; + } super.dispose(); } @@ -482,18 +426,16 @@ class _ChatScreenState extends State BuildContext? paneContext, }) { final row = _rowFor(selected); - final start = _startNotice; + final start = _runtime.startNotice; final thread = ChatThreadView( key: ValueKey('chat-session-$selected'), - gateway: widget.gateway is FederatedChatGateway - ? (widget.gateway as FederatedChatGateway).forChat(selected) - : widget.gateway, + gateway: _runtime.gatewayFor(selected), sessionId: selected, title: '${row?['title'] ?? ''}'.trim(), session: row, syncToken: widget.syncToken, - scrollPositions: _scrollPositions, - transcripts: _transcripts, + scrollPositions: _runtime.scrollPositions, + transcripts: _runtime.transcripts, initialNotice: start != null && start.id == selected ? start.notice : null, @@ -557,7 +499,7 @@ class _ChatScreenState extends State requests: _composerFocus, child: ServerContext.forServer( context, - '${row?['_server_id'] ?? parseFederatedChatId(selected)?.server ?? ''}', + _runtime.serverIdFor(selected), thread, ), ); diff --git a/app/test/features/chat/chat_runtime_test.dart b/app/test/features/chat/chat_runtime_test.dart new file mode 100644 index 00000000..4308bae6 --- /dev/null +++ b/app/test/features/chat/chat_runtime_test.dart @@ -0,0 +1,85 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/chat_runtime.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_models.dart'; + +class _Gateway implements ApiGateway { + @override + Stream get frames => const Stream.empty(); + @override + Future call(String type, [JsonMap fields = const {}]) async => {}; +} + +void main() { + late ChatRuntime runtime; + late int notified; + setUp(() { + runtime = ChatRuntime(gateway: _Gateway()); + notified = 0; + runtime.addListener(() => notified++); + }); + tearDown(() => runtime.dispose()); + + test('adopts listed rows for opened, selected and retained chats only', () { + runtime.opened['a'] = {'id': 'a', 'title': 'Old', 'running': true}; + runtime.adoptRows( + [ + {'id': 'a', 'title': 'New', 'running': false}, + {'id': 'b', 'title': 'B'}, + {'id': 'c', 'title': 'C'}, + {'id': 'd', 'title': 'D'}, + ], + selected: 'b', + retained: {'c'}, + ); + // The conversation keeps its own running flag. + expect(runtime.opened['a'], {'id': 'a', 'title': 'New', 'running': true}); + expect(runtime.opened.keys, ['a', 'b', 'c']); + expect(notified, 1); + // A chat that is only listed still resolves its row. + expect(runtime.rowFor('d')?['title'], 'D'); + expect(runtime.titleFor('zz'), 'zz'); + }); + + test('an unchanged listing never reverts an accepted mode', () { + final rows = [ + {'id': 'a', 'mode': 'ask'}, + ]; + runtime.adoptRows(rows, selected: 'a', retained: const {}); + expect(runtime.modeChanged('a', 'auto', 'Auto'), isTrue); + runtime.adoptRows(rows, selected: 'a', retained: const {}); + expect(runtime.opened['a']?['mode'], 'auto'); + expect(notified, 2); + expect(runtime.modeChanged('missing', 'auto', 'Auto'), isFalse); + }); + + test('an accepted model wins over the row and follows /new', () { + runtime.opened['a'] = {'id': 'a', 'model': 'old'}; + runtime.modelChanged('a', ( + provider: 'p', + model: 'new', + selection: 'p/new', + )); + expect(runtime.rowFor('a')?['model'], 'new'); + runtime.movedToSession('a', {'id': 'b', 'running': true}, 'Started'); + expect(runtime.rowFor('b'), { + 'id': 'b', + 'model': 'new', + 'model_provider': 'p', + 'model_selection': 'p/new', + }); + expect(runtime.startNotice, (id: 'b', notice: 'Started')); + }); + + test('rename updates the opened row; a new gateway drops transcripts', () { + runtime.opened['a'] = {'id': 'a', 'title': 'Old'}; + runtime.renamed('a', 'New'); + expect(runtime.titleFor('a'), 'New'); + expect(notified, 1); + final other = _Gateway(); + runtime.gateway = other; + expect(runtime.gateway, same(other)); + expect(runtime.gatewayFor('a'), same(other)); + expect(runtime.serverIdFor('a'), ''); + }); +}