From fdc730422dcdb9db98158e42fdee3174dc228cb9 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 10 Nov 2026 21:17:40 +0000 Subject: [PATCH] Host floating chats on the shell window system Phase 2.3 and 2.4 of docs/plans/floating-windows.md. A floating chat is a window of the chat kind over the app's WindowManager, built from the app-lifetime ChatRuntime, so it shows over every destination and at start without the Chat destination being built. Float and Dock move the same keyed view between the tiling and the window host. The pipelines app keeps one runtime and one ChatWindows; saved chatFloat records (v1 and v2) are brought over once. ChatFloatHost, ChatFloatWindow, the float frames and binding, the controller's float list and FloatingFocusRoot are gone; the workspace only asks whether a chat is out in a window. Every MenuAnchor targets the root overlay (guarded by a test), and menus and tooltips name the Alt chords. --- app/lib/application/app_windows.dart | 14 - app/lib/application/chat_destination.dart | 10 + app/lib/application/pipelines_app.dart | 65 ++- app/lib/core/servers/chat/browser_peer.dart | 6 +- app/lib/core/session/server_session.dart | 1 - app/lib/features/chat/chat_screen_float.dart | 108 ++-- .../features/chat/chat_screen_workspace.dart | 18 +- .../conversation/chat_effort_control.dart | 2 + .../chat/conversation/chat_thread_view.dart | 10 + app/lib/features/chat/screen.dart | 80 ++- .../chat/windows/chat_window_content.dart | 68 +++ .../features/chat/windows/chat_windows.dart | 280 +++++++++++ .../chat/workspace/chat_float_binding.dart | 156 ------ .../chat/workspace/chat_float_host.dart | 337 ------------- .../chat/workspace/chat_float_shortcut.dart | 6 +- .../chat/workspace/chat_float_window.dart | 229 --------- .../chat/workspace/chat_workspace.dart | 52 +- .../workspace/chat_workspace_controller.dart | 11 +- .../chat/workspace/chat_workspace_float.dart | 133 ++--- .../discovery/discovered_server_row.dart | 5 +- .../pipelines/widgets/pipeline_controls.dart | 2 + .../settings/saved_server_sign_in_step.dart | 4 +- .../features/terminal/terminal_shortcuts.dart | 5 +- app/lib/shell/adaptive_shell.dart | 12 +- app/lib/shell/windows/window_host.dart | 62 ++- app/lib/shell/windows/window_kind.dart | 11 + .../ui/adaptive/segmented_bar_overflow.dart | 2 + app/lib/ui/floating/floating_layer.dart | 52 +- app/notes/floating-windows.md | 4 +- .../chat/chat_floating_pane_test.dart | 463 +++++++++++------- .../features/chat/chat_pane_move_test.dart | 9 +- .../chat/conversation/chat_bar_tint_test.dart | 5 +- .../chat_unfocused_paste_routing_test.dart | 4 +- .../files/files_panel_mutations_test.dart | 27 +- .../ui/sessions/session_attention_test.dart | 15 +- .../ui/transcript/chat_copy_gutter_test.dart | 54 +- .../chat/windows/chat_windows_test.dart | 278 +++++++++++ .../workspace/chat_center_stage_test.dart | 4 +- .../workspace/chat_float_shortcut_test.dart | 283 ++--------- .../chat/workspace/chat_pane_move_test.dart | 4 +- .../workspace/chat_workspace_float_test.dart | 231 ++------- .../terminal/terminal_shortcuts_test.dart | 7 +- app/test/shell/windows/window_host_test.dart | 5 +- .../windows/window_popup_rules_test.dart | 27 + 44 files changed, 1369 insertions(+), 1792 deletions(-) delete mode 100644 app/lib/application/app_windows.dart create mode 100644 app/lib/features/chat/windows/chat_window_content.dart create mode 100644 app/lib/features/chat/windows/chat_windows.dart delete mode 100644 app/lib/features/chat/workspace/chat_float_binding.dart delete mode 100644 app/lib/features/chat/workspace/chat_float_host.dart delete mode 100644 app/lib/features/chat/workspace/chat_float_window.dart create mode 100644 app/test/features/chat/windows/chat_windows_test.dart create mode 100644 app/test/shell/windows/window_popup_rules_test.dart diff --git a/app/lib/application/app_windows.dart b/app/lib/application/app_windows.dart deleted file mode 100644 index d69c036c..00000000 --- a/app/lib/application/app_windows.dart +++ /dev/null @@ -1,14 +0,0 @@ -import '../shell/windows/window_kind.dart'; -import '../shell/windows/window_manager.dart'; -import '../shell/windows/window_store.dart'; - -/// The app's floating windows, for the app's lifetime: the kinds features -/// register at start and the one manager the shell's window host draws. -abstract final class AppWindows { - static final WindowKinds kinds = WindowKinds(); - - static final WindowManager manager = WindowManager( - kinds: kinds, - store: const SharedPreferencesWindowStore(), - ); -} diff --git a/app/lib/application/chat_destination.dart b/app/lib/application/chat_destination.dart index 5627598c..026fd3bf 100644 --- a/app/lib/application/chat_destination.dart +++ b/app/lib/application/chat_destination.dart @@ -1,7 +1,9 @@ import '../core/servers/chat/chat_server_pool.dart'; import 'package:flutter/material.dart'; +import '../features/chat/chat_runtime.dart'; import '../features/chat/screen.dart'; +import '../features/chat/windows/chat_windows.dart'; import '../ui/adaptive/host.dart'; import '../ui/adaptive/top_bar_notices.dart'; import 'app_session.dart'; @@ -25,6 +27,8 @@ class ChatDestination extends StatelessWidget { this.onBack, this.onWorkspaceEmpty, this.onAvailableSessionsChanged, + this.runtime, + this.windows, }); final AppSession session; @@ -36,6 +40,10 @@ class ChatDestination extends StatelessWidget { final VoidCallback? onWorkspaceEmpty; final ValueChanged>? onAvailableSessionsChanged; + /// The chats' app-lifetime state and floating windows (see [ChatScreen]). + final ChatRuntime? runtime; + final ChatWindows? windows; + @override Widget build(BuildContext context) => AnimatedBuilder( animation: Listenable.merge([session, ?pool]), @@ -86,5 +94,7 @@ class ChatDestination extends StatelessWidget { onBack: onBack, onWorkspaceEmpty: onWorkspaceEmpty, onAvailableSessionsChanged: onAvailableSessionsChanged, + runtime: runtime, + windows: windows, ); } diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index ce722efc..991c7e40 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -35,9 +35,13 @@ import '../features/updates/web_release.dart'; import '../features/settings/server_connections.dart'; import 'app.dart'; import '../shell/windows/window_host.dart'; +import '../shell/windows/window_kind.dart'; import '../shell/windows/window_manager.dart'; +import '../shell/windows/window_store.dart'; import 'app_terminals.dart'; -import 'app_windows.dart'; +import '../features/chat/chat_runtime.dart'; +import '../features/chat/windows/chat_windows.dart'; +import '../features/chat/workspace/chat_float_store.dart'; import '../features/terminal/terminal_layout.dart'; import 'app_route.dart'; import 'app_router.dart'; @@ -99,7 +103,8 @@ class PipelinesApp extends StatefulWidget { /// The terminal surface's saved layout; null is the device's own. final TerminalLayout? terminalLayout; - /// The floating windows; the app's own ([AppWindows.manager]) when null. + /// The floating windows; the app keeps its own (saved on this device) + /// when null. final WindowManager? windows; final ServerEndpoint server; final PipelinesClient? client; @@ -216,6 +221,8 @@ class _PipelinesAppState extends State NotificationServiceHandoff? _deliveryHandoff; late final AppTerminals _terminals; late final WindowManager _windows; + late final ChatRuntime _chatRuntime; + late final ChatWindows _chatWindows; @override void initState() { @@ -236,9 +243,38 @@ class _PipelinesAppState extends State bindServerIdentity(_session.gateway, widget.serverId); bindServerIdentity(_session.client, widget.serverId); // One server for now: windows are kept per server, and this one's show. - _windows = (widget.windows ?? AppWindows.manager) - ..server = widget.serverId ?? 'server'; - unawaited(_windows.restore()); + _windows = + (widget.windows ?? + WindowManager( + kinds: WindowKinds(), + store: const SharedPreferencesWindowStore(), + )) + ..server = widget.serverId ?? 'server'; + final chatGateway = widget.chatPool?.gateway ?? _session.gateway; + final chatScope = widget.chatPool != null + ? 'all-saved-servers' + : serverStorageScope(serverIdentity(chatGateway)); + _chatRuntime = ChatRuntime(gateway: chatGateway, serverKey: chatScope); + _chatWindows = ChatWindows( + manager: _windows, + runtime: _chatRuntime, + openInChat: (id) => _delegate.goTo(AppRoute.chatSession(id)), + ready: _chatReady, + readiness: Listenable.merge([_session, ?widget.chatPool]), + )..start(); + _session.addListener(_chatSyncChanged); + widget.chatPool?.addListener(_chatSyncChanged); + _chatSyncChanged(); + // Every kind is registered: saved windows can be restored, then the + // floating chats an older build saved are brought over once. + unawaited( + _windows.restore().then((_) { + if (!mounted) return null; + return _chatWindows.migrate( + SharedPreferencesChatFloatStore(serverScope: chatScope), + ); + }), + ); _terminals = AppTerminals( pool: widget.chatPool, connection: _session, @@ -464,6 +500,11 @@ class _PipelinesAppState extends State (_provider as PlatformRouteInformationProvider).dispose(); } _terminals.dispose(); + _session.removeListener(_chatSyncChanged); + widget.chatPool?.removeListener(_chatSyncChanged); + _chatWindows.dispose(); + _chatRuntime.dispose(); + if (widget.windows == null) _windows.dispose(); _session.dispose(); super.dispose(); } @@ -732,6 +773,18 @@ class _PipelinesAppState extends State _delegate.goTo(AppRoute.run(id)); } + /// Whether a chat can be read: the server has been reached (or saved + /// machines connect on their own). + bool _chatReady() { + final pool = widget.chatPool; + if (pool != null && pool.servers.catalog.servers.isNotEmpty) return true; + return _session.everConnected || _session.connected; + } + + /// A replaced socket makes open chats re-subscribe, also in windows. + void _chatSyncChanged() => _chatRuntime.syncToken.value = + widget.chatPool?.revision ?? _session.connectionEpoch; + /// The shell rebuilds its Runs tab badge from the attention count alone; the /// destination bodies keep their state through it. Widget _buildShell(BuildContext context, AppRoute route) => @@ -835,6 +888,8 @@ class _PipelinesAppState extends State initialSessionId: chatRoute.chatSessionId, onSessionSelected: (id) => _delegate.goTo(AppRoute.chatSession(id)), onBack: () => _delegate.goTo(AppRoute.chat), + runtime: _chatRuntime, + windows: _chatWindows, onWorkspaceEmpty: () => _chatWorkspaceRoute = null, onAvailableSessionsChanged: (ids) { _availableChatSessionIds = ids; diff --git a/app/lib/core/servers/chat/browser_peer.dart b/app/lib/core/servers/chat/browser_peer.dart index c0e689cb..c8db1a6e 100644 --- a/app/lib/core/servers/chat/browser_peer.dart +++ b/app/lib/core/servers/chat/browser_peer.dart @@ -6,10 +6,8 @@ import 'browser_peer_stub.dart' /// Registers [server] with the same-origin relay. [needsPassword] is the /// relay's own verdict, distinct from an unreachable machine. Future<({bool connected, bool needsPassword, String? error})> -registerBrowserPeer( - SavedServer server, { - String? password, -}) => impl.register(server, password: password); +registerBrowserPeer(SavedServer server, {String? password}) => + impl.register(server, password: password); Future removeBrowserPeer(String id) => impl.remove(id); Uri browserPeerEndpoint(String id, Uri endpoint, {Uri? page}) { final origin = page ?? Uri.base; diff --git a/app/lib/core/session/server_session.dart b/app/lib/core/session/server_session.dart index 1a829199..cd4d8b3f 100644 --- a/app/lib/core/session/server_session.dart +++ b/app/lib/core/session/server_session.dart @@ -297,4 +297,3 @@ class ServerSession { static ServerProbeResult interpret(Uri login, LoginProbe probe) => interpretLoginProbe(login, probe); } - diff --git a/app/lib/features/chat/chat_screen_float.dart b/app/lib/features/chat/chat_screen_float.dart index 9d3a540b..9bbf929b 100644 --- a/app/lib/features/chat/chat_screen_float.dart +++ b/app/lib/features/chat/chat_screen_float.dart @@ -1,81 +1,67 @@ part of 'screen.dart'; -/// The floating chats for one Chat destination visit: their menu choices, -/// window frames and persistence (see `notes/chat-floating-pane.md`). +/// Floating a tiled pane into a window and docking it back (see +/// [ChatWindows] and `notes/chat-floating-pane.md`). mixin _ChatScreenFloat on State, _ChatScreenWorkspace { - @override - final ChatFloatFrames _floatFrames = ChatFloatFrames(); - ChatFloatBinding? _floatBinding; + ChatTiling? _tiling; - /// Restores and saves the floating chat in [store] once [restored] (the - /// workspace layout's own restore) completes. - @override - void _bindFloat(ChatFloatStore store, Future restored) { - _floatBinding?.dispose(); - final binding = _floatBinding = ChatFloatBinding( - controller: _workspace, - frames: _floatFrames, - store: store, - ); - unawaited( - restored.then((_) { - if (mounted && identical(_floatBinding, binding)) { - return binding.start(); - } - }), + void _bindWindows() { + final windows = widget.windows; + if (windows == null) return; + _workspace.showOutside = windows.show; + windows.tiling = _tiling = ChatTiling( + holds: _workspace.holdsSession, + dock: _dockSession, + canFloatActive: () { + final pane = _workspace.activePane; + return mounted && + pane != null && + _floatsHere && + _workspaceVisible && + _workspace.canFloat(pane.id) && + _chatOwnsKeyboard(); + }, + floatActive: () { + final pane = _workspace.activePane; + if (pane != null) _floatPane(pane.id); + }, ); } - @override - void _unbindFloat() { - _floatBinding?.dispose(); - _floatBinding = null; - } - - void _disposeFloat() { - _unbindFloat(); - _floatFrames.dispose(); + void _unbindWindows() { + final windows = widget.windows; + if (windows != null && identical(windows.tiling, _tiling)) { + windows.tiling = null; + } + _workspace.showOutside = null; } /// Panes float only on a wide layout, beside the chat list. - bool get _floatsHere => !_pageOpen && showsListBesideDetail(context); + bool get _floatsHere => + widget.windows != null && !_pageOpen && showsListBesideDetail(context); - void _dockFloat(ChatWorkspacePane pane) { - _workspace.dock(pane.id); - _composerFocus.request(pane.sessionId); + /// The pane leaves the tiling and its live view moves into a window in + /// the same frame. + void _floatPane(String paneId) { + final pane = _workspace.detach(paneId); + if (pane != null) widget.windows?.float(pane.sessionId); } - /// The pane menu's floating choices: Float on a tiled pane that can, and - /// Dock, Hide and Close on a floating chat. + void _dockSession(String sessionId) { + if (!mounted) return; + _workspaceVisible = true; + if (!_pageOpen && showsListBesideDetail(context)) _usedWorkspace = true; + _workspace.dock(sessionId); + _composerFocus.request(sessionId); + } + + /// The pane menu's Float choice, on a tiled pane that can. List _floatControls(ChatWorkspacePane pane) { - final shortcut = chatFloatShortcutLabel(); - if (_workspace.isFloating(pane.id)) { - return [ - ChatBarAction( - label: 'Dock', - onPressed: () => _dockFloat(pane), - materialIcon: Icons.vertical_split_outlined, - cupertinoIcon: CupertinoIcons.rectangle_split_3x1, - ), - ChatBarAction( - label: 'Hide floating chats ($shortcut)', - onPressed: () => _workspace.setFloatShown(false), - materialIcon: Icons.visibility_off_outlined, - cupertinoIcon: CupertinoIcons.eye_slash, - ), - ChatBarAction( - label: 'Close pane', - onPressed: () => _closePane(pane.id), - materialIcon: Icons.close, - cupertinoIcon: CupertinoIcons.xmark, - ), - ]; - } if (!_floatsHere || !_workspace.canFloat(pane.id)) return const []; return [ ChatBarAction( - label: 'Float ($shortcut)', - onPressed: () => _workspace.float(pane.id), + label: 'Float (${chatFloatShortcutLabel()})', + onPressed: () => _floatPane(pane.id), materialIcon: Icons.picture_in_picture_alt_outlined, cupertinoIcon: CupertinoIcons.rectangle_on_rectangle, ), diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index ebf4f4bb..3991fa30 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -11,9 +11,6 @@ mixin _ChatScreenWorkspace on State { JsonMap? _rowFor(String id); void _back(); bool get _pageOpen; - ChatFloatFrames get _floatFrames; - void _bindFloat(ChatFloatStore store, Future restored); - void _unbindFloat(); Widget _thread(ChatWorkspacePane pane); ChatSidebarMode _sidebarMode = ChatSidebarMode.expanded; @@ -112,17 +109,8 @@ mixin _ChatScreenWorkspace on State { _publishWorkspaceRoute(); }, ); - final restored = _workspaceBinding!.start( - initialSessionId: widget.initialSessionId, - ); - unawaited(restored); - _bindFloat( - SharedPreferencesChatFloatStore( - serverScope: widget.gateway is FederatedChatGateway - ? 'all-saved-servers' - : scope, - ), - restored, + unawaited( + _workspaceBinding!.start(initialSessionId: widget.initialSessionId), ); } @@ -134,7 +122,6 @@ mixin _ChatScreenWorkspace on State { } _workspaceBinding?.dispose(); _workspaceBinding = null; - _unbindFloat(); if (_workspaceScope != null && scope != _workspaceScope) { _workspace.restoreLayout(ChatWorkspaceSnapshot.fromLayout(null, null)!); _forgetRecentSessions(); @@ -323,7 +310,6 @@ mixin _ChatScreenWorkspace on State { controller: _workspace, onVisibleSessionIdsChanged: _workspaceVisibilityChanged, shortcutsEnabled: _workspaceVisible, - floatFrames: _floatFrames, singlePane: !showsListBesideDetail(context), mobilePeeks: true, paneTitle: (pane) => diff --git a/app/lib/features/chat/conversation/chat_effort_control.dart b/app/lib/features/chat/conversation/chat_effort_control.dart index de429570..8ebe1e5e 100644 --- a/app/lib/features/chat/conversation/chat_effort_control.dart +++ b/app/lib/features/chat/conversation/chat_effort_control.dart @@ -159,6 +159,8 @@ class _ChatEffortControlState extends State { ); } return MenuAnchor( + // Above every floating window, and not clipped to one. + useRootOverlay: true, menuChildren: [ Padding( padding: const EdgeInsets.fromLTRB(12, 8, 12, 4), diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 1951b0a8..5aa31dfc 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -1,3 +1,4 @@ +import '../../../shell/windows/window_scope.dart'; import '../../terminal/terminal_open_action.dart'; import 'dart:async'; @@ -1429,6 +1430,15 @@ class _ChatThreadViewState extends State { ], moreActions: [ ?widget.sidebarControl, + // A window's own title bar names the chat, and its narrow action + // bar has no room for the title that opens the details. + if (WindowScope.maybeOf(context) != null) + ChatBarAction( + label: 'Chat details', + onPressed: _openInfo, + materialIcon: Icons.info_outline, + cupertinoIcon: CupertinoIcons.info, + ), ...widget.paneControls, chatShellRunMenuAction(onPressed: _runShellFromMenu), if (_shellRuns.finishedIds.isNotEmpty) diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 8a94c568..c9c278d3 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -1,5 +1,6 @@ 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'; @@ -20,9 +21,7 @@ import 'package:flutter/services.dart'; import '../../core/api_gateway.dart'; import '../../core/servers/server_scope.dart'; -import 'workspace/chat_float_binding.dart'; import 'workspace/chat_float_shortcut.dart'; -import 'workspace/chat_float_store.dart'; import 'workspace/chat_workspace_binding.dart'; import 'workspace/chat_workspace_snapshot.dart'; import 'workspace/chat_workspace_store.dart'; @@ -74,6 +73,7 @@ class ChatScreen extends StatefulWidget { this.onAvailableSessionsChanged, this.persistWorkspace = false, this.runtime, + this.windows, }); final ApiGateway gateway; @@ -83,6 +83,10 @@ class ChatScreen extends StatefulWidget { /// 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; @@ -137,6 +141,7 @@ class _ChatScreenState extends State ..gateway = widget.gateway ..addListener(_runtimeChanged); _runtime.addSessionReplacedListener(_replacedElsewhere); + _bindWindows(); final initial = widget.initialSessionId; if (initial != null && initial.isNotEmpty) { _workspace.open(initial); @@ -282,12 +287,6 @@ class _ChatScreenState extends State .toList()) { _closePane(pane.id); } - for (final pane - in _workspace.floatingPanes - .where((pane) => pane.sessionId == sessionId) - .toList()) { - _closePane(pane.id); - } unawaited(_sessions.refresh()); } @@ -374,7 +373,7 @@ class _ChatScreenState extends State HardwareKeyboard.instance.removeHandler(_slashFocusKey); _page.dispose(); _workspaceBinding?.dispose(); - _disposeFloat(); + _unbindWindows(); _workspace.removeListener(_workspaceChanged); _workspace.dispose(); _sessions.removeListener(_nextChanged); @@ -402,41 +401,36 @@ class _ChatScreenState extends State : null, useNativeBack: _page.open, pasteTarget: _workspaceVisible && pane.id == _workspace.activePaneId, - // A floating chat is never the active pane, so its composer takes a - // paste while it has the keyboard. - ownsPasteWhenFocused: _workspace.isFloating(pane.id), showBackButton: _page.open || !showsListBesideDetail(context), - paneControls: (paneContext) => _workspace.isFloating(pane.id) - ? _floatControls(pane) - : [ - ChatBarAction( - label: 'Add chat pane', - onPressed: () => _addPane(paneContext), - materialIcon: Icons.add_box_outlined, - cupertinoIcon: CupertinoIcons.plus_square, - ), - if (_workspace.paneCount > 1) - ChatBarAction( - label: 'Open chats (${_workspace.paneCount})', - onPressed: () => _pickPane(paneContext), - materialIcon: Icons.view_quilt_outlined, - cupertinoIcon: CupertinoIcons.square_split_2x2, - ), - 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, - cupertinoIcon: CupertinoIcons.xmark, - ), - ], + paneControls: (paneContext) => [ + ChatBarAction( + label: 'Add chat pane', + onPressed: () => _addPane(paneContext), + materialIcon: Icons.add_box_outlined, + cupertinoIcon: CupertinoIcons.plus_square, + ), + if (_workspace.paneCount > 1) + ChatBarAction( + label: 'Open chats (${_workspace.paneCount})', + onPressed: () => _pickPane(paneContext), + materialIcon: Icons.view_quilt_outlined, + cupertinoIcon: CupertinoIcons.square_split_2x2, + ), + 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, + cupertinoIcon: CupertinoIcons.xmark, + ), + ], ), ); } diff --git a/app/lib/features/chat/windows/chat_window_content.dart b/app/lib/features/chat/windows/chat_window_content.dart new file mode 100644 index 00000000..5ca6e15c --- /dev/null +++ b/app/lib/features/chat/windows/chat_window_content.dart @@ -0,0 +1,68 @@ +import 'package:flutter/material.dart'; + +import '../../../shell/windows/window_entry.dart'; +import '../../../ui/adaptive/window_margins.dart'; +import '../chat_pane_content.dart'; +import 'chat_windows.dart'; + +/// A floating window's chat: the same live view as a tiled pane (see +/// [buildChatPaneContent]), with what a window decides. Before the server +/// has been reached it says so instead of reading a chat. +class ChatWindowContent extends StatelessWidget { + const ChatWindowContent({ + super.key, + required this.windows, + required this.entry, + }); + + final ChatWindows windows; + final WindowEntry entry; + + @override + Widget build(BuildContext context) { + final runtime = windows.runtime; + final sessionId = entry.contentId; + return ListenableBuilder( + listenable: Listenable.merge([ + runtime, + runtime.syncToken, + windows.readiness, + ]), + builder: (context, _) { + // A chat is drawn once: the tiling wins, and this window closes. + if (windows.tiling?.holds(sessionId) ?? false) { + WidgetsBinding.instance.addPostFrameCallback( + (_) => windows.manager.close(entry.id), + ); + return const SizedBox.shrink(); + } + if (!windows.ready) { + return Center( + child: Text( + 'Connecting…', + style: Theme.of(context).textTheme.bodyMedium, + ), + ); + } + // A small window keeps the compact bar insets. + return WindowMargins.compact( + child: buildChatPaneContent( + runtime: runtime, + sessionId: sessionId, + placement: ChatPanePlacement( + syncToken: runtime.syncToken.value, + onBack: () {}, + showBackButton: false, + // Never the active pane: its composer takes a paste while it + // has the keyboard. + ownsPasteWhenFocused: true, + onNewSession: (previousId, session, notice) => windows + .startedNewSession(entry.id, previousId, session, notice), + onSessionClosed: () => windows.sessionClosed(entry.id), + ), + ), + ); + }, + ); + } +} diff --git a/app/lib/features/chat/windows/chat_windows.dart b/app/lib/features/chat/windows/chat_windows.dart new file mode 100644 index 00000000..ef0e9781 --- /dev/null +++ b/app/lib/features/chat/windows/chat_windows.dart @@ -0,0 +1,280 @@ +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 '../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'; + +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); + + /// 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); + runtime.addSessionReplacedListener(_replacedElsewhere); + runtime.sessions.addListener(_rowsChanged); + manager.addListener(_rowsChanged); + readiness.addListener(_rowsChanged); + } + + void dispose() { + if (!_started) return; + _started = false; + FocusManager.instance.removeEarlyKeyEventHandler(_key); + 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() { + 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.toggleGroup(chatWindowKind); + return KeyEventResult.handled; + } +} + +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); +} diff --git a/app/lib/features/chat/workspace/chat_float_binding.dart b/app/lib/features/chat/workspace/chat_float_binding.dart deleted file mode 100644 index 12233a8b..00000000 --- a/app/lib/features/chat/workspace/chat_float_binding.dart +++ /dev/null @@ -1,156 +0,0 @@ -import 'dart:async'; -import 'dart:ui'; - -import 'package:flutter/foundation.dart'; - -import 'chat_float_store.dart'; -import 'chat_workspace_controller.dart'; - -/// The floating chat windows' frames, by pane id. A drag moves a window every -/// pointer event without saving; [commit] marks the end of the drag. A pane -/// keeps its frame while it is docked, so floating it again puts the window -/// back where it was. -class ChatFloatFrames extends ChangeNotifier { - ChatFloatFrames([Map frames = const {}]) - : _frames = {...frames}; - final Map _frames; - int _commits = 0; - - Map get frames => Map.unmodifiable(_frames); - - /// Advances when a move or resize ends (the binding saves then). - int get commits => _commits; - - /// [paneId]'s frame; a window without one opens at the default frame, - /// stepped down and right by [index] so stacked windows stay visible. - Rect rectFor(String paneId, {int index = 0}) => - _frames[paneId] ?? - chatFloatDefaultRect.shift(Offset(32, 32) * index.toDouble()); - - /// Gives [paneId] its opening frame ([rectFor] at [index]) unless it has - /// one, so the window stays put when other windows come and go. - void place(String paneId, {required int index}) { - if (_frames.containsKey(paneId)) return; - move(paneId, rectFor(paneId, index: index)); - } - - void move(String paneId, Rect rect) { - if (_frames[paneId] == rect) return; - _frames[paneId] = rect; - notifyListeners(); - } - - /// Replaces every frame (a restore). - void restore(Map frames) { - if (mapEquals(frames, _frames)) return; - _frames - ..clear() - ..addAll(frames); - notifyListeners(); - } - - void commit() { - _commits++; - notifyListeners(); - } -} - -/// Saves which chats float, whether they show and their windows' frames, and -/// restores them once the workspace layout itself has been restored. -class ChatFloatBinding { - ChatFloatBinding({ - required this.controller, - required this.frames, - required this.store, - this.debounce = const Duration(milliseconds: 250), - }) { - controller.addListener(_changed); - frames.addListener(_framesChanged); - } - - final ChatWorkspaceController controller; - final ChatFloatFrames frames; - final ChatFloatStore store; - final Duration debounce; - ChatFloatRecord? _saved; - bool _loading = true; - bool _disposed = false; - int _commits = 0; - Timer? _timer; - Future _writes = Future.value(); - - /// Frames of panes still open somewhere (tiled or floating); a closed - /// pane's frame is dropped. - ChatFloatRecord get _current { - final open = { - for (final pane in controller.panes) pane.id, - for (final pane in controller.floatingPanes) pane.id, - }; - return ChatFloatRecord( - panes: controller.floatingPanes, - shown: controller.floatShown, - frames: { - for (final MapEntry(:key, :value) in frames.frames.entries) - if (open.contains(key)) key: value, - }, - ); - } - - /// Call after the workspace layout restored, so a saved float can tell - /// whether its chat is already open in the tiling. - Future start() async { - ChatFloatRecord? record; - try { - record = await store.read(); - } on Object { - // Unavailable preferences leave the default frames and no float. - } - if (_disposed) return; - if (record != null) { - _saved = record; - _commits = frames.commits; - frames.restore(record.frames); - if (record.panes.isNotEmpty && controller.floatingPanes.isEmpty) { - controller.restoreFloats(record.panes, shown: record.shown); - } - } - _loading = false; - _changed(); - } - - void _framesChanged() { - if (frames.commits == _commits) return; - _commits = frames.commits; - _changed(); - } - - void _changed() { - if (_disposed || _loading || _current == _saved) return; - _timer?.cancel(); - _timer = Timer(debounce, flush); - } - - Future flush() { - _timer?.cancel(); - _timer = null; - final record = _current; - if (_loading || record == _saved) return _writes; - _saved = record; - _writes = _writes.then((_) async { - try { - await store.write(record); - } on Object { - // A storage failure must not interrupt the chat. - } - }); - return _writes; - } - - void dispose() { - if (_disposed) return; - controller.removeListener(_changed); - frames.removeListener(_framesChanged); - unawaited(flush()); - _disposed = true; - } -} diff --git a/app/lib/features/chat/workspace/chat_float_host.dart b/app/lib/features/chat/workspace/chat_float_host.dart deleted file mode 100644 index 61c9f17e..00000000 --- a/app/lib/features/chat/workspace/chat_float_host.dart +++ /dev/null @@ -1,337 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/material.dart'; -import 'package:flutter/scheduler.dart'; -import 'package:flutter/services.dart'; - -import '../../../ui/floating/floating_layer.dart'; -import '../../../ui/motion/motion.dart'; -import '../../../ui/motion/surface_visibility.dart'; -import '../ui/sessions/chat_adaptive.dart'; -import 'chat_float_binding.dart'; -import 'chat_float_shortcut.dart'; -import 'chat_float_window.dart'; -import 'chat_workspace_controller.dart'; - -/// The split workspace ([child]) with its floating chats over the app: their -/// windows, show and hide motion, focus and shortcut (see -/// [chatFloatShortcut]). [content] is a floating pane's live view, moved here -/// from the tiling rather than rebuilt. -/// -/// The windows show while [enabled] (a wide layout), over every destination, -/// like the floating terminal. They show and hide together. -class ChatFloatHost extends StatefulWidget { - const ChatFloatHost({ - super.key, - required this.controller, - required this.frames, - required this.enabled, - required this.title, - required this.content, - required this.scope, - required this.focusedPane, - required this.onFocusPane, - required this.child, - }); - - final ChatWorkspaceController controller; - final ChatFloatFrames frames; - final bool enabled; - final String Function(ChatWorkspacePane pane) title; - final Widget Function(ChatWorkspacePane pane) content; - - /// A floating pane's focus scope. - final FocusScopeNode? Function(ChatWorkspacePane pane) scope; - - /// The tiled pane with the keyboard, which the shortcut floats when no - /// chat floats yet. - final ChatWorkspacePane? Function() focusedPane; - final ValueChanged? onFocusPane; - final Widget child; - - @override - State createState() => _ChatFloatHostState(); -} - -class _ChatFloatHostState extends State { - bool _visible = false; - Set _paneIds = const {}; - FocusNode? _previous; - - @override - void initState() { - super.initState(); - FocusManager.instance.addEarlyKeyEventHandler(_key); - widget.controller.addListener(_sync); - WidgetsBinding.instance.addPostFrameCallback((_) => _sync()); - } - - @override - void didUpdateWidget(covariant ChatFloatHost oldWidget) { - super.didUpdateWidget(oldWidget); - if (oldWidget.controller != widget.controller) { - oldWidget.controller.removeListener(_sync); - widget.controller.addListener(_sync); - } - if (oldWidget.enabled != widget.enabled) { - WidgetsBinding.instance.addPostFrameCallback((_) => _sync()); - } - } - - @override - void dispose() { - FocusManager.instance.removeEarlyKeyEventHandler(_key); - widget.controller.removeListener(_sync); - super.dispose(); - } - - void _sync() { - if (!mounted) return; - final panes = widget.controller.floatingPanes; - final ids = {for (final pane in panes) pane.id}; - final visible = widget.enabled && widget.controller.floatShown; - for (final (index, pane) in panes.indexed) { - widget.frames.place(pane.id, index: index); - } - if (panes.isEmpty) { - // Docked or closed: the views went back to the tiling. - _previous = null; - } else if (visible != _visible) { - if (visible) { - _remember(); - _focusSoon(panes.last); - } else { - _release(); - } - } else if (visible) { - // A newly floated chat takes the keyboard. - final added = panes.where((p) => !_paneIds.contains(p.id)).lastOrNull; - if (added != null) _focusSoon(added); - } - _paneIds = ids; - if (visible != _visible) setState(() => _visible = visible); - } - - bool _inside(FocusNode node) => widget.controller.floatingPanes.any((pane) { - final scope = widget.scope(pane); - return scope != null && - (identical(node, scope) || node.ancestors.contains(scope)); - }); - - void _remember() { - final current = FocusManager.instance.primaryFocus; - if (current == null || _inside(current)) return; - _previous = identical(current, FocusManager.instance.rootScope) - ? null - : current; - } - - void _focusSoon(ChatWorkspacePane pane) { - WidgetsBinding.instance - ..addPostFrameCallback((_) { - if (!mounted || !widget.controller.isFloating(pane.id)) return; - final focus = widget.onFocusPane; - if (focus != null) { - focus(pane); - } else { - widget.scope(pane)?.requestFocus(); - } - }) - ..ensureVisualUpdate(); - } - - /// Gives the keyboard back to what had it before the chats showed, if a - /// floating chat has it now. - void _release() { - final previous = _previous; - _previous = null; - final current = FocusManager.instance.primaryFocus; - if (current == null || !_inside(current)) return; - if (previous != null && - previous.context != null && - previous.canRequestFocus) { - previous.requestFocus(); - } else { - current.unfocus(); - } - } - - /// 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 (!mounted || - !widget.enabled || - !chatFloatShortcut(event, HardwareKeyboard.instance)) { - return KeyEventResult.ignored; - } - final controller = widget.controller; - if (controller.floatingPanes.isEmpty) { - final pane = widget.focusedPane(); - if (pane == null || !controller.canFloat(pane.id)) { - return KeyEventResult.ignored; - } - if (event is KeyDownEvent) controller.float(pane.id); - return KeyEventResult.handled; - } - if (event is KeyDownEvent) controller.toggleFloatShown(); - return KeyEventResult.handled; - } - - @override - Widget build(BuildContext context) { - final panes = widget.controller.floatingPanes; - final cupertino = - chatControlsStyleOf(context) == ChatControlsStyle.cupertino; - return Stack( - fit: StackFit.expand, - children: [ - widget.child, - for (final (index, pane) in panes.indexed) - Positioned.fill( - key: ValueKey(pane.id), - // Shown over every destination; the window's motion keeps - // running there (see [_ChatFloatSlot]). - child: FloatingLayer( - open: _visible, - coverOverlay: true, - builder: (context, bounds) => [ - ListenableBuilder( - listenable: widget.frames, - builder: (context, _) => _ChatFloatSlot( - visible: _visible, - rect: widget.frames.rectFor(pane.id, index: index), - currentRect: () => - widget.frames.rectFor(pane.id, index: index), - onMove: (rect) => widget.frames.move(pane.id, rect), - onCommit: widget.frames.commit, - bounds: bounds, - title: widget.title(pane), - cupertino: cupertino, - onDock: () => widget.controller.dock(pane.id), - onHide: () => widget.controller.setFloatShown(false), - child: widget.content(pane), - ), - ), - ], - ), - ), - ], - ); - } -} - -/// One floating chat's window and its own grow-and-fade motion, so a chat -/// floated while the others show animates in alone. -class _ChatFloatSlot extends StatefulWidget { - const _ChatFloatSlot({ - required this.visible, - required this.rect, - required this.currentRect, - required this.onMove, - required this.onCommit, - required this.bounds, - required this.title, - required this.cupertino, - required this.onDock, - required this.onHide, - required this.child, - }); - - final bool visible; - final Rect rect; - final Rect Function() currentRect; - final ValueChanged onMove; - final VoidCallback onCommit; - final Size bounds; - final String title; - final bool cupertino; - final VoidCallback onDock; - final VoidCallback onHide; - final Widget child; - - @override - State<_ChatFloatSlot> createState() => _ChatFloatSlotState(); -} - -class _ChatFloatSlotState extends State<_ChatFloatSlot> - implements TickerProvider { - Ticker? _ticker; - - /// A ticker the hidden destination's [TickerMode] does not mute: the - /// window must still show and hide over another destination, and a - /// TickerMode cannot re-enable what an ancestor turned off. - @override - Ticker createTicker(TickerCallback onTick) { - assert(_ticker == null, 'one reveal ticker per window'); - return _ticker = Ticker(onTick, debugLabel: 'chat float reveal'); - } - - late final AnimationController _reveal = AnimationController( - vsync: this, - duration: Motion.standard, - ); - late final CurvedAnimation _curve = CurvedAnimation( - parent: _reveal, - curve: Motion.curve, - reverseCurve: Curves.easeInCubic, - ); - - @override - void initState() { - super.initState(); - if (widget.visible) { - WidgetsBinding.instance.addPostFrameCallback((_) => _run()); - } - } - - @override - void didUpdateWidget(covariant _ChatFloatSlot oldWidget) { - super.didUpdateWidget(oldWidget); - if (oldWidget.visible != widget.visible) _run(); - } - - void _run() { - if (!mounted) return; - _reveal.duration = Motion.of(context, Motion.standard); - unawaited(widget.visible ? _reveal.forward() : _reveal.reverse()); - } - - @override - void dispose() { - _curve.dispose(); - _reveal.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) => AnimatedBuilder( - animation: _reveal, - builder: (context, _) { - final offstage = !widget.visible && _reveal.isDismissed; - return ChatFloatWindow( - rect: widget.rect, - currentRect: widget.currentRect, - onMove: widget.onMove, - onCommit: widget.onCommit, - bounds: widget.bounds, - title: widget.title, - cupertino: widget.cupertino, - reveal: _curve, - hiding: !widget.visible, - offstage: offstage, - shortcut: chatFloatShortcutLabel(), - onDock: widget.onDock, - onHide: widget.onHide, - // A hidden window's chat pauses its tickers like a hidden tab. - child: TickerMode( - enabled: !offstage, - child: SurfaceVisibility( - shown: !offstage, - current: !offstage, - child: widget.child, - ), - ), - ); - }, - ); -} diff --git a/app/lib/features/chat/workspace/chat_float_shortcut.dart b/app/lib/features/chat/workspace/chat_float_shortcut.dart index 19ec4f17..6d84b172 100644 --- a/app/lib/features/chat/workspace/chat_float_shortcut.dart +++ b/app/lib/features/chat/workspace/chat_float_shortcut.dart @@ -37,7 +37,7 @@ bool chatFloatShortcut( bool _apple(TargetPlatform platform) => platform == TargetPlatform.macOS || platform == TargetPlatform.iOS; -/// The floating chat's shortcut as it reads on this platform, for menus and -/// tooltips. +/// The floating chats' shortcut as it reads on this platform, for menus and +/// tooltips: the Alt chord, which every platform and browser delivers. String chatFloatShortcutLabel([TargetPlatform? platform]) => - _apple(platform ?? defaultTargetPlatform) ? 'Cmd+Y' : 'Ctrl+Y'; + _apple(platform ?? defaultTargetPlatform) ? 'Option+Y' : 'Alt+Y'; diff --git a/app/lib/features/chat/workspace/chat_float_window.dart b/app/lib/features/chat/workspace/chat_float_window.dart deleted file mode 100644 index bd367943..00000000 --- a/app/lib/features/chat/workspace/chat_float_window.dart +++ /dev/null @@ -1,229 +0,0 @@ -import 'package:flutter/cupertino.dart'; -import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; - -import '../../../ui/adaptive/window_margins.dart'; -import '../../terminal/terminal_float_frame.dart' show terminalFloatChrome; -import 'chat_float_store.dart'; - -/// [rect] moved and shrunk to fit inside [bounds], at least the smallest -/// window where the bounds allow it. -Rect fitChatFloat(Rect rect, Size bounds) { - final width = rect.width - .clamp(chatFloatMinSize.width, double.infinity) - .clamp(0.0, bounds.width); - final height = rect.height - .clamp(chatFloatMinSize.height, double.infinity) - .clamp(0.0, bounds.height); - return Rect.fromLTWH( - rect.left.clamp(0.0, bounds.width - width), - rect.top.clamp(0.0, bounds.height - height), - width, - height, - ); -} - -/// A floating chat's window: moved by its title bar, resized from its -/// lower right corner, kept inside [bounds]. It grows and fades in from its -/// place as [reveal] runs forward and leaves the same way in reverse. -class ChatFloatWindow extends StatelessWidget { - const ChatFloatWindow({ - super.key, - required this.rect, - required this.currentRect, - required this.onMove, - required this.onCommit, - required this.bounds, - required this.title, - required this.cupertino, - required this.reveal, - required this.hiding, - this.offstage = false, - required this.shortcut, - required this.onDock, - required this.onHide, - required this.child, - }); - - /// The saved frame; it is drawn fitted inside [bounds]. - final Rect rect; - - /// The frame now: several drag events can arrive before a rebuild. - final Rect Function() currentRect; - final ValueChanged onMove; - - /// A move or resize ended. - final VoidCallback onCommit; - final Size bounds; - final String title; - final bool cupertino; - final Animation reveal; - - /// While the window hides it takes no input. - final bool hiding; - - /// Hidden and settled: kept built (the chat keeps its state) but unpainted. - final bool offstage; - final String shortcut; - final VoidCallback onDock; - final VoidCallback onHide; - final Widget child; - - static const double revealScale = 0.92; - - void _resize(Offset delta) { - final rect = fitChatFloat(currentRect(), bounds); - onMove( - fitChatFloat( - Rect.fromLTWH( - rect.left, - rect.top, - rect.width + delta.dx, - rect.height + delta.dy, - ), - bounds, - ), - ); - } - - @override - Widget build(BuildContext context) { - final rect = fitChatFloat(this.rect, bounds); - final window = SizedBox.fromSize( - size: rect.size, - child: Stack( - children: [ - Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _titleBar(context, rect), - Expanded( - child: MediaQuery.removePadding( - context: context, - removeTop: true, - removeBottom: true, - removeLeft: true, - removeRight: true, - // A small window keeps the compact bar insets. - child: WindowMargins.compact(child: child), - ), - ), - ], - ), - PositionedDirectional(end: 0, bottom: 0, child: _corner()), - ], - ), - ); - return Positioned( - left: rect.left, - top: rect.top, - child: Offstage( - offstage: offstage, - child: IgnorePointer( - ignoring: hiding, - child: ExcludeFocus( - excluding: hiding, - child: FadeTransition( - opacity: reveal, - child: ScaleTransition( - scale: Tween( - begin: revealScale, - end: 1, - ).animate(reveal), - child: Semantics( - container: true, - label: 'Floating chat: $title', - identifier: 'chat-float-window', - child: terminalFloatChrome(context, cupertino, window), - ), - ), - ), - ), - ), - ), - ); - } - - Widget _titleBar(BuildContext context, Rect rect) { - final label = Text( - title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: cupertino - ? CupertinoTheme.of(context).textTheme.navTitleTextStyle - : Theme.of(context).textTheme.titleSmall, - ); - final drag = MouseRegion( - cursor: SystemMouseCursors.move, - child: GestureDetector( - key: const ValueKey('chat-float-title'), - behavior: HitTestBehavior.opaque, - dragStartBehavior: DragStartBehavior.down, - onPanUpdate: (details) => onMove( - fitChatFloat( - fitChatFloat(currentRect(), bounds).shift(details.delta), - bounds, - ), - ), - onPanEnd: (_) => onCommit(), - child: Padding( - padding: const EdgeInsetsDirectional.only(start: 12), - child: Align( - alignment: AlignmentDirectional.centerStart, - child: label, - ), - ), - ), - ); - return Row( - children: [ - Expanded(child: drag), - _button( - 'Dock', - Icons.vertical_split_outlined, - CupertinoIcons.rectangle_split_3x1, - onDock, - ), - _button( - 'Hide floating chats ($shortcut)', - Icons.close, - CupertinoIcons.xmark, - onHide, - ), - ], - ); - } - - Widget _button( - String label, - IconData material, - IconData cupertinoIcon, - VoidCallback onPressed, - ) => cupertino - ? CupertinoButton( - padding: const EdgeInsets.symmetric(horizontal: 8), - onPressed: onPressed, - child: Icon(cupertinoIcon, semanticLabel: label), - ) - : IconButton(tooltip: label, onPressed: onPressed, icon: Icon(material)); - - Widget _corner() => Semantics( - label: 'Resize floating chat', - child: MouseRegion( - cursor: SystemMouseCursors.resizeDownRight, - child: GestureDetector( - key: const ValueKey('chat-float-resize'), - behavior: HitTestBehavior.opaque, - dragStartBehavior: DragStartBehavior.down, - onPanUpdate: (details) => _resize(details.delta), - onPanEnd: (_) => onCommit(), - child: Padding( - padding: const EdgeInsets.all(4), - child: Icon( - cupertino ? CupertinoIcons.arrow_down_right : Icons.south_east, - ), - ), - ), - ), - ); -} diff --git a/app/lib/features/chat/workspace/chat_workspace.dart b/app/lib/features/chat/workspace/chat_workspace.dart index fbb2e13a..6b195f95 100644 --- a/app/lib/features/chat/workspace/chat_workspace.dart +++ b/app/lib/features/chat/workspace/chat_workspace.dart @@ -3,14 +3,11 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import '../../../ui/floating/floating_layer.dart'; import '../../../ui/motion/motion.dart'; import '../../../ui/motion/quick_switch_animation.dart'; import 'chat_center_stage_layout.dart'; import 'chat_center_stage_motion.dart'; import 'chat_center_stage_strip.dart'; -import 'chat_float_binding.dart'; -import 'chat_float_host.dart'; import 'chat_workspace_controller.dart'; import 'chat_workspace_geometry.dart'; import 'chat_mobile_panes.dart'; @@ -45,7 +42,6 @@ class ChatWorkspace extends StatefulWidget { this.onVisibleSessionIdsChanged, this.centerStage, this.paneColor, - this.floatFrames, }); final ChatWorkspaceController controller; final ChatWorkspacePaneBuilder paneBuilder; @@ -65,11 +61,6 @@ class ChatWorkspace extends StatefulWidget { /// A pane's chat colour, for its strip beside the stage. final Color? Function(ChatWorkspacePane)? paneColor; - /// Offers floating chats (see [ChatFloatHost]) in these frames; null for a - /// workspace without them. They show only while the panes are not - /// collapsed. - final ChatFloatFrames? floatFrames; - /// Keyboard navigation only: the owner can focus the target composer. /// Pointer activation leaves text-selection and pointer focus alone. final ValueChanged? onFocusPane; @@ -83,8 +74,7 @@ class _ChatWorkspaceState extends State final _focus = FocusNode(debugLabel: 'Chat workspace'); final Map _panes = {}; - /// Each pane's view keeps its State when it moves into or out of the - /// floating window. + /// Each pane's view keeps its State as the tiling rearranges. final Map _views = {}; late final ChatPaneSwitchMotion _motion; late final ChatCenterStageMotion _stage = ChatCenterStageMotion(vsync: this); @@ -295,13 +285,7 @@ class _ChatWorkspaceState extends State : !collapsed || pane.id == activeId) pane.sessionId, }); - final floating = widget.floatFrames == null - ? const [] - : widget.controller.floatingPanes; - final existing = { - ...panes.map((p) => p.id), - ...floating.map((p) => p.id), - }; + final existing = {...panes.map((p) => p.id)}; _views.removeWhere((id, _) => !existing.contains(id)); for (final id in _panes.keys.where((id) => !existing.contains(id)).toList()) { @@ -342,7 +326,7 @@ class _ChatWorkspaceState extends State edge, }, }; - final surface = chatWorkspaceSurface( + return chatWorkspaceSurface( context: context, backdrop: _backdrop, motion: _motion, @@ -364,21 +348,6 @@ class _ChatWorkspaceState extends State moveTargets[pane.id], ), ); - final frames = widget.floatFrames; - if (frames == null) return surface; - return ChatFloatHost( - controller: widget.controller, - frames: frames, - enabled: !widget.singlePane, - title: (pane) => widget.paneTitle?.call(pane) ?? pane.sessionId, - content: _floatView, - scope: (pane) => _panes[pane.id], - focusedPane: () => widget.controller.panes - .where((pane) => _panes[pane.id]?.hasFocus ?? false) - .firstOrNull, - onFocusPane: widget.onFocusPane, - child: surface, - ); }, ), ), @@ -441,19 +410,6 @@ class _ChatWorkspaceState extends State ); } - /// A floating chat's view: the same keyed content as in the tiling, so - /// floating and docking move it without rebuilding the chat. Its focus - /// hangs from the shell's [FloatingFocusRoot], so it keeps the keyboard - /// while another destination (which excludes this one) shows. - Widget _floatView(ChatWorkspacePane pane) => _paneContent( - pane, - active: true, - peek: false, - mobile: false, - edges: {}, - focusParent: FloatingFocusRoot.maybeOf(context), - ); - Widget _paneContent( ChatWorkspacePane pane, { required bool active, @@ -461,7 +417,6 @@ class _ChatWorkspaceState extends State required bool mobile, required Set edges, Map? moveTargets, - FocusNode? focusParent, }) { var actionBarPointerDown = false; bool preservesStageForActionBar() => @@ -469,7 +424,6 @@ class _ChatWorkspaceState extends State return KeyedSubtree( key: _views.putIfAbsent(pane.id, () => GlobalKey(debugLabel: pane.id)), child: FocusScope( - parentNode: focusParent, node: _panes.putIfAbsent( pane.id, () => FocusScopeNode(debugLabel: pane.id), diff --git a/app/lib/features/chat/workspace/chat_workspace_controller.dart b/app/lib/features/chat/workspace/chat_workspace_controller.dart index 540e605d..a3e5d7c8 100644 --- a/app/lib/features/chat/workspace/chat_workspace_controller.dart +++ b/app/lib/features/chat/workspace/chat_workspace_controller.dart @@ -12,10 +12,9 @@ class ChatWorkspaceController extends ChangeNotifier { ChatWorkspaceNode? _root; String? _active; - /// The chats taken out of the tiling into floating windows, oldest first. - /// They show and hide together. - final List _floating = []; - bool _floatShown = false; + /// Shows the window [sessionId] is out in and returns true, or returns + /// false when it is in none. Set by whoever hosts floating chats. + bool Function(String sessionId)? showOutside; double _mobilePeekFraction = .2; double get mobilePeekFraction => _mobilePeekFraction; void resizeMobilePeek(double fraction) { @@ -56,7 +55,6 @@ class ChatWorkspaceController extends ChangeNotifier { } collect(_root); - _floating.forEach(collect); String id; do { id = 'chat-$kind-${++_serial}'; @@ -70,7 +68,6 @@ class ChatWorkspaceController extends ChangeNotifier { _root = snapshot.root; _active = snapshot.activePaneId; _mobilePeekFraction = snapshot.mobilePeekFraction; - _floating.clear(); _serial = 0; _changed(); return true; @@ -193,12 +190,10 @@ class ChatWorkspaceController extends ChangeNotifier { } void close(String paneId) { - if (_closeFloating(paneId)) return; final before = panes; final index = before.indexWhere((p) => p.id == paneId); if (index < 0) return; _root = _remove(_root!, paneId); - _adoptFloatingIfEmpty(); final after = panes; if (_active == paneId) { _active = after.isEmpty diff --git a/app/lib/features/chat/workspace/chat_workspace_float.dart b/app/lib/features/chat/workspace/chat_workspace_float.dart index 7503b5f4..841a0477 100644 --- a/app/lib/features/chat/workspace/chat_workspace_float.dart +++ b/app/lib/features/chat/workspace/chat_workspace_float.dart @@ -1,30 +1,21 @@ part of 'chat_workspace_controller.dart'; -/// Chats can leave the split tiling for floating windows over the app. They -/// show and hide together. A floating pane keeps its id (and so its live view) -/// while it floats, hides or docks. +/// Chats can leave the split tiling for floating windows over the app (see +/// `ChatWindows`). The tiling keeps none of them: it only asks whether a +/// chat is out in a window before opening it. extension ChatWorkspaceFloat on ChatWorkspaceController { - /// The floating chats, shown or hidden, oldest first. - List get floatingPanes => List.unmodifiable(_floating); - - /// Whether [paneId] floats. - bool isFloating(String paneId) => _floating.any((pane) => pane.id == paneId); - - /// Whether the floating chats are shown (rather than hidden by Ctrl+Y). - bool get floatShown => _floating.isNotEmpty && _floatShown; - - /// Whether [sessionId] is open in the tiling or a floating window. + /// Whether [sessionId] is open in the tiling. bool holdsSession(String sessionId) => - _floating.any((pane) => pane.sessionId == sessionId) || panes.any((pane) => pane.sessionId == sessionId); /// A tiled pane can float while another chat stays in the tiling. bool canFloat(String paneId) => paneCount > 1 && panes.any((pane) => pane.id == paneId); - /// Floats the tiled pane [paneId] and shows every floating chat. - void float(String paneId) { - if (!canFloat(paneId)) return; + /// Takes the tiled pane [paneId] out of the tiling for a window; the pane + /// beside it becomes active. Null when it cannot float. + ChatWorkspacePane? detach(String paneId) { + if (!canFloat(paneId)) return null; final pane = panes.firstWhere((pane) => pane.id == paneId); final index = panes.indexWhere((p) => p.id == paneId); _root = _remove(_root!, paneId); @@ -32,18 +23,20 @@ extension ChatWorkspaceFloat on ChatWorkspaceController { final after = panes; _active = after[index.clamp(0, after.length - 1)].id; } - _floating.add(pane); - _floatShown = true; _changed(); + return pane; } - /// Puts the floating chat [paneId] back into the tiling, to the right of - /// the active pane, and makes it the active pane. - void dock(String paneId) { - final at = _floating.indexWhere((pane) => pane.id == paneId); - if (at < 0) return; - final pane = _floating.removeAt(at); - final split = _id('split'); + /// Puts the chat [sessionId] back from its window into the tiling, to the + /// right of the active pane, and makes it the active pane. + void dock(String sessionId) { + if (sessionId.isEmpty) return; + final existing = panes.where((p) => p.sessionId == sessionId).firstOrNull; + if (existing != null) { + activate(existing.id); + return; + } + final pane = ChatWorkspacePane(_id('pane'), sessionId); if (_root == null) { _root = pane; } else { @@ -51,93 +44,27 @@ extension ChatWorkspaceFloat on ChatWorkspaceController { _root = _replace( _root!, target.id, - ChatWorkspaceSplit(split, ChatSplitAxis.horizontal, target, pane), + ChatWorkspaceSplit( + _id('split'), + ChatSplitAxis.horizontal, + target, + pane, + ), ); } _active = pane.id; _changed(); } - void setFloatShown(bool shown) { - if (_floating.isEmpty || _floatShown == shown) return; - _floatShown = shown; - _changed(); - } + /// Opening a chat that is out in a window shows that window instead. + bool _showFloating(String sessionId) => showOutside?.call(sessionId) ?? false; - void toggleFloatShown() => setFloatShown(!_floatShown); - - /// Restores saved floating chats, skipping any whose session is already - /// open or whose pane id is taken. With no tiled pane the first becomes - /// the tiling instead. Returns how many were restored. - int restoreFloats(List saved, {required bool shown}) { - var restored = 0; - for (final pane in saved) { - if (holdsSession(pane.sessionId) || _taken(pane.id)) continue; - if (_root == null) { - _root = pane; - _active = pane.id; - } else { - _floating.add(pane); - } - restored++; - } - if (restored == 0) return 0; - _floatShown = shown; - _changed(); - return restored; - } - - bool _taken(String id) { - bool inTree(ChatWorkspaceNode? node) => - node != null && - (node.id == id || - node is ChatWorkspaceSplit && - (inTree(node.first) || inTree(node.second))); - return inTree(_root) || isFloating(id); - } - - /// Opening a floating chat (from the list, a link) shows the floats. - bool _showFloating(String sessionId) { - if (!_floating.any((pane) => pane.sessionId == sessionId)) return false; - setFloatShown(true); - return true; - } - - bool _closeFloating(String paneId) { - final at = _floating.indexWhere((pane) => pane.id == paneId); - if (at < 0) return false; - _floating.removeAt(at); - _changed(); - return true; - } - - /// The tiling never empties while a chat floats: the oldest one docks. - void _adoptFloatingIfEmpty() { - if (_root != null || _floating.isEmpty) return; - _root = _floating.removeAt(0); - } - - /// `/new` in a floating chat keeps it floating under the new session. + /// A tiled chat moved to a session that is out in a window: the window + /// stays and the tiled pane closes. bool _replaceFloating(String oldId, String newId) { - final at = _floating.indexWhere((pane) => pane.sessionId == oldId); - if (at >= 0) { - final pane = _floating[at]; - final elsewhere = - panes.any((p) => p.sessionId == newId) || - _floating.any((p) => p.sessionId == newId); - if (elsewhere) { - _closeFloating(pane.id); - } else { - _floating[at] = ChatWorkspacePane(pane.id, newId); - _changed(); - } - return true; - } - if (!_floating.any((pane) => pane.sessionId == newId)) return false; - // A tiled chat moved to a session that floats: the float stays. + if (!(showOutside?.call(newId) ?? false)) return false; final tiled = panes.where((p) => p.sessionId == oldId).firstOrNull; if (tiled != null) close(tiled.id); - setFloatShown(true); return true; } } diff --git a/app/lib/features/onboarding/discovery/discovered_server_row.dart b/app/lib/features/onboarding/discovery/discovered_server_row.dart index 6aed4751..6ab33e92 100644 --- a/app/lib/features/onboarding/discovery/discovered_server_row.dart +++ b/app/lib/features/onboarding/discovery/discovered_server_row.dart @@ -113,10 +113,7 @@ class _DiscoveredServerRowState extends State { _choice(context, cupertino, address), Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: Align( - alignment: AlignmentDirectional.centerStart, - child: use, - ), + child: Align(alignment: AlignmentDirectional.centerStart, child: use), ), ], ); diff --git a/app/lib/features/pipelines/widgets/pipeline_controls.dart b/app/lib/features/pipelines/widgets/pipeline_controls.dart index 3dee4153..deb81e3e 100644 --- a/app/lib/features/pipelines/widgets/pipeline_controls.dart +++ b/app/lib/features/pipelines/widgets/pipeline_controls.dart @@ -109,6 +109,8 @@ class PipelineSortButton extends StatelessWidget { ); } return MenuAnchor( + // Above every floating window, and not clipped to one. + useRootOverlay: true, menuChildren: [ for (final option in PipelineSort.values) MenuItemButton( diff --git a/app/lib/features/settings/saved_server_sign_in_step.dart b/app/lib/features/settings/saved_server_sign_in_step.dart index 48589daf..01aabe36 100644 --- a/app/lib/features/settings/saved_server_sign_in_step.dart +++ b/app/lib/features/settings/saved_server_sign_in_step.dart @@ -108,7 +108,9 @@ class _SavedServerSignInStepState extends State { child: CircularProgressIndicator(strokeWidth: 2), ), const SizedBox(width: 12), - Expanded(child: Text('Saved. Checking whether $name needs a sign-in…')), + Expanded( + child: Text('Saved. Checking whether $name needs a sign-in…'), + ), ], ); } diff --git a/app/lib/features/terminal/terminal_shortcuts.dart b/app/lib/features/terminal/terminal_shortcuts.dart index 2e3c169b..abaae335 100644 --- a/app/lib/features/terminal/terminal_shortcuts.dart +++ b/app/lib/features/terminal/terminal_shortcuts.dart @@ -57,11 +57,12 @@ class TerminalShortcutLabels { bool get _apple => platform == TargetPlatform.macOS || platform == TargetPlatform.iOS; - /// The keys that show or hide the terminal, most convenient first. + /// The keys that show or hide the terminal. The Alt chord leads (the + /// button's tooltip names it): every platform and browser delivers it. List get toggle => [ + _apple ? 'Option+T' : 'Alt+T', if (!web && _apple) 'Cmd+T', if (!web || _apple) 'Ctrl+T', - _apple ? 'Option+T' : 'Alt+T', 'Ctrl+`', ]; diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index f88456fd..dd81fd6f 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -1,4 +1,3 @@ -import '../ui/floating/floating_layer.dart'; import '../ui/motion/fade_through_stack.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -423,15 +422,12 @@ class _AdaptiveShellState extends State { ); } - // Floating windows (chats) keep the keyboard over every destination. Widget _destinationStack(List contents) => ListPaneWidthsScope( widths: _paneWidths, - child: FloatingFocusRoot( - child: FadeThroughStack( - key: _destinationStackKey, - index: AppDestination.values.indexOf(_selected), - children: contents, - ), + child: FadeThroughStack( + key: _destinationStackKey, + index: AppDestination.values.indexOf(_selected), + children: contents, ), ); } diff --git a/app/lib/shell/windows/window_host.dart b/app/lib/shell/windows/window_host.dart index c7f2a561..357bb895 100644 --- a/app/lib/shell/windows/window_host.dart +++ b/app/lib/shell/windows/window_host.dart @@ -68,41 +68,55 @@ class _WindowHostState extends State { if (_visible.isEmpty && visible.isNotEmpty) _focus.remember(); if (active == null) { if (_visible.isNotEmpty) _focus.release(); - } else if (active != _active || !_visible.contains(active)) { - _focus.focusSoon(active); - } else if (focused != null && !visible.contains(focused)) { - _focus.focusSoon(active); + } else if (active != _active || + !_visible.contains(active) || + (focused != null && !visible.contains(focused))) { + _focusWindow(active); } _visible = visible; _active = active; setState(() {}); } + /// The window takes the keyboard, then its content places it. + void _focusWindow(String id) { + _focus.focusSoon(id); + final entry = widget.manager.byId(id); + if (entry != null) widget.manager.kinds[entry.kind]?.focusContent(entry); + } + @override Widget build(BuildContext context) { final manager = widget.manager; final windows = manager.windows; _focus.retain({for (final w in windows) w.id}); - return LayoutBuilder( - builder: (context, constraints) { - final bounds = constraints.biggest; - return Stack( - fit: StackFit.expand, - children: [ - for (final entry in windows) - if (manager.kinds[entry.kind] case final kind?) - WindowLayer( - key: ValueKey(entry.id), - manager: manager, - kind: kind, - entry: entry, - visible: manager.isVisible(entry), - bounds: bounds, - focus: _focus, - ), - ], - ); - }, + return ListenableBuilder( + listenable: Listenable.merge([ + for (final kind in manager.kinds.all) ?kind.changes, + ]), + builder: (context, _) => LayoutBuilder( + builder: (context, constraints) { + final bounds = constraints.biggest; + return Stack( + fit: StackFit.expand, + children: [ + for (final entry in windows) + if (manager.kinds[entry.kind] case final kind?) + WindowLayer( + key: ValueKey(entry.id), + manager: manager, + kind: kind, + entry: entry, + visible: + manager.isVisible(entry) && + bounds.width >= kind.minHostWidth, + bounds: bounds, + focus: _focus, + ), + ], + ); + }, + ), ); } } diff --git a/app/lib/shell/windows/window_kind.dart b/app/lib/shell/windows/window_kind.dart index 78ed7b6b..3a98499d 100644 --- a/app/lib/shell/windows/window_kind.dart +++ b/app/lib/shell/windows/window_kind.dart @@ -46,6 +46,17 @@ abstract class WindowKind { List actions(BuildContext context, WindowEntry entry) => const []; + /// Notifies when a title or the actions of this kind's windows change. + Listenable? get changes => null; + + /// The narrowest app this kind's windows show in; below it they hide (and + /// come back when the app widens). + double get minHostWidth => 0; + + /// Puts the keyboard where [entry]'s content wants it (a chat's composer) + /// as its window takes focus. The default leaves it on the window. + void focusContent(WindowEntry entry) {} + /// Called after the user closes the window (the X). void closed(WindowEntry entry) {} diff --git a/app/lib/ui/adaptive/segmented_bar_overflow.dart b/app/lib/ui/adaptive/segmented_bar_overflow.dart index f23c5ba8..64ba8173 100644 --- a/app/lib/ui/adaptive/segmented_bar_overflow.dart +++ b/app/lib/ui/adaptive/segmented_bar_overflow.dart @@ -99,6 +99,8 @@ class SegmentedMoreButton extends StatelessWidget { ); } return MenuAnchor( + // Above every floating window, and not clipped to one. + useRootOverlay: true, menuChildren: [ for (final entry in entries) if (entry.choices.isEmpty) diff --git a/app/lib/ui/floating/floating_layer.dart b/app/lib/ui/floating/floating_layer.dart index 26b82973..5176e868 100644 --- a/app/lib/ui/floating/floating_layer.dart +++ b/app/lib/ui/floating/floating_layer.dart @@ -3,8 +3,8 @@ import 'package:flutter/widgets.dart'; /// A layer of floating windows painted in the app's root overlay, above the /// page, while it keeps its place in the tree (its inherited widgets, focus /// and state stay where it is built). Every [FloatingLayer] shares that one -/// overlay, so windows from different features (the terminal, a floating -/// chat) stack by use: the layer last pressed, focused or opened is on top. +/// overlay. Only the terminal's floating window still uses it; the app's +/// other windows are in the shell's window host. /// /// [builder] returns the windows as [Positioned] children of a [Stack] the /// size of [bounds]: this widget's own box, or the whole overlay when @@ -97,51 +97,3 @@ class _FloatingLayerState extends State { ); } } - -/// A focus parent for floating windows placed above the app's destinations, -/// so a window built inside one destination keeps the keyboard while another -/// destination shows (a hidden destination excludes its own subtree from -/// focus). Windows attach their focus scope here with [maybeOf]. -class FloatingFocusRoot extends StatefulWidget { - const FloatingFocusRoot({super.key, required this.child}); - - final Widget child; - - /// The nearest root's focus node, or null outside one. - static FocusNode? maybeOf(BuildContext context) => - context.dependOnInheritedWidgetOfExactType<_FloatingFocusScope>()?.node; - - @override - State createState() => _FloatingFocusRootState(); -} - -class _FloatingFocusRootState extends State { - final FocusNode _node = FocusNode( - debugLabel: 'floating windows', - canRequestFocus: false, - skipTraversal: true, - ); - - @override - void dispose() { - _node.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) => Focus( - focusNode: _node, - includeSemantics: false, - child: _FloatingFocusScope(node: _node, child: widget.child), - ); -} - -class _FloatingFocusScope extends InheritedWidget { - const _FloatingFocusScope({required this.node, required super.child}); - - final FocusNode node; - - @override - bool updateShouldNotify(_FloatingFocusScope oldWidget) => - oldWidget.node != node; -} diff --git a/app/notes/floating-windows.md b/app/notes/floating-windows.md index 35b7496b..c15a477d 100644 --- a/app/notes/floating-windows.md +++ b/app/notes/floating-windows.md @@ -5,11 +5,11 @@ system; no feature uses it yet (chats move in Phase 2, the terminal in Phase 3). ## Pieces (`lib/shell/windows/`) -- `WindowManager` (`AppWindows.manager`): the open windows bottom to top, frames, +- `WindowManager` (one per `PipelinesApp`): the open windows bottom to top, frames, minimised/maximised, group show/hide, cycling. Saved through `WindowStore` (`pipelines.windows.v1`), one record for every server; server-scoped windows carry their server key and only the current server's are listed. -- `WindowKind` (`AppWindows.kinds`): what a kind of window builds, its title, +- `WindowKind` (registered on the manager's `kinds`): what a kind of window builds, its title, icon, title-bar actions, minimum size and saved data. - `WindowHost`: the windows as plain children of the terminal stage's stack, in the shell page (not an overlay above it), outside every destination. diff --git a/app/test/features/chat/chat_floating_pane_test.dart b/app/test/features/chat/chat_floating_pane_test.dart index dbd58993..729c3549 100644 --- a/app/test/features/chat/chat_floating_pane_test.dart +++ b/app/test/features/chat/chat_floating_pane_test.dart @@ -4,12 +4,18 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/core/servers/server_scope.dart'; +import 'package:pipelines_app/features/chat/chat_runtime.dart'; import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/windows/chat_windows.dart'; import 'package:pipelines_app/features/chat/workspace/chat_float_store.dart'; import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; import 'package:pipelines_app/features/chat/workspace/chat_workspace_store.dart'; -import 'package:pipelines_app/ui/floating/floating_layer.dart'; +import 'package:pipelines_app/shell/windows/window_frame.dart'; +import 'package:pipelines_app/shell/windows/window_host.dart'; +import 'package:pipelines_app/shell/windows/window_kind.dart'; +import 'package:pipelines_app/shell/windows/window_manager.dart'; +import 'package:pipelines_app/shell/windows/window_store.dart'; import 'package:pipelines_app/ui/motion/fade_through_stack.dart'; import 'conversation/chat_thread_fixtures.dart'; @@ -29,6 +35,17 @@ class _Gateway extends FakeChatGateway { } } +class _Store implements WindowStore { + String? value; + @override + Future read() async => value; + @override + Future write(String record) async { + value = record; + return true; + } +} + Finder _thread(String id) => find.byWidgetPredicate( (widget) => widget is ChatThreadView && widget.sessionId == id, skipOffstage: false, @@ -38,45 +55,102 @@ Finder _input(String id) => find.descendant( matching: find.byType(EditableText, skipOffstage: false), skipOffstage: false, ); -ChatWorkspaceController _workspace(WidgetTester tester) => - tester.widget(find.byType(ChatWorkspace)).controller; +ChatWorkspaceController _workspace(WidgetTester tester) => tester + .widget(find.byType(ChatWorkspace, skipOffstage: false)) + .controller; -Future<_Gateway> _mount( - WidgetTester tester, { - Size size = const Size(1800, 1000), - ValueNotifier? destination, -}) async { - tester.view.physicalSize = size; - tester.view.devicePixelRatio = 1; - addTearDown(tester.view.reset); +/// The window whose title is [title]. +Finder _window(String title) => + find.ancestor(of: find.text(title), matching: find.byType(WindowFrame)); + +/// That window's title bar, where it shows and takes input. +Finder _shown(String title) => find + .descendant( + of: _window(title), + matching: find.byKey(const ValueKey('window-title')), + ) + .hitTestable(); + +/// The app in miniature: the Chat destination beside another one, and the +/// window host above both, with app-lifetime chat state. +class _App { + _App(this.store); + final _Store store; final gateway = _Gateway()..history = (_) async => chatPage([]); - bindServerIdentity(gateway, 'server-a'); - addTearDown(gateway.close); - final chat = ChatScreen(gateway: gateway, persistWorkspace: true); - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: destination == null - ? chat - // As the shell keeps destinations: the hidden one is muted, - // unfocusable and takes no input. - : FloatingFocusRoot( - child: ValueListenableBuilder( - valueListenable: destination, - builder: (context, index, _) => FadeThroughStack( - index: index, - children: [ - chat, - const Center(child: Text('Runs page')), - ], - ), + final destination = ValueNotifier(0); + final chatBuilt = ValueNotifier(true); + final opened = []; + late final ChatRuntime runtime; + late final WindowManager manager; + late final ChatWindows windows; + + Future start( + WidgetTester tester, { + Size size = const Size(1800, 1000), + }) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + bindServerIdentity(gateway, 'server-a'); + runtime = ChatRuntime(gateway: gateway, serverKey: 'server-a'); + manager = WindowManager( + kinds: WindowKinds(), + store: store, + server: 'server-a', + ); + windows = ChatWindows( + manager: manager, + runtime: runtime, + openInChat: opened.add, + )..start(); + await manager.restore(); + await windows.migrate( + const SharedPreferencesChatFloatStore(serverScope: 'server-a'), + ); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Stack( + fit: StackFit.expand, + children: [ + ListenableBuilder( + listenable: Listenable.merge([destination, chatBuilt]), + builder: (context, _) => FadeThroughStack( + index: destination.value, + children: [ + if (chatBuilt.value) + ChatScreen( + gateway: gateway, + persistWorkspace: true, + runtime: runtime, + windows: windows, + ) + else + const Center(child: Text('Not connected')), + const Center(child: Text('Runs page')), + ], ), ), + Positioned.fill(child: WindowHost(manager: manager)), + ], + ), + ), ), - ), - ); - await tester.pumpAndSettle(); - return gateway; + ); + await tester.pumpAndSettle(); + } + + Future stop(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + windows.dispose(); + runtime.dispose(); + manager.dispose(); + destination.dispose(); + chatBuilt.dispose(); + gateway.close(); + } + + List get floating => [for (final w in windows.windows) w.contentId]; } /// Opens [session]'s pane menu (wherever it is) and chooses [label]. @@ -106,26 +180,34 @@ Future _saved(String a, String b, [String? c]) async { }); } +Future _chord(WidgetTester tester) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyY); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pumpAndSettle(); +} + void main() { testWidgets('Float and Dock move the live chat with its draft', ( tester, ) async { await _saved('a', 'b'); - final gateway = await _mount(tester); + final app = _App(_Store()); + await app.start(tester); final b = tester.state(_thread('b')); await tester.enterText(_input('b'), 'Draft B'); - await _menu(tester, 'b', 'Float (Ctrl+Y)'); + await _menu(tester, 'b', 'Float (Alt+Y)'); final controller = _workspace(tester); - expect(controller.floatingPanes.single.sessionId, 'b'); + expect(app.floating, ['b']); expect(controller.panes.map((p) => p.sessionId), ['a']); - expect(find.byKey(const ValueKey('chat-float-title')), findsOneWidget); expect(tester.state(_thread('b')), same(b)); expect(tester.widget(_input('b')).controller.text, 'Draft B'); - // The window floats over the app, not inside a pane. - final window = tester.getRect( - find.byKey(const ValueKey('chat-float-title')), + // A window over the app, titled by its chat, not a pane. + expect(tester.getSize(_window('Chat b')).width, lessThan(1800 / 2)); + expect( + find.descendant(of: _window('Chat b'), matching: find.byTooltip('Dock')), + findsOneWidget, ); - expect(window.width, lessThan(1800 / 2)); // The lone tiled pane cannot float: the tiling would be empty. await tester.tap( @@ -137,157 +219,164 @@ void main() { .hitTestable(), ); await tester.pumpAndSettle(); - expect(find.text('Float (Ctrl+Y)'), findsNothing); + expect(find.textContaining('Float'), findsNothing); await tester.tapAt(const Offset(5, 995)); await tester.pumpAndSettle(); - await _menu(tester, 'b', 'Dock'); - expect(controller.floatingPanes, isEmpty); + await tester.tap(find.byTooltip('Dock')); + await tester.pumpAndSettle(); + expect(app.floating, isEmpty); expect(controller.panes.map((p) => p.sessionId), ['a', 'b']); expect(tester.state(_thread('b')), same(b)); expect(tester.widget(_input('b')).controller.text, 'Draft B'); expect( - gateway.calls.where( + app.gateway.calls.where( (call) => ['chat_close', 'chat_interrupt'].contains(call.type), ), isEmpty, ); expect(tester.takeException(), isNull); - await tester.pumpWidget(const SizedBox.shrink()); + await app.stop(tester); }); - testWidgets('the floating chat and its frame survive a reload', ( + testWidgets('X closes the window and returns nothing to the tiling', ( tester, ) async { await _saved('a', 'b'); - await _mount(tester); - await _menu(tester, 'b', 'Float (Ctrl+Y)'); + final app = _App(_Store()); + await app.start(tester); + await _menu(tester, 'b', 'Float (Alt+Y)'); + await tester.tap(find.byTooltip('Close')); + await tester.pumpAndSettle(); + expect(app.floating, isEmpty); + expect(_workspace(tester).panes.map((p) => p.sessionId), ['a']); + expect(_thread('b'), findsNothing); + expect(app.gateway.calls.where((c) => c.type == 'chat_close'), isEmpty); + await app.stop(tester); + }); + + testWidgets('popups from a floating chat open above its window', ( + tester, + ) async { + await _saved('a', 'b'); + final app = _App(_Store()); + await app.start(tester); + await _menu(tester, 'b', 'Float (Alt+Y)'); + // The More actions menu, opened from inside the window. + await tester.tap( + find + .descendant( + of: _thread('b'), + matching: find.byTooltip('More actions'), + ) + .hitTestable(), + ); + await tester.pumpAndSettle(); + expect(find.text('Chat details').hitTestable(), findsOneWidget); + // Chat details, the sheet that used to open behind the window. + await tester.tap(find.text('Chat details')); + await tester.pumpAndSettle(); + final sheet = find.byType(BottomSheet); + expect(sheet.hitTestable(), findsOneWidget); + // On the root navigator: wider than the window, and over it. + expect( + tester.getSize(sheet).width, + greaterThan(tester.getSize(_window('Chat b')).width), + ); + expect(_shown('Chat b'), findsNothing); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + + testWidgets('windows and their frames survive a reload, without the Chat ' + 'destination being built', (tester) async { + await _saved('a', 'b'); + final store = _Store(); + var app = _App(store); + await app.start(tester); + await _menu(tester, 'b', 'Float (Alt+Y)'); await tester.drag( - find.byKey(const ValueKey('chat-float-title')), + find.descendant( + of: _window('Chat b'), + matching: find.byKey(const ValueKey('window-title')), + ), const Offset(200, 40), ); await tester.pumpAndSettle(); - await _menu(tester, 'b', 'Hide floating chats (Ctrl+Y)'); - expect(find.byKey(const ValueKey('chat-float-title')), findsNothing); - await tester.pump(const Duration(seconds: 1)); - final preferences = await SharedPreferences.getInstance(); - final record = ChatFloatRecord.decode( - preferences.getString( - scopedServerKey(chatFloatPreferenceKey, 'server-a'), - )!, - )!; - final floated = record.panes.single; - expect(floated.sessionId, 'b'); - expect(record.shown, isFalse); - expect(record.frames[floated.id]?.left, chatFloatDefaultRect.left + 200); - - await tester.pumpWidget(const SizedBox.shrink()); - await _mount(tester); - final controller = _workspace(tester); - expect(controller.floatingPanes.single.sessionId, 'b'); - expect(controller.floatShown, isFalse); - expect(controller.panes.map((p) => p.sessionId), ['a']); - controller.setFloatShown(true); + await tester.tap(find.byTooltip('Minimise')); await tester.pumpAndSettle(); - expect( - tester.getTopLeft(find.byKey(const ValueKey('chat-float-title'))).dx, - greaterThanOrEqualTo(chatFloatDefaultRect.left + 200), - ); - await tester.pumpWidget(const SizedBox.shrink()); + expect(_shown('Chat b'), findsNothing); + await app.stop(tester); + + app = _App(store)..chatBuilt.value = false; + await app.start(tester); + expect(find.text('Not connected'), findsOneWidget); + final entry = app.windows.windows.single; + expect(entry.contentId, 'b'); + expect(entry.minimized, isTrue); + expect(entry.frame.left, chatFloatDefaultRect.left + 200); + await _chord(tester); + expect(_shown('Chat b'), findsOneWidget); + expect(tester.getTopLeft(_window('Chat b')).dx, entry.frame.left); + expect(_thread('b').hitTestable(), findsOneWidget); + // Dock with no tiling opens the chat in the Chat destination. + await tester.tap(find.byTooltip('Dock')); + await tester.pumpAndSettle(); + expect(app.opened, ['b']); + expect(app.floating, isEmpty); + await app.stop(tester); }); - Future chord(WidgetTester tester) async { - await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); - await tester.sendKeyEvent(LogicalKeyboardKey.keyY); - await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); - await tester.pumpAndSettle(); - } - - final titles = find.byKey(const ValueKey('chat-float-title')); - testWidgets('several chats float; the chord hides and shows them all ' 'where they were', (tester) async { await _saved('a', 'b', 'c'); - await _mount(tester); - await _menu(tester, 'b', 'Float (Ctrl+Y)'); - await _menu(tester, 'c', 'Float (Ctrl+Y)'); + final app = _App(_Store()); + await app.start(tester); + await _menu(tester, 'b', 'Float (Alt+Y)'); + await _menu(tester, 'c', 'Float (Alt+Y)'); final controller = _workspace(tester); - expect(controller.floatingPanes.map((p) => p.sessionId), ['b', 'c']); + expect(app.floating, ['b', 'c']); expect(controller.panes.map((p) => p.sessionId), ['a']); - expect(titles, findsNWidgets(2)); // The second window opens stepped from the first, so both show. - final first = tester.getTopLeft(titles.first); - final second = tester.getTopLeft(titles.last); + final first = tester.getTopLeft(_window('Chat b')); + final second = tester.getTopLeft(_window('Chat c')); expect(second.dx, greaterThan(first.dx)); - await tester.drag(titles.first, const Offset(300, 100)); - await tester.pumpAndSettle(); - final moved = tester.getTopLeft(titles.first); - expect(moved.dx, greaterThan(first.dx + 200)); - await chord(tester); - expect(controller.floatShown, isFalse); - expect(titles, findsNothing); - await chord(tester); - expect(controller.floatShown, isTrue); - expect(titles, findsNWidgets(2)); - expect(tester.getTopLeft(titles.first), moved); - expect(tester.getTopLeft(titles.last), second); + await _chord(tester); + expect( + find.byKey(const ValueKey('window-title')).hitTestable(), + findsNothing, + ); + await _chord(tester); + expect(tester.getTopLeft(_window('Chat b')), first); + expect(tester.getTopLeft(_window('Chat c')), second); // Docking one leaves the other floating. - await _menu(tester, 'b', 'Dock'); - expect(controller.floatingPanes.map((p) => p.sessionId), ['c']); - expect(titles, findsOneWidget); - - await tester.pump(const Duration(seconds: 1)); - final preferences = await SharedPreferences.getInstance(); - final record = ChatFloatRecord.decode( - preferences.getString( - scopedServerKey(chatFloatPreferenceKey, 'server-a'), - )!, - )!; - expect(record.panes.map((p) => p.sessionId), ['c']); - // The docked chat keeps its frame for its next float. - expect(record.frames, hasLength(2)); + await tester.tap( + find.descendant(of: _window('Chat b'), matching: find.byTooltip('Dock')), + ); + await tester.pumpAndSettle(); + expect(app.floating, ['c']); + expect(controller.panes.map((p) => p.sessionId), ['a', 'b']); expect(tester.takeException(), isNull); - await tester.pumpWidget(const SizedBox.shrink()); + await app.stop(tester); }); - testWidgets('a floating chat moves, types, hides and shows over another ' - 'destination', (tester) async { + testWidgets('a floating chat types, runs its tickers, hides and shows over ' + 'another destination', (tester) async { await _saved('a', 'b'); - final destination = ValueNotifier(0); - addTearDown(destination.dispose); - await _mount(tester, destination: destination); - await _menu(tester, 'b', 'Float (Ctrl+Y)'); - final controller = _workspace(tester); - - destination.value = 1; + final app = _App(_Store()); + await app.start(tester); + await _menu(tester, 'b', 'Float (Alt+Y)'); + app.destination.value = 1; await tester.pumpAndSettle(); expect(find.text('Runs page'), findsOneWidget); - // The chat page is offstage, so finders look past it; the window itself - // paints and takes input in the root overlay. - final title = find.byKey( - const ValueKey('chat-float-title'), - skipOffstage: false, - ); - bool hits(Finder finder) { - final box = tester.renderObject(finder); - return tester - .hitTestOnBinding(tester.getCenter(finder)) - .path - .any((entry) => identical(entry.target, box)); - } - - expect(hits(title), isTrue); - final before = tester.getTopLeft(title); - await tester.drag(title, const Offset(150, 60)); - await tester.pumpAndSettle(); - expect(tester.getTopLeft(title).dx, greaterThan(before.dx + 100)); - expect(tester.getTopLeft(title).dy, greaterThan(before.dy + 20)); + expect(_shown('Chat b'), findsOneWidget); + // Not muted by the hidden Chat destination. + expect(TickerMode.valuesOf(tester.element(_thread('b'))).enabled, isTrue); // The composer takes the keyboard there. final input = _input('b'); - expect(hits(input), isTrue); await tester.tapAt(tester.getCenter(input)); await tester.pump(); final field = tester.widget(input); @@ -296,35 +385,65 @@ void main() { await tester.pump(); expect(field.controller.text, 'From runs'); - // The chord and the window's own hide button both work there. - // The window itself animates away and back, not only the state. - await chord(tester); - expect(controller.floatShown, isFalse); - expect(hits(title), isFalse); - await chord(tester); - expect(controller.floatShown, isTrue); - expect(hits(title), isTrue); - final hide = find.byTooltip( - 'Hide floating chats (Ctrl+Y)', - skipOffstage: false, - ); - expect(hits(hide), isTrue); - await tester.tapAt(tester.getCenter(hide)); - await tester.pumpAndSettle(); - expect(controller.floatShown, isFalse); - expect(hits(title), isFalse); + await _chord(tester); + expect(_shown('Chat b'), findsNothing); + await _chord(tester); + expect(_shown('Chat b'), findsOneWidget); + // Shown again by the chord, the composer has the keyboard at once. + expect(tester.widget(_input('b')).focusNode.hasFocus, isTrue); expect(tester.takeException(), isNull); - await tester.pumpWidget(const SizedBox.shrink()); + await app.stop(tester); }); - testWidgets('narrow layouts offer no Float', (tester) async { + testWidgets('floating chats saved by an older build come back as windows', ( + tester, + ) async { + await _saved('a', 'c'); + final preferences = await SharedPreferences.getInstance(); + await preferences.setString( + scopedServerKey(chatFloatPreferenceKey, 'server-a'), + const ChatFloatRecord( + panes: [ChatWorkspacePane('chat-pane-9', 'b')], + shown: true, + frames: {'chat-pane-9': Rect.fromLTWH(400, 300, 500, 420)}, + ).encode(), + ); + final app = _App(_Store()); + await app.start(tester); + expect(app.floating, ['b']); + expect(tester.getTopLeft(_window('Chat b')), const Offset(400, 300)); + expect(_workspace(tester).panes.map((p) => p.sessionId), ['a', 'c']); + await app.stop(tester); + }); + + testWidgets('a chat is drawn once: opening a floating chat from the list ' + 'shows its window', (tester) async { await _saved('a', 'b'); - await _mount(tester, size: const Size(430, 900)); + final app = _App(_Store()); + await app.start(tester); + await _menu(tester, 'b', 'Float (Alt+Y)'); + app.manager.setGroupShown(chatWindowKind, false); + await tester.pumpAndSettle(); + _workspace(tester).open('b'); + await tester.pumpAndSettle(); + expect(_shown('Chat b'), findsOneWidget); + expect(_workspace(tester).panes.map((p) => p.sessionId), ['a']); + expect(_thread('b'), findsOneWidget); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + + testWidgets('narrow layouts offer no Float and show no window', ( + tester, + ) async { + await _saved('a', 'b'); + final app = _App(_Store()); + await app.start(tester, size: const Size(430, 900)); final finder = find.byTooltip('More actions').hitTestable(); await tester.tap(finder.first); await tester.pumpAndSettle(); expect(find.textContaining('Float'), findsNothing); expect(find.text('Open chats (2)'), findsOneWidget); - await tester.pumpWidget(const SizedBox.shrink()); + await app.stop(tester); }); } diff --git a/app/test/features/chat/chat_pane_move_test.dart b/app/test/features/chat/chat_pane_move_test.dart index c5ae8e8a..10a0fcee 100644 --- a/app/test/features/chat/chat_pane_move_test.dart +++ b/app/test/features/chat/chat_pane_move_test.dart @@ -82,7 +82,10 @@ Future _openMenu(WidgetTester tester, String session) async { MenuItemButton _item(WidgetTester tester, String label) => tester.widget( - find.ancestor(of: find.text(label), matching: find.byType(MenuItemButton)), + find.ancestor( + of: find.text(label), + matching: find.byType(MenuItemButton), + ), ); ChatWorkspaceController _controller(WidgetTester tester) => @@ -205,7 +208,9 @@ void main() { final gateway = _Gateway()..history = (_) async => chatPage([]); addTearDown(gateway.close); await tester.pumpWidget( - MaterialApp(home: Scaffold(body: ChatScreen(gateway: gateway))), + MaterialApp( + home: Scaffold(body: ChatScreen(gateway: gateway)), + ), ); await tester.pumpAndSettle(); await tester.tap(find.text('Chat a').first); diff --git a/app/test/features/chat/conversation/chat_bar_tint_test.dart b/app/test/features/chat/conversation/chat_bar_tint_test.dart index 8ac9ca46..d2c8a974 100644 --- a/app/test/features/chat/conversation/chat_bar_tint_test.dart +++ b/app/test/features/chat/conversation/chat_bar_tint_test.dart @@ -244,9 +244,6 @@ void main() { isSameColorAs(tint.foreground), ); // Outside the bar the theme's tint is untouched. - expect( - CupertinoTheme.of(context).primaryColor, - isNot(tint.foreground), - ); + expect(CupertinoTheme.of(context).primaryColor, isNot(tint.foreground)); }); } diff --git a/app/test/features/chat/conversation/chat_unfocused_paste_routing_test.dart b/app/test/features/chat/conversation/chat_unfocused_paste_routing_test.dart index 17c13724..b4a546fb 100644 --- a/app/test/features/chat/conversation/chat_unfocused_paste_routing_test.dart +++ b/app/test/features/chat/conversation/chat_unfocused_paste_routing_test.dart @@ -201,9 +201,7 @@ void main() { await done(tester); }); - testWidgets('a focused floating composer takes pasted files', ( - tester, - ) async { + testWidgets('a focused floating composer takes pasted files', (tester) async { final accepts = {}; ChatClipboardPaste source(String id) => ChatClipboardPaste( subscribe: (onFiles, canAccept, onError, onText, canAcceptText) { diff --git a/app/test/features/chat/files/files_panel_mutations_test.dart b/app/test/features/chat/files/files_panel_mutations_test.dart index df1bbe9a..4cc53905 100644 --- a/app/test/features/chat/files/files_panel_mutations_test.dart +++ b/app/test/features/chat/files/files_panel_mutations_test.dart @@ -271,19 +271,20 @@ void main() { expect(mounted.gateway.listings, 2); }); - testWidgets('A refused move is shown in the server\'s words until dismissed', ( - tester, - ) async { - final mounted = await pump(tester); - const refusal = '$shown/docs/notes.txt already exists'; - mounted.gateway.refusals['move_path'] = refusal; - await dragOnto(tester, 'notes.txt', 'docs'); - expect(find.text(refusal), findsOneWidget); - expect(mounted.gateway.listings, 2, reason: 'reloaded all the same'); - await tester.tap(find.text('Dismiss')); - await tester.pumpAndSettle(); - expect(find.text(refusal), findsNothing); - }); + testWidgets( + 'A refused move is shown in the server\'s words until dismissed', + (tester) async { + final mounted = await pump(tester); + const refusal = '$shown/docs/notes.txt already exists'; + mounted.gateway.refusals['move_path'] = refusal; + await dragOnto(tester, 'notes.txt', 'docs'); + expect(find.text(refusal), findsOneWidget); + expect(mounted.gateway.listings, 2, reason: 'reloaded all the same'); + await tester.tap(find.text('Dismiss')); + await tester.pumpAndSettle(); + expect(find.text(refusal), findsNothing); + }, + ); test('canDropEntryOn refuses files, itself and its own subtree', () { const docs = DirectoryEntry( diff --git a/app/test/features/chat/ui/sessions/session_attention_test.dart b/app/test/features/chat/ui/sessions/session_attention_test.dart index ce79e2fb..bedc1e14 100644 --- a/app/test/features/chat/ui/sessions/session_attention_test.dart +++ b/app/test/features/chat/ui/sessions/session_attention_test.dart @@ -39,11 +39,10 @@ void main() { }); test('only visible assistant reply text is unread', () { - bool attention(Map event) => - chatSessionFrameEffect({ - 'type': 'chat_event', - 'chat_event': {'session_id': 's', ...event}, - })!.attention; + bool attention(Map event) => chatSessionFrameEffect({ + 'type': 'chat_event', + 'chat_event': {'session_id': 's', ...event}, + })!.attention; for (final status in ['running', 'completed', 'error']) { expect( attention({ @@ -67,11 +66,7 @@ void main() { expect(attention({'kind': 'text', 'delta': ' \n'}), isFalse); for (final messageKind in ['notice', 'agent_report']) { expect( - attention({ - 'kind': 'text', - 'delta': 'x', - 'message_kind': messageKind, - }), + attention({'kind': 'text', 'delta': 'x', 'message_kind': messageKind}), isFalse, ); } diff --git a/app/test/features/chat/ui/transcript/chat_copy_gutter_test.dart b/app/test/features/chat/ui/transcript/chat_copy_gutter_test.dart index c66a4070..ab429dc4 100644 --- a/app/test/features/chat/ui/transcript/chat_copy_gutter_test.dart +++ b/app/test/features/chat/ui/transcript/chat_copy_gutter_test.dart @@ -76,34 +76,36 @@ void main() { expect(_opacity(tester), 1); }); - testWidgets('desktop shows it on hover and focus, and keeps semantics', ( - tester, - ) async { - final semantics = tester.ensureSemantics(); - await tester.pumpWidget(_host(48)); - expect(_opacity(tester), 0); - // Hidden, it is still reachable by a screen reader. - expect( - tester.getSemantics(_copy), - isSemantics(tooltip: 'Copy', isButton: true, isFocusable: true), - ); + testWidgets( + 'desktop shows it on hover and focus, and keeps semantics', + (tester) async { + final semantics = tester.ensureSemantics(); + await tester.pumpWidget(_host(48)); + expect(_opacity(tester), 0); + // Hidden, it is still reachable by a screen reader. + expect( + tester.getSemantics(_copy), + isSemantics(tooltip: 'Copy', isButton: true, isFocusable: true), + ); - final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); - addTearDown(mouse.removePointer); - await mouse.addPointer(location: Offset.zero); - await mouse.moveTo(tester.getCenter(find.text('The answer text'))); - await tester.pumpAndSettle(); - expect(_opacity(tester), 1); - await mouse.moveTo(const Offset(5, 590)); - await tester.pumpAndSettle(); - expect(_opacity(tester), 0); + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + addTearDown(mouse.removePointer); + await mouse.addPointer(location: Offset.zero); + await mouse.moveTo(tester.getCenter(find.text('The answer text'))); + await tester.pumpAndSettle(); + expect(_opacity(tester), 1); + await mouse.moveTo(const Offset(5, 590)); + await tester.pumpAndSettle(); + expect(_opacity(tester), 0); - // Keyboard focus reveals it too. - await tester.sendKeyEvent(LogicalKeyboardKey.tab); - await tester.pumpAndSettle(); - expect(_opacity(tester), 1); - semantics.dispose(); - }, variant: TargetPlatformVariant.only(TargetPlatform.macOS)); + // Keyboard focus reveals it too. + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pumpAndSettle(); + expect(_opacity(tester), 1); + semantics.dispose(); + }, + variant: TargetPlatformVariant.only(TargetPlatform.macOS), + ); for (final (width, inGutter) in [(1400.0, true), (560.0, false)]) { testWidgets('a ${width.toInt()} px conversation puts Copy ' diff --git a/app/test/features/chat/windows/chat_windows_test.dart b/app/test/features/chat/windows/chat_windows_test.dart new file mode 100644 index 00000000..b0471607 --- /dev/null +++ b/app/test/features/chat/windows/chat_windows_test.dart @@ -0,0 +1,278 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/chat_runtime.dart'; +import 'package:pipelines_app/features/chat/windows/chat_windows.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_float_store.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_controller.dart'; +import 'package:pipelines_app/shell/windows/window_kind.dart'; +import 'package:pipelines_app/shell/windows/window_manager.dart'; +import 'package:pipelines_app/ui/input/keyboard_owner.dart'; + +class _Gateway implements ApiGateway { + final calls = []; + @override + Stream get frames => const Stream.empty(); + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(type); + if (type == 'chat_sessions') { + return { + 'chat_sessions': [ + {'id': 'a', 'title': 'Chat a'}, + {'id': 'b', 'title': 'Chat b'}, + ], + }; + } + return {}; + } +} + +class _Legacy implements ChatFloatStore { + _Legacy(this.record); + ChatFloatRecord? record; + @override + Future read() async => record; + @override + Future write(ChatFloatRecord value) async { + record = value; + return true; + } +} + +class _Harness { + _Harness() { + windows = ChatWindows( + manager: manager, + runtime: runtime, + openInChat: opened.add, + )..start(); + } + final gateway = _Gateway(); + late final runtime = ChatRuntime(gateway: gateway, serverKey: 'home'); + final manager = WindowManager(kinds: WindowKinds(), server: 'home'); + final opened = []; + final docked = []; + final floated = []; + final tiled = {}; + bool canFloat = true; + late final ChatWindows windows; + + void mountTiling() => windows.tiling = ChatTiling( + holds: tiled.contains, + dock: docked.add, + canFloatActive: () => canFloat, + floatActive: () { + floated.add('active'); + windows.float('a'); + }, + ); + + List get chats => [for (final w in windows.windows) w.contentId]; + + void dispose() { + windows.dispose(); + runtime.dispose(); + manager.dispose(); + } +} + +Future _chord( + WidgetTester tester, [ + LogicalKeyboardKey modifier = LogicalKeyboardKey.altLeft, +]) async { + await tester.sendKeyDownEvent(modifier); + await tester.sendKeyEvent(LogicalKeyboardKey.keyY); + await tester.sendKeyUpEvent(modifier); + await tester.pump(); +} + +void main() { + late _Harness h; + // Built inside each test: the chord's handler belongs to that test's + // focus manager. + void start() { + h = _Harness(); + addTearDown(h.dispose); + } + + Future wide(WidgetTester tester, {Size size = const Size(1280, 800)}) { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + start(); + return tester.pumpWidget(const MaterialApp(home: SizedBox())); + } + + test('a window is a server-scoped chat entry; show raises it', () { + start(); + h.windows.float('a'); + h.windows.float('b'); + final a = h.manager.find(chatWindowKind, 'a')!; + expect(a.serverKey, 'home'); + expect(a.frame, chatFloatDefaultRect); + expect(h.windows.show('a'), isTrue); + expect(h.manager.active!.contentId, 'a'); + expect(h.windows.show('zz'), isFalse); + h.manager.setGroupShown(chatWindowKind, false); + expect(h.windows.show('b'), isTrue); + expect(h.manager.groupShown(chatWindowKind), isTrue); + }); + + test('Dock returns the chat to the tiling, or opens Chat without one', () { + start(); + h.windows.float('a'); + h.windows.float('b'); + h.windows.dock(h.manager.find(chatWindowKind, 'a')!); + expect(h.opened, ['a']); + h.mountTiling(); + h.windows.dock(h.manager.find(chatWindowKind, 'b')!); + expect(h.docked, ['b']); + expect(h.chats, isEmpty); + }); + + test('/new moves the window to the new session; /close closes it', () { + start(); + h.windows.float('a'); + final id = h.manager.find(chatWindowKind, 'a')!.id; + h.windows.startedNewSession(id, 'a', {'id': 'a2', 'title': 'Fresh'}, 'New'); + expect(h.chats, ['a2']); + expect(h.runtime.startNotice, (id: 'a2', notice: 'New')); + expect(h.runtime.titleFor('a2'), 'Fresh'); + // Another device moves it again. + h.runtime.sessions.onSessionReplaced!('a2', {'id': 'a3'}); + expect(h.chats, ['a3']); + // Into a session the tiling already shows: the duplicate window closes. + h.mountTiling(); + h.tiled.add('t'); + h.windows.startedNewSession(id, 'a3', {'id': 't'}, 'New'); + expect(h.chats, isEmpty); + + h.windows.float('b'); + h.windows.sessionClosed(h.manager.find(chatWindowKind, 'b')!.id); + expect(h.chats, isEmpty); + }); + + test('windows read their rows without the Chat destination', () async { + start(); + h.windows.float('a'); + await pumpEventQueue(); + expect(h.gateway.calls, contains('chat_sessions')); + expect(h.runtime.titleFor('a'), 'Chat a'); + expect(h.runtime.opened.keys, ['a']); + }); + + test('saved floating chats of an older build become windows, once', () async { + start(); + final legacy = _Legacy( + const ChatFloatRecord( + panes: [ChatWorkspacePane('p1', 'a'), ChatWorkspacePane('p2', 'b')], + shown: false, + frames: {'p2': Rect.fromLTWH(300, 200, 500, 400)}, + ), + ); + await h.windows.migrate(legacy); + expect(h.chats, ['a', 'b']); + expect( + h.manager.find(chatWindowKind, 'b')!.frame, + const Rect.fromLTWH(300, 200, 500, 400), + ); + expect(h.manager.groupShown(chatWindowKind), isFalse); + expect(legacy.record!.panes, isEmpty); + h.manager.close(h.manager.find(chatWindowKind, 'a')!.id); + await h.windows.migrate(legacy); + expect(h.chats, ['b']); + + // Windows already saved by this build win over an old record. + final other = _Legacy( + const ChatFloatRecord(panes: [ChatWorkspacePane('p9', 'z')]), + ); + await h.windows.migrate(other); + expect(h.chats, ['b']); + expect(other.record!.panes, isEmpty); + }); + + testWidgets('the chord floats the active pane, then hides and shows every ' + 'chat window', (tester) async { + await wide(tester); + // No tiling and no window: the key is left alone. + await _chord(tester); + expect(h.chats, isEmpty); + h.mountTiling(); + h.canFloat = false; + await _chord(tester); + expect(h.floated, isEmpty); + h.canFloat = true; + await _chord(tester); + expect(h.floated, ['active']); + expect(h.chats, ['a']); + h.windows.float('b'); + + await _chord(tester); + expect(h.manager.groupShown(chatWindowKind), isFalse); + await _chord(tester, LogicalKeyboardKey.controlLeft); + expect(h.manager.groupShown(chatWindowKind), isTrue); + expect(h.floated, ['active']); + // A plain Y is typing. + await tester.sendKeyEvent(LogicalKeyboardKey.keyY); + expect(h.manager.groupShown(chatWindowKind), isTrue); + }); + + testWidgets('a held chord toggles once', (tester) async { + await wide(tester); + h.windows.float('a'); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.keyY); + await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyY); + await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyY); + await tester.sendKeyUpEvent(LogicalKeyboardKey.keyY); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + expect(h.manager.groupShown(chatWindowKind), isFalse); + }); + + testWidgets( + 'on macOS Ctrl+Y in a terminal stays with it; Cmd+Y and Option+Y toggle', + (tester) async { + await wide(tester); + final typing = FocusNode(); + addTearDown(typing.dispose); + final typed = []; + await tester.pumpWidget( + MaterialApp( + home: TypingSurface( + child: Focus( + focusNode: typing, + onKeyEvent: (node, event) { + if (event is KeyDownEvent) typed.add(event.logicalKey); + return KeyEventResult.handled; + }, + child: const SizedBox(height: 40), + ), + ), + ), + ); + h.windows.float('a'); + typing.requestFocus(); + await tester.pump(); + await _chord(tester, LogicalKeyboardKey.controlLeft); + expect(h.manager.groupShown(chatWindowKind), isTrue); + expect(typed, contains(LogicalKeyboardKey.keyY)); + await _chord(tester, LogicalKeyboardKey.metaLeft); + expect(h.manager.groupShown(chatWindowKind), isFalse); + await _chord(tester); + expect(h.manager.groupShown(chatWindowKind), isTrue); + }, + variant: const TargetPlatformVariant({TargetPlatform.macOS}), + ); + + testWidgets('a narrow app never takes the chord', (tester) async { + await wide(tester, size: const Size(430, 900)); + h.mountTiling(); + await _chord(tester); + expect(h.chats, isEmpty); + h.windows.float('a'); + await _chord(tester); + expect(h.manager.groupShown(chatWindowKind), isTrue); + }); +} diff --git a/app/test/features/chat/workspace/chat_center_stage_test.dart b/app/test/features/chat/workspace/chat_center_stage_test.dart index b471c732..545f1df2 100644 --- a/app/test/features/chat/workspace/chat_center_stage_test.dart +++ b/app/test/features/chat/workspace/chat_center_stage_test.dart @@ -281,7 +281,7 @@ void main() { addTearDown(workspace.dispose); addTearDown(stage.dispose); await tester.pumpWidget(host(workspace, stage)); - workspace.float(workspace.panes.first.id); + workspace.detach(workspace.panes.first.id); await tester.pumpAndSettle(); expect(workspace.activePane?.sessionId, 'three'); expect(widthOf(tester, 'three'), 950); @@ -289,7 +289,7 @@ void main() { expect(widthOf(tester, 'two'), 1368 - 12 - 950); expect(find.byType(ChatCenterStageStrip), findsNothing); - workspace.dock(workspace.floatingPanes.single.id); + workspace.dock('one'); await tester.pumpAndSettle(); expect(workspace.activePane?.sessionId, 'one'); expect(widthOf(tester, 'one'), 950); diff --git a/app/test/features/chat/workspace/chat_float_shortcut_test.dart b/app/test/features/chat/workspace/chat_float_shortcut_test.dart index 1864350b..66ffc3e3 100644 --- a/app/test/features/chat/workspace/chat_float_shortcut_test.dart +++ b/app/test/features/chat/workspace/chat_float_shortcut_test.dart @@ -1,245 +1,54 @@ -import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:pipelines_app/features/chat/workspace/chat_float_binding.dart'; import 'package:pipelines_app/features/chat/workspace/chat_float_shortcut.dart'; -import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; -import 'package:pipelines_app/ui/input/keyboard_owner.dart'; -class _Pane extends StatefulWidget { - const _Pane(this.id); - final String id; - @override - State<_Pane> createState() => _PaneState(); -} - -class _PaneState extends State<_Pane> { - final text = TextEditingController(); - final focus = FocusNode(); - @override - void dispose() { - text.dispose(); - focus.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) => Material( - child: TextField( - key: ValueKey('field-${widget.id}'), - controller: text, - focusNode: focus, - ), - ); -} - -Finder _pane(String id) => find.byWidgetPredicate( - (w) => w is _Pane && w.id == id, - skipOffstage: false, +const _y = KeyDownEvent( + physicalKey: PhysicalKeyboardKey.keyY, + logicalKey: LogicalKeyboardKey.keyY, + timeStamp: Duration.zero, ); -class _Harness { - final controller = ChatWorkspaceController() - ..open('a') - ..splitActive('b', ChatSplitAxis.horizontal); - final frames = ChatFloatFrames(); - final typing = FocusNode(debugLabel: 'terminal'); - final typed = []; - - Widget app({bool narrow = false}) => MaterialApp( - home: Scaffold( - body: Column( - children: [ - Expanded( - child: ChatWorkspace( - controller: controller, - floatFrames: frames, - singlePane: narrow, - onFocusPane: (pane) => _focus(pane.sessionId), - paneBuilder: (context, pane, active) => _Pane(pane.sessionId), - ), - ), - TypingSurface( - child: Focus( - focusNode: typing, - onKeyEvent: (node, event) { - if (event is KeyDownEvent && - event.logicalKey == LogicalKeyboardKey.keyY) { - typed.add(event.logicalKey); - } - return KeyEventResult.handled; - }, - child: const SizedBox(height: 40, child: Text('terminal')), - ), - ), - ], - ), - ), - ); - - WidgetTester? tester; - void _focus(String session) => - tester!.state<_PaneState>(_pane(session)).focus.requestFocus(); - - void dispose() { - controller.dispose(); - frames.dispose(); - typing.dispose(); - } -} - -Future _chord( - WidgetTester tester, - LogicalKeyboardKey modifier, { - LogicalKeyboardKey key = LogicalKeyboardKey.keyY, -}) async { - await tester.sendKeyDownEvent(modifier); - await tester.sendKeyEvent(key); - await tester.sendKeyUpEvent(modifier); - await tester.pumpAndSettle(); -} - void main() { - test('the chord is Ctrl+Y, and Cmd+Y on Apple platforms', () { - expect(chatFloatShortcutLabel(TargetPlatform.linux), 'Ctrl+Y'); - expect(chatFloatShortcutLabel(TargetPlatform.windows), 'Ctrl+Y'); - expect(chatFloatShortcutLabel(TargetPlatform.macOS), 'Cmd+Y'); + test('menus and tooltips name the Alt chord', () { + expect(chatFloatShortcutLabel(TargetPlatform.linux), 'Alt+Y'); + expect(chatFloatShortcutLabel(TargetPlatform.windows), 'Alt+Y'); + expect(chatFloatShortcutLabel(TargetPlatform.macOS), 'Option+Y'); }); - Future<_Harness> pump(WidgetTester tester, {bool narrow = false}) async { - tester.view.physicalSize = const Size(1280, 800); - tester.view.devicePixelRatio = 1; - addTearDown(tester.view.reset); - final h = _Harness()..tester = tester; - addTearDown(h.dispose); - await tester.pumpWidget(h.app(narrow: narrow)); - await tester.pumpAndSettle(); - return h; - } - - testWidgets('Ctrl+Y floats the focused pane, then hides and shows it', ( - tester, - ) async { - final h = await pump(tester); - final b = tester.state<_PaneState>(_pane('b')); - await tester.enterText(find.byKey(const ValueKey('field-b')), 'draft'); - await tester.tap(find.byKey(const ValueKey('field-a'))); - await tester.pump(); - // Plain Y and Shift+Y type; only the chord acts. - await tester.sendKeyEvent(LogicalKeyboardKey.keyY); - await _chord(tester, LogicalKeyboardKey.shiftLeft); - expect(h.controller.floatingPanes, isEmpty); - - tester.state<_PaneState>(_pane('b')).focus.requestFocus(); - await tester.pump(); - await _chord(tester, LogicalKeyboardKey.controlLeft); - expect(h.controller.floatingPanes.firstOrNull?.sessionId, 'b'); - expect(h.controller.paneCount, 1); - expect(find.byKey(const ValueKey('chat-float-title')), findsOneWidget); - // The chat moved: same State, same draft, its field has the keyboard. - expect(tester.state<_PaneState>(_pane('b')), same(b)); - expect(b.text.text, 'draft'); - expect(b.focus.hasFocus, isTrue); - - await _chord(tester, LogicalKeyboardKey.controlLeft); - expect(h.controller.floatShown, isFalse); - expect(find.byKey(const ValueKey('chat-float-title')), findsNothing); - expect(tester.state<_PaneState>(_pane('b')), same(b)); - - // Showing focuses the floating chat; hiding gives the keyboard back. - final a = tester.state<_PaneState>(_pane('a')); - a.focus.requestFocus(); - await tester.pump(); - await _chord(tester, LogicalKeyboardKey.controlLeft); - expect(h.controller.floatShown, isTrue); - expect(b.focus.hasFocus, isTrue); - await _chord(tester, LogicalKeyboardKey.controlLeft); - expect(a.focus.hasFocus, isTrue); - - // Docking returns the same chat to the tiling. - h.controller.dock(h.controller.floatingPanes.single.id); - await tester.pumpAndSettle(); - expect(h.controller.paneCount, 2); - expect(tester.state<_PaneState>(_pane('b')), same(b)); - expect(b.text.text, 'draft'); - expect(tester.takeException(), isNull); - }); - - testWidgets('in a terminal, Ctrl+Y acts only when a chat floats', ( - tester, - ) async { - final h = await pump(tester); - h.typing.requestFocus(); - await tester.pump(); - await tester.sendKeyEvent(LogicalKeyboardKey.keyY); - await _chord(tester, LogicalKeyboardKey.controlLeft); - // Nothing to float from the terminal: the shell gets Ctrl+Y (yank). - expect(h.controller.floatingPanes, isEmpty); - expect(h.typed, contains(LogicalKeyboardKey.keyY)); - expect(h.typed.where((k) => k == LogicalKeyboardKey.keyY).length, 2); - - h.controller.float(h.controller.panes.last.id); - await tester.pumpAndSettle(); - h.typing.requestFocus(); - await tester.pump(); - h.typed.clear(); - await _chord(tester, LogicalKeyboardKey.controlLeft); - expect(h.controller.floatShown, isFalse); - expect(h.typed, isNot(contains(LogicalKeyboardKey.keyY))); - await tester.sendKeyEvent(LogicalKeyboardKey.keyY); - expect(h.typed, [LogicalKeyboardKey.keyY]); - }); - - testWidgets( - 'on macOS Cmd+Y toggles and Ctrl+Y in a terminal stays with it', - (tester) async { - final h = await pump(tester); - h.controller.float(h.controller.panes.last.id); - await tester.pumpAndSettle(); - h.typing.requestFocus(); - await tester.pump(); - await _chord(tester, LogicalKeyboardKey.controlLeft); - expect(h.controller.floatShown, isTrue); - expect(h.typed, [LogicalKeyboardKey.keyY]); - await _chord(tester, LogicalKeyboardKey.metaLeft); - expect(h.controller.floatShown, isFalse); - await _chord(tester, LogicalKeyboardKey.metaLeft); - expect(h.controller.floatShown, isTrue); - }, - variant: const TargetPlatformVariant({TargetPlatform.macOS}), - ); - - testWidgets('narrow layouts never show the window or take the chord', ( - tester, - ) async { - final h = await pump(tester, narrow: true); - tester.state<_PaneState>(_pane('b')).focus.requestFocus(); - await tester.pump(); - await _chord(tester, LogicalKeyboardKey.controlLeft); - expect(h.controller.floatingPanes, isEmpty); - // A float saved on a wide window stays, unpainted, with its state. - h.controller.float(h.controller.panes.last.id); - await tester.pumpAndSettle(); - expect(find.byKey(const ValueKey('chat-float-title')), findsNothing); - expect(_pane('b'), findsOneWidget); - await _chord(tester, LogicalKeyboardKey.controlLeft); - expect(h.controller.floatShown, isTrue); - }); - - testWidgets('Alt+Y floats, hides and shows like Ctrl+Y, also from a ' - 'terminal', (tester) async { - final h = await pump(tester); - tester.state<_PaneState>(_pane('b')).focus.requestFocus(); - await tester.pump(); - await _chord(tester, LogicalKeyboardKey.altLeft); - expect(h.controller.floatingPanes.firstOrNull?.sessionId, 'b'); - expect(h.controller.floatShown, isTrue); - h.typing.requestFocus(); - await tester.pump(); - h.typed.clear(); - await _chord(tester, LogicalKeyboardKey.altLeft); - expect(h.controller.floatShown, isFalse); - expect(h.typed, isEmpty); + test('Alt+Y, Ctrl+Y and Cmd+Y on Apple platforms; a plain Y types', () { + bool chord(Set held, TargetPlatform platform) => + chatFloatShortcut(_y, _FakeKeyboard(held), platform: platform); + expect(chord({}, TargetPlatform.linux), isFalse); + expect( + chord({LogicalKeyboardKey.shiftLeft}, TargetPlatform.linux), + isFalse, + ); + expect(chord({LogicalKeyboardKey.altLeft}, TargetPlatform.linux), isTrue); + expect(chord({LogicalKeyboardKey.altLeft}, TargetPlatform.macOS), isTrue); + expect( + chord({LogicalKeyboardKey.controlLeft}, TargetPlatform.linux), + isTrue, + ); + expect(chord({LogicalKeyboardKey.metaLeft}, TargetPlatform.linux), isFalse); + expect(chord({LogicalKeyboardKey.metaLeft}, TargetPlatform.macOS), isTrue); + expect( + chord({ + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.metaLeft, + }, TargetPlatform.macOS), + isFalse, + ); + expect( + chatFloatShortcut( + const KeyUpEvent( + physicalKey: PhysicalKeyboardKey.keyY, + logicalKey: LogicalKeyboardKey.keyY, + timeStamp: Duration.zero, + ), + _FakeKeyboard({LogicalKeyboardKey.altLeft}), + ), + isFalse, + ); }); test('Option+Y matches by key position; extra modifiers do not', () { @@ -255,11 +64,6 @@ void main() { chatFloatShortcut(yen, keyboard, platform: TargetPlatform.macOS), isTrue, ); - const y = KeyDownEvent( - physicalKey: PhysicalKeyboardKey.keyY, - logicalKey: LogicalKeyboardKey.keyY, - timeStamp: Duration.zero, - ); for (final extra in [ LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.metaLeft, @@ -267,14 +71,13 @@ void main() { ]) { expect( chatFloatShortcut( - y, + _y, _FakeKeyboard({LogicalKeyboardKey.altLeft, extra}), ), isFalse, reason: '$extra', ); } - expect(chatFloatShortcut(y, _FakeKeyboard({})), isFalse); }); } diff --git a/app/test/features/chat/workspace/chat_pane_move_test.dart b/app/test/features/chat/workspace/chat_pane_move_test.dart index 4c727b48..4fdfdd8f 100644 --- a/app/test/features/chat/workspace/chat_pane_move_test.dart +++ b/app/test/features/chat/workspace/chat_pane_move_test.dart @@ -125,7 +125,9 @@ void main() { addTearDown(controller.dispose); final outer = controller.root as ChatWorkspaceSplit; controller.resize(outer.id, .3); - final ids = {for (final s in ['a', 'b', 'c', 'd']) s: _id(controller, s)}; + final ids = { + for (final s in ['a', 'b', 'c', 'd']) s: _id(controller, s), + }; final serial = controller.moveSerial; controller.swap(ids['a']!, ids['c']!); expect(controller.panes.map((p) => p.sessionId), ['c', 'b', 'a', 'd']); diff --git a/app/test/features/chat/workspace/chat_workspace_float_test.dart b/app/test/features/chat/workspace/chat_workspace_float_test.dart index 9a657953..0448216b 100644 --- a/app/test/features/chat/workspace/chat_workspace_float_test.dart +++ b/app/test/features/chat/workspace/chat_workspace_float_test.dart @@ -1,7 +1,6 @@ import 'dart:ui'; import 'package:flutter_test/flutter_test.dart'; -import 'package:pipelines_app/features/chat/workspace/chat_float_binding.dart'; import 'package:pipelines_app/features/chat/workspace/chat_float_store.dart'; import 'package:pipelines_app/features/chat/workspace/chat_workspace_controller.dart'; @@ -13,156 +12,63 @@ ChatWorkspaceController _three() => ChatWorkspaceController() List _sessions(ChatWorkspaceController c) => c.panes.map((p) => p.sessionId).toList(); -List _floating(ChatWorkspaceController c) => - c.floatingPanes.map((p) => p.sessionId).toList(); - ChatWorkspacePane _pane(ChatWorkspaceController c, String session) => c.panes.firstWhere((p) => p.sessionId == session); -class _Store implements ChatFloatStore { - _Store([this.record]); - ChatFloatRecord? record; - int writes = 0; - @override - Future read() async => record; - @override - Future write(ChatFloatRecord value) async { - writes++; - record = value; - return true; - } -} - void main() { - test('float takes a pane out of the tiling and keeps its id', () { + test('detach takes a pane out of the tiling and activates a neighbour', () { final c = _three(); final b = _pane(c, 'b'); c.activate(b.id); - c.float(b.id); - expect(c.floatingPanes.single.id, b.id); - expect(c.isFloating(b.id), isTrue); - expect(c.floatShown, isTrue); + expect(c.canFloat(b.id), isTrue); + expect(c.detach(b.id)?.sessionId, 'b'); expect(_sessions(c), ['a', 'c']); - expect(c.activePane?.sessionId, isNot('b')); - expect(c.holdsSession('b'), isTrue); + expect(c.activePane, isNotNull); + expect(c.holdsSession('b'), isFalse); }); - test('a lone pane cannot float; the tiling never empties', () { + test('a lone pane cannot leave: the tiling never empties by floating', () { final c = ChatWorkspaceController()..open('a'); - expect(c.canFloat(c.panes.single.id), isFalse); - c.float(c.panes.single.id); - expect(c.floatingPanes, isEmpty); - c.splitActive('b', ChatSplitAxis.horizontal); - final b = c.activePane!; - c.float(b.id); - // The last tiled chat stays: it cannot float too. - expect(c.canFloat(c.panes.single.id), isFalse); - // Closing the last tiled pane docks the oldest floating chat in its place. - c.close(c.panes.single.id); - expect(c.floatingPanes, isEmpty); - expect(c.panes.single.id, b.id); - expect(c.activePaneId, b.id); - }); - - test('several chats float together and show or hide together', () { - final c = _three(); - c.float(_pane(c, 'a').id); - c.setFloatShown(false); - c.float(_pane(c, 'c').id); - expect(_floating(c), ['a', 'c']); - // Floating another one shows them all. - expect(c.floatShown, isTrue); - expect(_sessions(c), ['b']); - c.toggleFloatShown(); - expect(c.floatShown, isFalse); - c.toggleFloatShown(); - expect(c.floatShown, isTrue); - // Docking one leaves the other floating. - final a = c.floatingPanes.first; - c.dock(a.id); - expect(_floating(c), ['c']); - expect(c.activePaneId, a.id); - expect(_sessions(c), ['b', 'a']); + final only = c.panes.single; + expect(c.canFloat(only.id), isFalse); + expect(c.detach(only.id), isNull); + expect(c.detach('nope'), isNull); + expect(_sessions(c), ['a']); }); test('dock puts the chat right of the active pane and activates it', () { final c = _three(); - final b = _pane(c, 'b'); - c.float(b.id); - final active = c.activePane!; - c.dock(b.id); - expect(c.floatingPanes, isEmpty); - expect(c.activePaneId, b.id); - final panes = c.panes.map((p) => p.id).toList(); - expect(panes.indexOf(b.id), panes.indexOf(active.id) + 1); - expect(_sessions(c).toSet(), {'a', 'b', 'c'}); + c.detach(_pane(c, 'b').id); + c.activate(_pane(c, 'a').id); + c.dock('b'); + expect(_sessions(c), ['a', 'b', 'c']); + expect(c.activePane?.sessionId, 'b'); + // Docking a chat the tiling already shows only activates it. + c.dock('c'); + expect(_sessions(c), ['a', 'b', 'c']); + expect(c.activePane?.sessionId, 'c'); + final empty = ChatWorkspaceController()..dock('z'); + expect(_sessions(empty), ['z']); }); - test('hide, show, reopen, close and /new follow the floating chat', () { + test('a chat out in a window is shown there instead of opened', () { final c = _three(); - final b = _pane(c, 'b'); - c.float(b.id); - c.toggleFloatShown(); - expect(c.floatShown, isFalse); - c.open('b'); - expect(c.floatShown, isTrue); - expect(_sessions(c), ['a', 'c']); - c.splitActive('b', ChatSplitAxis.vertical); - expect(c.paneCount, 2); - c.replaceSession('b', 'b2'); - expect(c.floatingPanes.single.id, b.id); - expect(c.floatingPanes.single.sessionId, 'b2'); - c.close(b.id); - expect(c.floatingPanes, isEmpty); - expect(c.paneCount, 2); - }); - - test('/new into a session another float holds closes the duplicate', () { - final c = _three(); - c.float(_pane(c, 'a').id); - c.float(_pane(c, 'b').id); - c.replaceSession('a', 'b'); - expect(_floating(c), ['b']); - }); - - test('restoreFloats skips open sessions and taken ids', () { - final c = ChatWorkspaceController() - ..open('a') - ..splitActive('b', ChatSplitAxis.horizontal); - final taken = c.panes.first.id; - expect( - c.restoreFloats([ - const ChatWorkspacePane('x', 'a'), - ChatWorkspacePane(taken, 'z'), - ], shown: true), - 0, - ); - expect(c.floatShown, isFalse); - expect( - c.restoreFloats([ - const ChatWorkspacePane('x', 'z'), - const ChatWorkspacePane('y', 'w'), - const ChatWorkspacePane('x', 'v'), - ], shown: false), - 2, - ); - expect(_floating(c), ['z', 'w']); - expect(c.floatShown, isFalse); - // A new split id never collides with a floating pane's. - c.splitActive('d', ChatSplitAxis.vertical); - expect( - c.panes.map((p) => p.id), - isNot(anyOf(contains('x'), contains('y'))), - ); - }); - - test('a restored layout drops every floating chat', () { - final c = _three(); - c.float(c.panes.first.id); - c.float(c.panes.first.id); - final snapshot = c.snapshot()!; - c.restoreLayout(snapshot); - expect(c.floatingPanes, isEmpty); + final shown = []; + c.showOutside = (id) { + if (id != 'w') return false; + shown.add(id); + return true; + }; + c.open('w'); + c.splitActive('w', ChatSplitAxis.horizontal); + expect(_sessions(c), ['a', 'b', 'c']); + expect(shown, ['w', 'w']); + c.open('d'); + expect(c.holdsSession('d'), isTrue); + // /new into a session a window holds closes the tiled duplicate. + c.replaceSession('a', 'w'); + expect(c.holdsSession('a'), isFalse); + expect(c.holdsSession('w'), isFalse); }); test('records round-trip, read version 1 and reject malformed input', () { @@ -213,63 +119,4 @@ void main() { expect(ChatFloatRecord.decode(bad), isNull, reason: bad); } }); - - test('frames are kept per pane, cascade by default and restore', () { - final frames = ChatFloatFrames(); - expect(frames.rectFor('a'), chatFloatDefaultRect); - expect( - frames.rectFor('b', index: 2), - chatFloatDefaultRect.shift(const Offset(64, 64)), - ); - frames.move('a', const Rect.fromLTWH(1, 2, 400, 300)); - expect(frames.rectFor('a', index: 3), const Rect.fromLTWH(1, 2, 400, 300)); - frames.restore({'b': const Rect.fromLTWH(9, 9, 400, 300)}); - expect(frames.rectFor('a'), chatFloatDefaultRect); - expect(frames.rectFor('b'), const Rect.fromLTWH(9, 9, 400, 300)); - }); - - test('binding restores after the layout and saves changes', () async { - final c = ChatWorkspaceController() - ..open('a') - ..splitActive('b', ChatSplitAxis.horizontal); - final store = _Store( - const ChatFloatRecord( - panes: [ChatWorkspacePane('f', 'c'), ChatWorkspacePane('g', 'd')], - shown: true, - frames: { - 'f': Rect.fromLTWH(5, 6, 400, 300), - 'g': Rect.fromLTWH(50, 60, 400, 300), - }, - ), - ); - final frames = ChatFloatFrames(); - final binding = ChatFloatBinding( - controller: c, - frames: frames, - store: store, - debounce: Duration.zero, - ); - await binding.start(); - expect(_floating(c), ['c', 'd']); - expect(c.floatShown, isTrue); - expect(frames.rectFor('f'), const Rect.fromLTWH(5, 6, 400, 300)); - expect(frames.rectFor('g'), const Rect.fromLTWH(50, 60, 400, 300)); - expect(store.writes, 0); - c.setFloatShown(false); - await Future.delayed(Duration.zero); - await binding.flush(); - expect(store.record?.shown, isFalse); - frames.move('f', const Rect.fromLTWH(70, 80, 400, 300)); - final writes = store.writes; - await binding.flush(); - expect(store.writes, writes + 1); - expect(store.record?.frames['f']?.left, 70); - // A docked chat keeps its frame for the next float; a closed one drops it. - c.dock('f'); - c.close('g'); - binding.dispose(); - await Future.delayed(Duration.zero); - expect(store.record?.panes, isEmpty); - expect(store.record?.frames.keys, ['f']); - }); } diff --git a/app/test/features/terminal/terminal_shortcuts_test.dart b/app/test/features/terminal/terminal_shortcuts_test.dart index d6fd3108..cf0ac39a 100644 --- a/app/test/features/terminal/terminal_shortcuts_test.dart +++ b/app/test/features/terminal/terminal_shortcuts_test.dart @@ -234,18 +234,19 @@ void main() { web: false, platform: TargetPlatform.macOS, ); - expect(mac.toggle, ['Cmd+T', 'Ctrl+T', 'Option+T', 'Ctrl+`']); + expect(mac.toggle, ['Option+T', 'Cmd+T', 'Ctrl+T', 'Ctrl+`']); expect(mac.tabs, ['Ctrl+Tab', 'Ctrl+Shift+Tab']); const linux = TerminalShortcutLabels( web: false, platform: TargetPlatform.linux, ); - expect(linux.toggle, ['Ctrl+T', 'Alt+T', 'Ctrl+`']); + expect(linux.toggle, ['Alt+T', 'Ctrl+T', 'Ctrl+`']); const macWeb = TerminalShortcutLabels( web: true, platform: TargetPlatform.macOS, ); - expect(macWeb.toggle, ['Ctrl+T', 'Option+T', 'Ctrl+`']); + expect(macWeb.toggle, ['Option+T', 'Ctrl+T', 'Ctrl+`']); + expect(macWeb.button, 'Terminal (Option+T)'); expect(macWeb.tabs, isEmpty); expect(macWeb.summary, isNot(contains('Tab'))); const windowsWeb = TerminalShortcutLabels( diff --git a/app/test/shell/windows/window_host_test.dart b/app/test/shell/windows/window_host_test.dart index 5be9cc6e..dec28079 100644 --- a/app/test/shell/windows/window_host_test.dart +++ b/app/test/shell/windows/window_host_test.dart @@ -33,10 +33,7 @@ void main() { // semantics (a page route's barrier hides what is behind it). final handle = tester.ensureSemantics(); expect(find.bySemanticsLabel('Window: Probe a'), findsOneWidget); - expect( - tester.getSemantics(find.byTooltip('Minimise')).tooltip, - 'Minimise', - ); + expect(tester.getSemantics(find.byTooltip('Minimise')).tooltip, 'Minimise'); expect(find.bySemanticsLabel('sheet'), findsOneWidget); expect(find.bySemanticsLabel('Chat'), findsOneWidget); expect( diff --git a/app/test/shell/windows/window_popup_rules_test.dart b/app/test/shell/windows/window_popup_rules_test.dart new file mode 100644 index 00000000..5178a005 --- /dev/null +++ b/app/test/shell/windows/window_popup_rules_test.dart @@ -0,0 +1,27 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +/// Window content takes input only inside its window (see `WindowNavigator`), +/// so a `MenuAnchor` panel, which may extend past the window, must be in the +/// root overlay. Any content can end up in a window, so every `MenuAnchor` in +/// the app opts in. +void main() { + test('every MenuAnchor targets the root overlay', () { + final offenders = []; + for (final file in Directory('lib').listSync(recursive: true)) { + if (file is! File || !file.path.endsWith('.dart')) continue; + final source = file.readAsStringSync(); + for (final match in RegExp(r'\bMenuAnchor\(').allMatches(source)) { + final end = (match.end + 400).clamp(0, source.length); + if (!source + .substring(match.end, end) + .contains('useRootOverlay: true')) { + final line = '\n'.allMatches(source.substring(0, match.start)).length; + offenders.add('${file.path}:${line + 1}'); + } + } + } + expect(offenders, isEmpty); + }); +}