import '../../../../core/servers/chat/federated_chat_gateway.dart'; import '../../../../core/servers/server_context.dart'; import 'chat_machine_picker.dart'; import '../../../../ui/adaptive/segmented_bar.dart'; import 'dart:async'; import 'package:flutter/material.dart'; import '../../../../ui/layout/content_width.dart'; import '../../../../core/api_gateway.dart'; import '../../../../shell/shell_bar.dart'; import '../../../../shell/shell_list_shortcuts.dart'; import '../../../terminal/terminal_open_action.dart'; import '../../data/chat_repository.dart'; import '../../domain/chat_colors.dart'; import '../../domain/chat_cycle.dart'; import '../../domain/chat_sessions.dart'; import 'chat_adaptive.dart'; import 'chat_color_picker.dart'; import 'chat_session_local.dart'; import 'chat_sessions_body.dart'; import 'chat_sessions_controller.dart'; import 'create_chat_dialog.dart'; import 'rename_chat_dialog.dart'; import 'session_actions.dart'; import 'session_pane_menu.dart'; /// Browses server-owned sessions. Opening a row is read-only at this layer. class ChatSessionsScreen extends StatefulWidget { const ChatSessionsScreen({ super.key, required this.gateway, required this.onOpen, this.onOpenBeside, this.draggable = false, this.onOpenBelow, this.onFloat, this.paneMenu, this.onShortcutOpen, this.embedded = false, this.syncToken = 0, this.onSessions, this.localStore, this.controller, this.activeSessionId, this.visibleSessionIds = const {}, this.publishShellBar, this.folds, }); final ApiGateway gateway; final void Function(JsonMap session) onOpen; /// Optional split-pane actions; absent when the host cannot offer a split. final ValueChanged? onOpenBeside; final bool draggable; final ValueChanged? onOpenBelow; /// Floats the chat in a window over the app; absent when it cannot. final ValueChanged? onFloat; /// The open panes' More choices for each row's menu, when the list has panes. final SessionPaneMenu? paneMenu; /// Opens a row the shell's Ctrl+1…Ctrl+9 named, so the destination can put /// the keyboard in its composer; null opens it like a tap ([onOpen]). final void Function(JsonMap session)? onShortcutOpen; /// True under the application shell, which owns the single navigation bar. final bool embedded; /// Advances when the shared socket is replaced; sessions created, renamed or /// closed elsewhere during the gap must not stay invisible until Refresh. final int syncToken; /// Reports the loaded rows after a frame. The destination resolves a routed /// session id (a deep link) from them, so that conversation gets the same /// title and model facts as a tapped row without a second list request. final ValueChanged>? onSessions; /// The conversation open above this list, or null when the list is showing. /// Pushed activity for it is being read, so it never raises a New mark. final String? activeSessionId; final Set visibleSessionIds; /// A pushed phone page owns separate chrome. Keep the underlying list's bar /// ready without pretending its open conversation is unread/inactive. final bool? publishShellBar; /// Overrides the device-local hidden/read store in tests. final ChatSessionLocalStore? localStore; /// A list controller the destination owns and keeps across this screen's /// life, so a session created from an open conversation can be listed here. /// Null makes this screen own its own. final ChatSessionsController? controller; /// Which sections are folded, when the destination keeps them (Next chat /// counts the same rows); null makes this screen keep its own. final ChatSectionFolds? folds; @override ChatSessionsScreenState createState() => ChatSessionsScreenState(); } class ChatSessionsScreenState extends State { late final ChatSessionsController _controller = (widget.controller ?? ChatSessionsController( ChatRepository(widget.gateway), localStore: widget.localStore, )) ..activeSessionId = widget.activeSessionId ..refresh(); final _search = TextEditingController(); late final ChatSectionFolds _folds = widget.folds ?? ChatSectionFolds(); Timer? _undoTimer; @override void initState() { super.initState(); _controller.addListener(_reportSessions); } /// Reports the loaded rows at the end of the frame: the destination learns a /// routed row without this screen calling back inside its own build. void _reportSessions() { if (widget.onSessions == null) return; WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; widget.onSessions?.call(_controller.sessions); }); } @override void didUpdateWidget(covariant ChatSessionsScreen oldWidget) { super.didUpdateWidget(oldWidget); _controller.activeSessionId = widget.activeSessionId; if (oldWidget.gateway != widget.gateway) { _controller.replaceRepository(ChatRepository(widget.gateway)); } else if (oldWidget.syncToken != widget.syncToken) { unawaited(_controller.refresh()); } } @override void dispose() { _undoTimer?.cancel(); _controller.removeListener(_reportSessions); if (widget.controller == null) _controller.dispose(); if (widget.folds == null) _folds.dispose(); _search.dispose(); super.dispose(); } String _sessionId(JsonMap session) => '${session['id'] ?? ''}'; Future _rename(JsonMap session) async { final id = _sessionId(session); await showRenameChatDialog( context, session, onSubmit: (title) => _controller.renameOrThrow(id, title), ); } Future _close(JsonMap session) async { if (!await confirmCloseChat(context, session)) return; if (!mounted) return; await _controller.close(_sessionId(session)); } bool _openingRequestedChat = false; void _resumeNewChatIntent() { final scope = ServerContext.maybeOf(context); if (_openingRequestedChat || scope == null || !scope.notifier!.takeNewChatIntent(scope.serverId)) { return; } _openingRequestedChat = true; WidgetsBinding.instance.addPostFrameCallback((_) async { if (!mounted) return; await _newChat(chooseMachine: false); _openingRequestedChat = false; }); } Future _newChat({bool chooseMachine = true}) async { final scope = ServerContext.maybeOf(context); var repository = _controller.repository; if (chooseMachine && scope != null) { final selected = await chooseChatMachine(context); if (!mounted || selected == null) return; if (repository.gateway is FederatedChatGateway) { try { repository = ChatRepository( (repository.gateway as FederatedChatGateway).forServer(selected.id), ); } catch (_) { await showChatMachineError( context, 'Sign in to ${selected.name} or retry its connection before creating a chat.', ); return; } } else if (selected.id != scope.serverId) { final switched = await scope.notifier!.requestNewChat(selected.id); if (!switched && mounted) { await showChatMachineError( context, scope.notifier!.error ?? 'The machine could not be selected.', ); } return; } } // One id per create intent: a refusal retried in the dialog reuses it. final operationId = 'native-chat-${DateTime.now().microsecondsSinceEpoch}'; if (!mounted) return; final session = await showChatCreateDialog( context, repository: repository, operationId: operationId, onSubmit: (draft, id) => _controller.createOrThrow( targetRepository: repository, title: draft.title, directory: draft.directory, backend: draft.backend, instructions: draft.instructions, operationId: id, ), ); if (session != null && mounted) widget.onOpen(session); } /// Starts the same machine picker and create dialog used by the list action. Future newChat() => _newChat(); void _markOpened(JsonMap session) => unawaited(_controller.markOpened(session)); void _openBeside(JsonMap session) { _markOpened(session); widget.onOpenBeside?.call(session); } void _openBelow(JsonMap session) { _markOpened(session); widget.onOpenBelow?.call(session); } void _open(JsonMap session, {bool byShortcut = false}) { _markOpened(session); final open = byShortcut ? widget.onShortcutOpen : null; (open ?? widget.onOpen)(session); } // Methods rather than closures, so the list's memoized rows see the same // callbacks from one build to the next. void _reopen(JsonMap session) => _controller.reopen(_sessionId(session)); void _star(JsonMap session) => _controller.star(_sessionId(session), session['starred'] != true); Future _color(JsonMap session) => showChatColorPicker( context, title: chatSessionTitle(session), selected: chatSessionColor(session), onSelected: (color) => _controller.setColor(_sessionId(session), color), ); /// Ctrl+N: opens the Nth row the list draws (Starred first, then Chats by /// directory, then Closed while it is unfolded), searched as shown. bool _openIndex(int index) { final rows = chatSessionsShown( _controller.sessions, query: _search.text, isOpen: _folds.isOpen, ); if (index < 0 || index >= rows.length) return false; _open(rows[index], byShortcut: true); return true; } Future _hide(JsonMap session) async { await _controller.hide(_sessionId(session)); _undoTimer?.cancel(); _undoTimer = Timer(const Duration(seconds: 8), () { if (mounted) _controller.dismissUndo(); }); } Future _undoHide() async { _undoTimer?.cancel(); await _controller.undoHide(); } @override Widget build(BuildContext context) { _resumeNewChatIntent(); return ListenableBuilder( listenable: _controller, builder: (context, _) { // Built under the page's scaffold, whose media padding carries the // floating bar's height. final body = Builder( builder: (context) => Column( children: [ // A notice above the list starts below the floating bar; the list // under it then needs no inset of its own. if (_controller.error != null) Padding( padding: EdgeInsets.only( top: MediaQuery.paddingOf(context).top, ), child: ChatErrorNotice( message: _controller.error!, onRetry: _controller.refresh, ), ), Expanded( child: MediaQuery.removePadding( context: context, removeTop: _controller.error != null, child: Stack( children: [ ContentWidth( child: ChatSessionsBody( sessions: _controller.sessions, activeSessionId: widget.activeSessionId, visibleSessionIds: widget.visibleSessionIds, query: _search.text, loading: _controller.loading, error: _controller.error, onOpen: _open, onOpenBeside: widget.onOpenBeside == null ? null : _openBeside, draggable: widget.draggable, onOpenBelow: widget.onOpenBelow == null ? null : _openBelow, onFloat: widget.onFloat, paneMenu: widget.paneMenu, onRename: _rename, onClose: _close, onReopen: _reopen, onStar: _star, onColor: _color, onHide: _hide, folds: _folds, onClearSearch: () { _search.clear(); setState(() {}); }, isUnseen: _controller.isUnseen, errorFor: _controller.errorFor, onDismissError: _controller.dismissError, ), ), // The web's hide report is a fixed overlay: replacing or // growing it must never move the list or overflow the screen. if (_controller.lastHidden != null) Positioned( left: 8, right: 8, bottom: 8, child: ChatUndoBar( key: const Key('chat-undo-hide'), message: 'Hidden on this device; the chat stays on the server.', onUndo: _undoHide, ), ), ], ), ), ), ], ), ); // Under the shell, New chat and Refresh are its bar's actions; the // list keeps the space without a search field. if (widget.embedded) { if (ShellBar.available(context)) { return ShellBar( active: widget.publishShellBar ?? widget.activeSessionId == null, actions: _actions(context), // The Chat tab counts chats with messages not yet seen. child: ShellBadge( kind: ShellBadgeKind.unread, count: _controller.sessions.where(_controller.isUnseen).length, child: ShellListShortcut(onOpenIndex: _openIndex, child: body), ), ); } return Column( children: [ Align( alignment: AlignmentDirectional.centerEnd, child: Row( mainAxisSize: MainAxisSize.min, children: _actions(context), ), ), Expanded(child: body), ], ); } return Scaffold( extendBodyBehindAppBar: true, appBar: SegmentedBar(title: 'Chats', actions: _actions(context)), // The list scrolls behind the floating bar; New chat is the bar's // own action, so there is no second create button. body: body, ); }, ); } /// New chat, Refresh and, on a narrow layout, the terminal toggle (wide /// layouts keep it on the shell bar, so it is null here). List _actions(BuildContext context) { final terminal = terminalChatBarAction(context); return [ ChatBarAction( key: const Key('chat-new-chat'), label: 'New chat', onPressed: _newChat, materialIcon: Icons.add, ), ChatBarAction( key: const Key('chat-refresh'), label: 'Refresh', onPressed: _controller.refresh, materialIcon: Icons.refresh, ), ?terminal, ]; } }