Files
pipelines/app/lib/features/chat/screen.dart
T
alan 04ba81e0ea Remove Cupertino chat cleanup leftovers
Keep chat and folder-picker UI on the Material path by removing obsolete Cupertino imports, icon metadata, flags, and alternate control handling while preserving existing behavior and focused test coverage.
2026-11-11 20:06:37 +00:00

557 lines
20 KiB
Dart

import 'chat_pane_content.dart';
import 'chat_runtime.dart';
import 'windows/chat_windows.dart';
import 'workspace/federated_workspace_store.dart';
import '../../core/servers/chat/federated_chat_gateway.dart';
import '../../shell/destination.dart';
import '../../shell/shell_bar.dart';
import '../../shell/shell_destination_menu.dart';
import '../../shell/detail_page.dart';
import '../../shell/empty_detail_pane.dart';
import '../../shell/list_detail.dart';
import 'dart:async';
import '../../ui/motion/motion.dart';
import '../../ui/motion/container_transform_source.dart';
import 'package:flutter/foundation.dart' show setEquals;
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import '../../core/api_gateway.dart';
import '../../core/servers/server_scope.dart';
import 'workspace/chat_float_shortcut.dart';
import 'workspace/chat_workspace_binding.dart';
import 'workspace/chat_workspace_snapshot.dart';
import 'workspace/chat_workspace_store.dart';
import 'conversation/chat_bar_tint.dart';
import 'conversation/chat_pane_picker.dart';
import 'conversation/chat_add_pane_picker.dart';
import 'conversation/chat_sidebar_controls.dart';
import 'ui/sessions/chat_compact_sidebar.dart';
import 'workspace/chat_workspace.dart';
import 'workspace/chat_center_stage_action.dart';
import 'workspace/chat_center_stage_controller.dart';
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/composer_focus_request.dart';
import 'conversation/composer_selection_focus.dart';
import 'domain/chat_commands.dart';
import 'domain/chat_cycle.dart';
import '../terminal/terminal_scope.dart';
import 'domain/chat_colors.dart';
import 'ui/sessions/chat_color_palette.dart';
import 'ui/sessions/chat_sessions_body.dart';
import 'ui/sessions/chat_sessions_controller.dart';
import 'ui/sessions/chat_sessions_screen.dart';
import '../../ui/input/keyboard_owner.dart';
part 'chat_screen_float.dart';
part 'chat_screen_keys.dart';
part 'chat_screen_workspace.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,
this.onWorkspaceEmpty,
this.onAvailableSessionsChanged,
this.persistWorkspace = false,
this.runtime,
this.windows,
});
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 app's floating chat windows; null offers none (a pane cannot
/// float).
final ChatWindows? windows;
/// 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<String>? onSessionSelected;
final VoidCallback? onBack;
final VoidCallback? onWorkspaceEmpty;
final ValueChanged<Set<String>>? onAvailableSessionsChanged;
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen>
with _ChatScreenWorkspace, _ChatScreenKeys, _ChatScreenFloat {
/// 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);
ChatSessionsController get _sessions => _runtime.sessions;
@override
Map<String, JsonMap> 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
ChatComposerFocusRequests get _composerFocus => _runtime.composerFocus;
ChatSectionFolds get _folds => _runtime.folds;
/// Whether the last build offered Next chat, so a list change rebuilds only
/// when that changes.
bool _offeredNext = false;
@override
ChatSessionsController get _sessionsForSidebar => _sessions;
@override
ChatSectionFolds get _foldsForSidebar => _folds;
@override
void _openSidebarSession(JsonMap session) => _openBySelection(session);
@override
void initState() {
super.initState();
_runtime
..gateway = widget.gateway
..addListener(_runtimeChanged);
_runtime.addSessionReplacedListener(_replacedElsewhere);
_bindWindows();
final initial = widget.initialSessionId;
if (initial != null && initial.isNotEmpty) {
_workspace.open(initial);
_workspaceVisible = true;
_publishedWorkspaceSession = initial;
_noteRecentSession();
}
_workspace.addListener(_workspaceChanged);
_bindWorkspacePersistence();
HardwareKeyboard.instance.addHandler(_cycleChatKey);
HardwareKeyboard.instance.addHandler(_slashFocusKey);
// Seen from now on, so the press that chooses the first chat counts.
LastPointerKind.instance;
_sessions.addListener(_nextChanged);
_sessions.addListener(_availableSessionsChanged);
_availableSessionsChanged();
_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.
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) _openBySelection(next);
}
void _availableSessionsChanged() {
if (!mounted || _sessions.loading) return;
widget.onAvailableSessionsChanged?.call({
for (final row in _sessions.sessions)
if (row['closed_at'] == null && row['closed'] != true)
'${row['id'] ?? ''}',
});
}
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 {
if (_workspaceVisible && _workspace.activePane != null) {
return _workspace.activePane!.sessionId;
}
if (!_workspaceVisible && _usedWorkspace) return null;
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);
/// Opens [session] chosen by a tap, click or Next chat: its composer takes
/// focus on a desktop host or after a mouse click, not from a finger on a
/// phone or tablet (see [chatSelectionFocusesComposer]).
void _openBySelection(JsonMap session) =>
_open(session, focusComposer: chatSelectionFocusesComposer(session));
@override
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;
_workspaceVisible = true;
_workspace.open(id);
if (_runtime.startNotice?.id != id) _runtime.startNotice = null;
final select = widget.onSessionSelected;
if (select != null) {
if (_publishedWorkspaceSession != id) {
_publishedWorkspaceSession = id;
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 || !_workspace.holdsSession(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) {
_runtime.movedToSession(previousId, session, notice);
_forgetRecentSession(previousId);
_workspace.replaceSession(previousId, '${session['id'] ?? ''}');
if (_workspace.paneCount == 0) _open(session);
}
/// `/close` was accepted: the conversation leaves, back to the list, which
/// re-reads the closed row.
void _closed(String sessionId) {
_forgetRecentSession(sessionId);
for (final pane
in _workspace.panes
.where((pane) => pane.sessionId == sessionId)
.toList()) {
_closePane(pane.id);
}
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<JsonMap> rows) {
if (!mounted) return;
widget.onAvailableSessionsChanged?.call({
for (final row in rows)
if (row['closed_at'] == null && row['closed'] != true)
'${row['id'] ?? ''}',
});
_runtime.adoptRows(
rows,
selected: _selected,
retained: _workspace.panes.map((pane) => pane.sessionId).toSet(),
);
}
@override
JsonMap? _rowFor(String id) => _runtime.rowFor(id);
@override
void _back() {
_workspaceVisible = false;
_publishedWorkspaceSession = null;
_runtime.startNotice = null;
_composerFocus.cancel();
if (_workspace.paneCount == 0) widget.onWorkspaceEmpty?.call();
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();
/// The list rows the phone's chat page grows from and shrinks back into:
/// the open chat's row, also after the page switched to another chat.
final ContainerTransformSources _rowSources = ContainerTransformSources();
late final ContainerTransformLink _growFromRow = _rowSources.link(
() => _selected,
);
@override
bool get _pageOpen => _page.open;
@override
void didUpdateWidget(covariant ChatScreen oldWidget) {
super.didUpdateWidget(oldWidget);
final reboundWorkspace = _updateWorkspacePersistence(oldWidget);
if (!reboundWorkspace &&
oldWidget.initialSessionId != widget.initialSessionId) {
_workspaceBinding?.changed();
final id = widget.initialSessionId;
if (id != null && id.isNotEmpty) {
_workspaceVisible = true;
_publishedWorkspaceSession = id;
_workspace.open(id);
} else if (widget.onSessionSelected != null) {
_workspaceVisible = false;
}
}
// Transcripts read through another gateway belong to that server.
_runtime.gateway = widget.gateway;
}
@override
void dispose() {
HardwareKeyboard.instance.removeHandler(_cycleChatKey);
HardwareKeyboard.instance.removeHandler(_slashFocusKey);
_page.dispose();
_workspaceBinding?.dispose();
_unbindWindows();
_workspace.removeListener(_workspaceChanged);
_workspace.dispose();
_sessions.removeListener(_nextChanged);
_sessions.removeListener(_availableSessionsChanged);
_folds.removeListener(_nextChanged);
_runtime.removeListener(_runtimeChanged);
_runtime.removeSessionReplacedListener(_replacedElsewhere);
if (widget.runtime == null) _runtime.dispose();
super.dispose();
}
@override
Widget _thread(ChatWorkspacePane pane) {
final selected = pane.sessionId;
return buildChatPaneContent(
runtime: _runtime,
sessionId: selected,
placement: ChatPanePlacement(
syncToken: widget.syncToken,
onBack: _back,
onNewSession: _startedNewSession,
onSessionClosed: () => _closed(selected),
onNextChat: _nextAfter(selected) != null
? () => _openNext(selected)
: null,
useNativeBack: _page.open,
pasteTarget: _workspaceVisible && pane.id == _workspace.activePaneId,
showBackButton: _page.open || !showsListBesideDetail(context),
paneControls: (paneContext) => [
ChatBarAction(
label: 'Add chat pane',
onPressed: () => _addPane(paneContext),
materialIcon: Icons.add_box_outlined,
),
if (_workspace.paneCount > 1)
ChatBarAction(
label: 'Open chats (${_workspace.paneCount})',
onPressed: () => _pickPane(paneContext),
materialIcon: Icons.view_quilt_outlined,
),
if (_workspace.paneCount > 1 && showsListBesideDetail(context))
chatCenterStageAction(ChatCenterStageController.instance),
...chatPaneMoveActions(
ChatWorkspacePaneScope.maybeOf(paneContext),
onMove: (target) => _movePane(pane.id, target),
),
..._floatControls(pane),
if (_workspace.paneCount > 1)
ChatBarAction(
label: 'Close pane',
onPressed: () => _closePane(pane.id),
materialIcon: Icons.close,
),
],
),
);
}
@override
Widget build(BuildContext context) {
final selected = _selected;
if (_workspaceVisible && selected != _publishedWorkspaceSession) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => _publishWorkspaceRoute(),
);
}
_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 = !_page.open && showsListBesideDetail(context);
if (beside && selected != null) _usedWorkspace = true;
_page.sync(
context,
selected: selected != null && !beside && !_usedWorkspace,
destination: AppDestination.chat,
onClosed: _back,
growFrom: _growFromRow,
builder: (context) => selected == null
? const SizedBox.shrink()
: ShellBar(barless: true, child: _workspaceView()),
);
// 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 sessions = ChatSessionsScreen(
gateway: widget.gateway,
embedded: true,
syncToken: widget.syncToken,
controller: _sessions,
folds: _folds,
onOpen: _openBySelection,
onOpenBeside: beside ? _openBeside : null,
onOpenBelow: _openBelow,
onShortcutOpen: _openByShortcut,
onSessions: _adoptRows,
activeSessionId: selected,
visibleSessionIds: _visibleSidebarSessions,
publishShellBar:
(selected == null ||
!beside ||
_sidebarMode == ChatSidebarMode.expanded) &&
(beside || !_usedWorkspace || selected == null),
);
final fullList = ContainerTransformScope(
sources: _rowSources,
child: sessions,
);
final list = _sidebarList(fullList, selected, beside);
if (!beside) {
if (!_usedWorkspace) return list;
final media = MediaQuery.of(context);
final system = ShellSystemInsets.of(context);
return PopScope(
canPop: selected == null,
onPopInvokedWithResult: (didPop, _) {
if (!didPop && selected != null) _back();
},
child: ShellBar(
active: selected != null,
barless: true,
hideNavigation: true,
child: Stack(
fit: StackFit.expand,
children: [
Offstage(
offstage: selected != null,
child: ExcludeFocus(excluding: selected != null, child: list),
),
ChatWorkspaceEntrance(
visible: selected != null,
child: ExcludeFocus(
excluding: selected == null,
child: MediaQuery(
data: media.copyWith(
padding: media.padding.copyWith(
top: system.top,
bottom: system.bottom,
),
),
child: _workspaceView(),
),
),
),
],
),
),
);
}
return ShellBar(
active: selected != null && _sidebarMode != ChatSidebarMode.expanded,
barless: true,
hideNavigation: true,
child: ListDetailPanes(
list: list,
compactListWidth: selected == null ? null : ChatCompactSidebar.width,
onListCompactChanged: selected == null
? null
: (compact) => _setSidebarMode(
compact ? ChatSidebarMode.compact : ChatSidebarMode.expanded,
),
listWidthOverride: selected == null
? null
: switch (_sidebarMode) {
ChatSidebarMode.expanded => null,
ChatSidebarMode.compact => ChatCompactSidebar.width,
ChatSidebarMode.hidden => 0,
},
detailIdentity: selected,
detail: selected == null
? const EmptyDetailPane(
destination: AppDestination.chat,
message: 'Select a chat to open it here.',
)
: SizedBox.expand(
key: const ValueKey('chat-detail-pane'),
child: _workspaceView(),
),
),
);
}
}