import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; import '../../../shell/list_detail_policy.dart'; import '../../../shell/windows/window_entry.dart'; import '../../../shell/windows/window_kind.dart'; import '../../../shell/windows/window_manager.dart'; import '../../terminal/terminal_scope.dart'; import '../chat_runtime.dart'; import '../domain/chat_commands.dart'; import '../workspace/chat_float_shortcut.dart'; import '../workspace/chat_float_store.dart'; import 'chat_window_content.dart'; import 'chat_window_tabs.dart'; const chatWindowKind = 'chat'; /// What the mounted Chat destination offers the chat windows: its tiling. class ChatTiling { const ChatTiling({ required this.holds, required this.dock, required this.canFloatActive, required this.floatActive, }); /// Whether the tiling shows [sessionId]. final bool Function(String sessionId) holds; /// Puts a chat back into the tiling. final void Function(String sessionId) dock; /// Whether the chord can float the active pane now. final bool Function() canFloatActive; final VoidCallback floatActive; } /// The floating chat windows, for the app's lifetime: the `chat` window kind /// over the app's [WindowManager], its chord (see [chatFloatShortcut]), and /// what `/new` and `/close` do to a chat in a window. The windows are built /// from [runtime], so they show whatever destination is open, also when the /// Chat destination has never been built. class ChatWindows { ChatWindows({ required this.manager, required this.runtime, required this.openInChat, this._ready, Listenable? readiness, }) : readiness = readiness ?? const _Never(); final WindowManager manager; final ChatRuntime runtime; /// Opens a chat in the Chat destination (when no tiling is mounted to /// dock into). final void Function(String sessionId) openInChat; final bool Function()? _ready; /// Notifies when [ready] may have changed. final Listenable readiness; /// The mounted Chat destination's tiling, if it is built. ChatTiling? tiling; late final ChatWindowKind kind = ChatWindowKind(this); bool _started = false; /// Whether the server has been reached, so a chat can be read. bool get ready => _ready?.call() ?? true; Iterable get windows => manager.windows.where((w) => w.kind == chatWindowKind); Iterable get floatingSessionIds => windows.map((window) => window.contentId); /// Registers the kind and starts answering the chord. Call before the /// manager restores, so saved chat windows are kept. void start() { if (_started) return; _started = true; manager.kinds.register(kind); FocusManager.instance ..addEarlyKeyEventHandler(_key) ..addEarlyKeyEventHandler(_tabKey); runtime.addSessionReplacedListener(_replacedElsewhere); runtime.sessions.addListener(_rowsChanged); manager.addListener(_rowsChanged); readiness.addListener(_rowsChanged); } void dispose() { if (!_started) return; _started = false; FocusManager.instance ..removeEarlyKeyEventHandler(_key) ..removeEarlyKeyEventHandler(_tabKey); runtime.removeSessionReplacedListener(_replacedElsewhere); runtime.sessions.removeListener(_rowsChanged); manager.removeListener(_rowsChanged); readiness.removeListener(_rowsChanged); manager.kinds.unregister(chatWindowKind); } /// Opens the windows an older build saved (`pipelines.next.chatFloat.v1`, /// both formats) once, after the manager restored and found none. Future migrate(ChatFloatStore legacy) async { final record = await legacy.read(); if (record == null || record.panes.isEmpty || !_started) return; if (windows.isEmpty) { for (final pane in record.panes) { manager.open( chatWindowKind, pane.sessionId, frame: record.frames[pane.id], ); } if (!record.shown) manager.setGroupShown(chatWindowKind, false); } await legacy.write(const ChatFloatRecord()); } /// Shows the window [sessionId] is in; false when it is in none. bool show(String sessionId) { final entry = manager.find(chatWindowKind, sessionId); if (entry == null) return false; manager.show(entry.id); return true; } /// Opens [sessionId] in a window (the caller took it out of the tiling). void float(String sessionId) => manager.open(chatWindowKind, sessionId); /// Puts the window's chat back into the tiling, or opens it in the Chat /// destination when that is not built. void dock(WindowEntry entry) { final tiling = this.tiling; manager.close(entry.id); if (tiling != null) { tiling.dock(entry.contentId); } else { openInChat(entry.contentId); } } /// `/new` in a window's chat: the window follows the new session, unless /// that session is already open elsewhere. void startedNewSession( String windowId, String previousId, JsonMap session, String notice, ) { runtime.sessions.replaceSession(previousId, session); _follow(windowId, previousId, session, notice); unawaited(runtime.sessions.refresh()); } void _replacedElsewhere(String previousId, JsonMap session) { final entry = manager.find(chatWindowKind, previousId); if (entry == null) return; _follow(entry.id, previousId, session, chatNewSessionElsewhereNotice); } void _follow( String windowId, String previousId, JsonMap session, String notice, ) { final id = '${session['id'] ?? ''}'; if (id.isEmpty) return; final elsewhere = manager.find(chatWindowKind, id) != null || (tiling?.holds(id) ?? false); if (elsewhere) { manager.close(windowId); return; } runtime.movedToSession(previousId, session, notice); manager.setContent(windowId, id); } /// `/close` was accepted for a window's chat. void sessionClosed(String windowId) { manager.close(windowId); unawaited(runtime.sessions.refresh()); } bool _reading = false; /// The windows' chats take their rows (title, model, mode) from the /// session list, which nothing else reads while the Chat destination is /// not built. void _rowsChanged() { _noteOpenOrder(); final ids = {for (final w in windows) w.contentId}; if (ids.isEmpty || !ready) return; final sessions = runtime.sessions; if (ids.any((id) => runtime.rowFor(id) == null) && !_reading) { _reading = true; unawaited(sessions.refresh().whenComplete(() => _reading = false)); } final rows = sessions.sessions; scheduleMicrotask(() { if (_started) runtime.adoptRows(rows, selected: null, retained: ids); }); } bool get _wide { final view = WidgetsBinding.instance.platformDispatcher.views.firstOrNull; return view == null || view.physicalSize.width / view.devicePixelRatio >= kListDetailMinWidth; } /// Handled before any focused widget sees the key, so it works from a /// composer or the terminal; ignored (left to them) when it does nothing. KeyEventResult _key(KeyEvent event) { if (!_wide || !chatFloatShortcut(event, HardwareKeyboard.instance)) { return KeyEventResult.ignored; } if (windows.isEmpty) { final tiling = this.tiling; if (tiling == null || !tiling.canFloatActive()) { return KeyEventResult.ignored; } if (event is KeyDownEvent) tiling.floatActive(); return KeyEventResult.handled; } if (event is KeyDownEvent) manager.toggleOrRaiseGroup(chatWindowKind); return KeyEventResult.handled; } /// Ctrl+Tab and Ctrl+Shift+Tab while a floating chat window holds the /// keyboard: the next (previous) shown chat window, in open order and /// wrapping, comes to the top. The window host then gives it the keyboard, /// its composer. Left alone when another window or the tiling has the /// keyboard, when the terminal claims tab keys, or with one window. KeyEventResult _tabKey(KeyEvent event) { final step = chatWindowTabStep(event, HardwareKeyboard.instance); if (step == null || !_wide) return KeyEventResult.ignored; final scope = keyboardWindow(); if (scope == null || scope.entry.kind != chatWindowKind || _terminalClaimsTabs()) { return KeyEventResult.ignored; } final target = chatWindowAfter(shownInOpenOrder(), scope.entry.id, step); if (target == null) return KeyEventResult.ignored; manager.raise(target.id); return KeyEventResult.handled; } /// The ids of the chat windows in the order they were opened; a window /// restored from a saved layout keeps its saved place. Raising a window /// changes the stacking order, not this one, so the Ctrl+Tab cycle is /// stable. Kept in step on every change of the windows (see [_rowsChanged]). final List _openOrder = []; void _noteOpenOrder() { final ids = {for (final w in windows) w.id}; _openOrder.removeWhere((id) => !ids.contains(id)); for (final w in windows) { if (!_openOrder.contains(w.id)) _openOrder.add(w.id); } } /// The shown chat windows (not minimised, their group shown), in open order. List shownInOpenOrder() { _noteOpenOrder(); final shown = { for (final w in windows) if (manager.isVisible(w)) w.id: w, }; return [for (final id in _openOrder) ?shown[id]]; } /// Ctrl+Tab from the tiling or the chat list while chat windows are shown: /// the top-most shown chat window comes to the top and its composer takes /// the keyboard. False, doing nothing, when no chat window is shown. bool raiseTopFromTiling() { final top = windows.where(manager.isVisible).lastOrNull; if (top == null) return false; manager.raise(top.id); kind.focusContent(top); return true; } bool _terminalClaimsTabs() { final context = FocusManager.instance.primaryFocus?.context; return context != null && TerminalScope.peek(context)?.claimsTabKeys == true; } } class _Never implements Listenable { const _Never(); @override void addListener(VoidCallback listener) {} @override void removeListener(VoidCallback listener) {} } /// A chat in a floating window. class ChatWindowKind extends WindowKind { ChatWindowKind(this.windows); final ChatWindows windows; @override String get key => chatWindowKind; @override bool get serverScoped => true; @override IconData get icon => Icons.chat_bubble_outline; @override Size get minSize => chatFloatMinSize; @override Rect get defaultFrame => chatFloatDefaultRect; /// Chats float beside the chat list, on a wide layout only. @override double get minHostWidth => kListDetailMinWidth; @override Listenable get changes => windows.runtime; @override String title(BuildContext context, WindowEntry entry) => windows.runtime.titleFor(entry.contentId); @override Widget build(BuildContext context, WindowEntry entry) => ChatWindowContent(windows: windows, entry: entry); @override List actions(BuildContext context, WindowEntry entry) => [ WindowAction( label: 'Dock', icon: Icons.vertical_split_outlined, onPressed: () => windows.dock(entry), ), ]; @override void focusContent(WindowEntry entry) => windows.runtime.composerFocus.request(entry.contentId); }