Files
pipelines/app/lib/features/chat/chat_runtime.dart
T
alan 558eedb410 Extract ChatRuntime from the Chat screen
Phase 2.1 of docs/plans/floating-windows.md. The session list controller,
opened rows, accepted models, transcript positions and caches, composer
focus requests and list folds move from ChatScreen's state to ChatRuntime.
ChatScreen builds its own unless one is passed; behaviour is unchanged.
2026-11-10 21:00:21 +00:00

192 lines
7.3 KiB
Dart

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<String, JsonMap> opened = {};
/// Each row as the list last reported it (without its live `running`), so
/// [adoptRows] adopts only what a re-read changed.
final Map<String, JsonMap> _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<String, ChatModelSelection> _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] = <String, dynamic>{...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<JsonMap> rows, {
required String? selected,
required Set<String> retained,
}) {
final next = <String, JsonMap>{};
for (final row in rows) {
final id = '${row['id'] ?? ''}';
if (id.isEmpty) continue;
final listed = <String, dynamic>{...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 = <String, dynamic>{...?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();
}
}