import '../../shell/destination.dart'; import '../../shell/detail_page.dart'; import '../../shell/empty_detail_pane.dart'; import '../../shell/list_detail.dart'; import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import '../../core/api_gateway.dart'; import 'conversation/chat_models.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 'data/chat_repository.dart'; import 'domain/chat_commands.dart'; import 'domain/chat_cycle.dart'; import 'ui/sessions/chat_sessions_body.dart'; import 'ui/sessions/chat_sessions_controller.dart'; import 'ui/sessions/chat_sessions_screen.dart'; /// The Chat destination's list/detail switch. /// /// The route names the open session, so a row tap, a deep link and Back all /// navigate through the same value. The session list stays mounted (offstage) /// while a conversation is open, so returning to it keeps its rows and query. /// The destination owns the list controller too, so a session a conversation's /// `/new` creates is listed, opened and refreshed from here. /// The shell owns the app bar; this screen adds no second one. class ChatScreen extends StatefulWidget { const ChatScreen({ super.key, required this.gateway, this.initialSessionId, this.syncToken = 0, this.onSessionSelected, this.onBack, }); final ApiGateway gateway; /// The chat session the current route names, or null for the list. final String? initialSessionId; /// Advances when the shared socket is replaced. The open conversation /// re-subscribes and re-reads in place, so its selection survives. final int syncToken; final ValueChanged? onSessionSelected; final VoidCallback? onBack; @override State createState() => _ChatScreenState(); } class _ChatScreenState extends State { /// 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; /// 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. 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; String? _standaloneSelection; /// Ctrl+1…Ctrl+9 put the keyboard in the opened chat's composer. final ChatComposerFocusRequests _composerFocus = ChatComposerFocusRequests(); /// The list's folded sections, kept here so Next chat counts the rows the /// list draws. final ChatSectionFolds _folds = ChatSectionFolds(); /// Whether the last build offered Next chat, so a list change rebuilds only /// when that changes. bool _offeredNext = false; @override void initState() { super.initState(); _sessions.addListener(_nextChanged); _folds.addListener(_nextChanged); } /// 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. JsonMap? _nextAfter(String id) => chatSessionAfter( chatSessionsShown(_sessions.sessions, query: '', isOpen: _folds.isOpen), id, ); /// Next chat opens that row exactly as a tap on it would. void _openNext(String id) { final next = _nextAfter(id); if (next != null) _open(next); } void _nextChanged() { if (!mounted) return; final id = _selected; final offered = id != null && _nextAfter(id) != null; if (offered == _offeredNext) return; // The list may load while it builds; rebuild after that frame. if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) { WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) setState(() {}); }); } else { setState(() {}); } } String? get _selected { final routed = widget.initialSessionId; if (routed != null && routed.isNotEmpty) return routed; return _standaloneSelection; } /// Opens [session] from the keyboard: its composer takes focus once built, /// also when it is the chat already open. void _openByShortcut(JsonMap session) => _open(session, focusComposer: true); void _open(JsonMap session, {bool focusComposer = false}) { final id = '${session['id'] ?? ''}'; if (id.isEmpty) return; if (focusComposer) { _composerFocus.request(id); } else { _composerFocus.cancel(); } _openedSessions[id] = session; if (_startNotice?.id != id) _startNotice = null; final select = widget.onSessionSelected; if (select != null) { select(id); } else { setState(() => _standaloneSelection = id); } } /// `/new` moved the chat [previousId] to a fresh session: [session] takes /// its list row, the fresh conversation opens on [notice], then the list /// re-reads from the server. void _startedNewSession(String previousId, JsonMap session, String notice) { final id = '${session['id'] ?? ''}'; if (id.isEmpty) return; _sessions.replaceSession(previousId, session); _followNewSession(previousId, session, notice); unawaited(_sessions.refresh()); } /// Another device started a new session in a chat: only an open chat /// follows it; the list already swapped the row. void _replacedElsewhere(String previousId, JsonMap session) { if (!mounted || _selected != previousId) return; _followNewSession(previousId, session, chatNewSessionElsewhereNotice); } /// Opens the chat 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). /// 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); _open({...session}..remove('running')); } /// `/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}); } unawaited(_sessions.refresh()); } /// `/close` was accepted: the conversation leaves, back to the list, which /// re-reads the closed row. void _closed() { _back(); unawaited(_sessions.refresh()); } /// Adopts the list's loaded rows for the routed session and for every row /// this visit has opened. A deep link opens the conversation before any row /// has been tapped, and a created or long-open row can predate facts the /// list has since read (its mode, a mode another device chose, a title). /// The header's title, model and mode controls come from that row, so the /// open conversation follows each re-read instead of waiting to be reopened. /// 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 this visit has 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. Called after a frame, never during /// the list's own build. void _adoptRows(List rows) { if (!mounted) return; final selected = _selected; 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) 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)); } void _modelChanged(String id, ChatModelSelection applied) { if (!mounted) return; setState(() => _acceptedModels[id] = applied); } /// An accepted mode switch updates the opened row, so reopening the chat in /// this visit shows it before the list re-reads. The list then re-reads, so /// 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}, ); unawaited(_sessions.refresh()); } /// The row to open for [id], with an accepted model folded in. JsonMap? _rowFor(String id) { final row = _openedSessions[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, }; } void _back() { _startNotice = null; _composerFocus.cancel(); final back = widget.onBack; if (back != null) { back(); } else { setState(() => _standaloneSelection = null); } } /// On a phone the open chat is a real page above the main screen. final DetailPageHost _page = DetailPageHost(); @override void didUpdateWidget(covariant ChatScreen oldWidget) { super.didUpdateWidget(oldWidget); // Transcripts read through another gateway belong to that server. if (oldWidget.gateway != widget.gateway) _transcripts.clear(); } @override void dispose() { _page.dispose(); _sessions.dispose(); _folds.dispose(); _composerFocus.dispose(); super.dispose(); } Widget _thread(String selected, VoidCallback onBack) { final row = _rowFor(selected); final start = _startNotice; final thread = ChatThreadView( key: ValueKey('chat-session-$selected'), gateway: widget.gateway, sessionId: selected, title: '${row?['title'] ?? ''}'.trim(), session: row, syncToken: widget.syncToken, scrollPositions: _scrollPositions, transcripts: _transcripts, initialNotice: start != null && start.id == selected ? start.notice : null, onBack: onBack, onModelChanged: (applied) => _modelChanged(selected, applied), onModeChanged: (mode, name) => _modeChanged(selected, mode, name), onNewSession: _startedNewSession, onSessionRenamed: (title) => _renamed(selected, title), onSessionClosed: _closed, onColorSelected: (color) => _sessions.setColor(selected, color), onNextChat: _offeredNext ? () => _openNext(selected) : null, ); return ChatComposerFocusScope( sessionId: selected, requests: _composerFocus, child: thread, ); } @override Widget build(BuildContext context) { final selected = _selected; _offeredNext = selected != null && _nextAfter(selected) != null; // A phone opens a chat as a real Navigator page with stock Back. A wide // window keeps the destination rail and the chat list beside the open // chat, which has no Back: another row, `/close` or a route change swaps it. final beside = showsListBesideDetail(context); _page.sync( context, selected: selected != null && !beside, destination: AppDestination.chat, onClosed: _back, builder: (context) => selected == null ? const SizedBox.shrink() : _thread(selected, () => Navigator.of(context).maybePop()), ); // The session list pads its first row by the bar's height itself, so it // scrolls behind the shell's floating bar like the other lists. final list = ChatSessionsScreen( gateway: widget.gateway, embedded: true, syncToken: widget.syncToken, controller: _sessions, folds: _folds, onOpen: _open, onShortcutOpen: _openByShortcut, onSessions: _adoptRows, activeSessionId: selected, publishShellBar: true, ); if (!beside) return list; return ListDetailPanes( list: list, detailIdentity: selected, detail: selected == null ? const EmptyDetailPane( destination: AppDestination.chat, message: 'Select a chat to open it here.', ) : DetailPane( key: const ValueKey('chat-detail-pane'), destination: AppDestination.chat, implyBack: false, builder: (context) => _thread(selected, _back), ), ); } }