From 558eedb4100d7898e7852a8eb225ebab41953657 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 10 Nov 2026 21:00:21 +0000 Subject: [PATCH 1/5] Extract ChatRuntime from the Chat screen Phase 2.1 of docs/plans/floating-windows.md. The session list controller, opened rows, accepted models, transcript positions and caches, composer focus requests and list folds move from ChatScreen's state to ChatRuntime. ChatScreen builds its own unless one is passed; behaviour is unchanged. --- app/lib/features/chat/chat_runtime.dart | 191 ++++++++++++++++++ app/lib/features/chat/screen.dart | 158 +++++---------- app/test/features/chat/chat_runtime_test.dart | 85 ++++++++ 3 files changed, 326 insertions(+), 108 deletions(-) create mode 100644 app/lib/features/chat/chat_runtime.dart create mode 100644 app/test/features/chat/chat_runtime_test.dart diff --git a/app/lib/features/chat/chat_runtime.dart b/app/lib/features/chat/chat_runtime.dart new file mode 100644 index 00000000..7f43fb30 --- /dev/null +++ b/app/lib/features/chat/chat_runtime.dart @@ -0,0 +1,191 @@ +import 'package:flutter/foundation.dart'; + +import '../../core/api_gateway.dart'; +import '../../core/servers/chat/chat_identity.dart'; +import '../../core/servers/chat/federated_chat_gateway.dart'; +import 'conversation/chat_efforts.dart'; +import 'conversation/chat_models.dart'; +import 'conversation/chat_row_widgets.dart'; +import 'conversation/chat_scroll.dart'; +import 'conversation/chat_transcript_cache.dart'; +import 'conversation/composer_focus_request.dart'; +import 'data/chat_repository.dart'; +import 'ui/sessions/chat_sessions_body.dart'; +import 'ui/sessions/chat_sessions_controller.dart'; + +/// What open chats share for one server, wherever they are shown (the Chat +/// destination's tiling or a floating window): the session list, the rows +/// opened so far, model switches the server accepted, transcript positions +/// and caches, and composer focus requests. +/// +/// It notifies when a row a conversation is drawn from changes. +class ChatRuntime extends ChangeNotifier { + ChatRuntime({required ApiGateway gateway}) + : _gateway = gateway, + sessions = ChatSessionsController(ChatRepository(gateway)); + + ApiGateway _gateway; + + /// The gateway chats are read through. Transcripts read through another + /// gateway belong to that server, so replacing it drops them. + ApiGateway get gateway => _gateway; + set gateway(ApiGateway value) { + if (identical(_gateway, value)) return; + _gateway = value; + transcripts.clear(); + } + + /// The gateway for one chat: its own server's on a federated gateway. + ApiGateway gatewayFor(String sessionId) { + final gateway = _gateway; + return gateway is FederatedChatGateway + ? gateway.forChat(sessionId) + : gateway; + } + + /// The id of the server [sessionId] lives on, or empty. + String serverIdFor(String sessionId) => + '${rowFor(sessionId)?['_server_id'] ?? parseFederatedChatId(sessionId)?.server ?? ''}'; + + /// The list's controller, shared with the mounted list screen. The list + /// screen refreshes it on mount and swaps its repository when the socket + /// is replaced. + final ChatSessionsController sessions; + + /// The list's folded sections, so Next chat counts the rows the list + /// draws. + final ChatSectionFolds folds = ChatSectionFolds(); + + /// Rows opened so far, used for the title and the recorded model facts. + /// The mounted list also reports its loaded rows, so a routed id (a deep + /// link) resolves the same row without a second list request. + final Map opened = {}; + + /// Each row as the list last reported it (without its live `running`), so + /// [adoptRows] adopts only what a re-read changed. + final Map _listed = {}; + + /// Model switches the server accepted after a row was opened. The row that + /// opened the conversation may still carry the pre-switch model, so these + /// win, including when the same chat is reopened. + final Map _acceptedModels = {}; + + /// Transcript positions, so Back and a reopened chat return to the same + /// place. + final ChatScrollStore scrollPositions = MemoryChatScrollStore(); + + /// Transcripts of recently left chats, so a reopened chat shows its last + /// transcript at once while it re-subscribes and re-reads. Bounded and in + /// memory only; see [ChatTranscriptCache]. + final ChatTranscriptCache transcripts = ChatTranscriptCache(); + + /// Puts the keyboard in an opened chat's composer once it is built. + final ChatComposerFocusRequests composerFocus = ChatComposerFocusRequests(); + + /// The line a just-created conversation opens on, tied to the selection + /// `/new` made. Leaving that conversation drops it, so a later reopen is + /// an ordinary visit. + ({String id, String notice})? startNotice; + + /// The row to open for [id], with an accepted model folded in. + JsonMap? rowFor(String id) { + final row = opened[id] ?? _listed[id]; + final accepted = _acceptedModels[id]; + if (row == null || accepted == null) return row; + return { + ...row, + 'model': accepted.model, + 'model_provider': accepted.provider, + 'model_selection': accepted.selection, + }; + } + + /// [id]'s title as shown on a pane or window, else the id. + String titleFor(String id) => '${rowFor(id)?['title'] ?? id}'; + + void modelChanged(String id, ChatModelSelection applied) { + _acceptedModels[id] = applied; + notifyListeners(); + } + + /// An accepted mode switch updates the opened row, so reopening the chat + /// shows it before the list re-reads. Returns false when [id] has no + /// opened row. + bool modeChanged(String id, String mode, String name) { + final row = opened[id]; + if (row == null) return false; + opened[id] = {...row, 'mode': mode, 'mode_name': name}; + notifyListeners(); + return true; + } + + /// An accepted thinking level updates the opened row like a mode switch. + bool effortChanged(String id, ChatEffortState state) { + final row = opened[id]; + if (row == null) return false; + opened[id] = state.applyTo(row); + notifyListeners(); + return true; + } + + /// `/rename` was accepted for [id]: the opened row follows the title. + void renamed(String id, String title) { + final row = opened[id]; + if (row == null) return; + opened[id] = {...row, 'title': title}; + notifyListeners(); + } + + /// The chat [previousId] moved to the new session [session] (`/new`): it + /// opens under its new id on the server's row, which carries every shared + /// field (an omitted one is unset, so the old row is not merged in), on + /// [notice]. A model switch accepted for the old id moves with the chat. + void movedToSession(String previousId, JsonMap session, String notice) { + final id = '${session['id'] ?? ''}'; + final accepted = _acceptedModels[previousId]; + if (accepted != null) _acceptedModels[id] = accepted; + startNotice = (id: id, notice: notice); + opened[id] = {...session}..remove('running'); + } + + /// Adopts the list's loaded [rows] for [selected], for every chat in + /// [retained] and for every opened row. Only a listed row that changed + /// since the list last reported it is adopted, so an unchanged (or still + /// loading) listing never reverts a mode or model just accepted. Fields + /// only the opened row carries (a create's instruction status) are kept. + /// The list's live `running` flag is ignored: the conversation tracks its + /// own turn, and following it would rebuild the open thread at every turn. + void adoptRows( + List rows, { + required String? selected, + required Set retained, + }) { + final next = {}; + for (final row in rows) { + final id = '${row['id'] ?? ''}'; + if (id.isEmpty) continue; + final listed = {...row}..remove('running'); + final previous = _listed[id]; + _listed[id] = listed; + final was = opened[id]; + if (was == null && id != selected && !retained.contains(id)) continue; + if (was != null && chatJsonEquals(previous, listed)) continue; + final adopted = {...?was, ...listed}; + if (was != null && was.containsKey('running')) { + adopted['running'] = was['running']; + } + if (!chatJsonEquals(was, adopted)) next[id] = adopted; + } + if (next.isEmpty) return; + opened.addAll(next); + notifyListeners(); + } + + @override + void dispose() { + sessions.dispose(); + folds.dispose(); + composerFocus.dispose(); + super.dispose(); + } +} diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index ce5f131b..cc6d16aa 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -1,5 +1,5 @@ +import 'chat_runtime.dart'; import 'workspace/federated_workspace_store.dart'; -import '../../core/servers/chat/chat_identity.dart'; import '../../core/servers/chat/federated_chat_gateway.dart'; import '../../core/servers/server_context.dart'; import '../../shell/destination.dart'; @@ -40,13 +40,9 @@ import 'workspace/chat_center_stage_keys.dart'; import 'workspace/chat_pane_move_actions.dart'; import 'workspace/chat_workspace_entrance.dart'; import 'ui/sessions/chat_adaptive.dart'; -import 'conversation/chat_row_widgets.dart'; -import 'conversation/chat_scroll.dart'; import 'conversation/chat_thread_view.dart'; -import 'conversation/chat_transcript_cache.dart'; import 'conversation/composer_focus_request.dart'; import 'conversation/composer_selection_focus.dart'; -import 'data/chat_repository.dart'; import 'domain/chat_commands.dart'; import 'domain/chat_cycle.dart'; import '../terminal/terminal_scope.dart'; @@ -80,11 +76,16 @@ class ChatScreen extends StatefulWidget { this.onWorkspaceEmpty, this.onAvailableSessionsChanged, this.persistWorkspace = false, + this.runtime, }); final ApiGateway gateway; final bool persistWorkspace; + /// The chats' shared state, kept by the app beyond this screen; the screen + /// keeps its own for the visit when null. + final ChatRuntime? runtime; + /// The chat session the current route names, or null for the list. final String? initialSessionId; @@ -103,53 +104,23 @@ class ChatScreen extends StatefulWidget { class _ChatScreenState extends State with _ChatScreenWorkspace, _ChatScreenKeys, _ChatScreenFloat { - /// The list's controller, shared with the mounted list screen. The list - /// screen refreshes it on mount and swaps its repository when the socket is - /// replaced; this destination lists created rows and re-reads after a - /// conversation's command changes a session. - late final ChatSessionsController _sessions = ChatSessionsController( - ChatRepository(widget.gateway), - )..onSessionReplaced = _replacedElsewhere; + /// The chats' shared state: the list, opened rows, accepted models, + /// transcript positions and caches (see [ChatRuntime]). + late final ChatRuntime _runtime = + widget.runtime ?? ChatRuntime(gateway: widget.gateway); - /// Rows this visit has opened, used for the native title and the recorded - /// model facts. The mounted list also reports its loaded rows, so a routed id - /// (a deep link) resolves the same row without a second list request. + ChatSessionsController get _sessions => _runtime.sessions; @override - final Map _openedSessions = {}; - - /// Each row as the list last reported it (without its live `running`), so - /// [_adoptRows] adopts only what a re-read changed. - final Map _listedRows = {}; - - /// Model switches the server accepted after a row was opened. The row that - /// opened the conversation may still carry the pre-switch model, so these win - /// for the rest of this visit, including when the same chat is reopened. - final Map _acceptedModels = {}; - - /// Transcript positions for this visit. It lives with the destination, not a - /// conversation view, so Back and a reopened chat return to the same place. - final ChatScrollStore _scrollPositions = MemoryChatScrollStore(); - - /// Transcripts of recently left chats for this visit, so a reopened chat - /// shows its last transcript at once while it re-subscribes and re-reads. - /// Bounded and in memory only; see [ChatTranscriptCache]. - final ChatTranscriptCache _transcripts = ChatTranscriptCache(); - - /// The line a just-created conversation opens on, tied to the selection - /// `/new` made. Leaving that conversation drops it, so a later reopen is an - /// ordinary visit. - ({String id, String notice})? _startNotice; + Map get _openedSessions => _runtime.opened; String? _standaloneSelection; /// Ctrl+1…Ctrl+9 put the keyboard in the opened chat's composer; choosing a /// chat does too where [chatSelectionFocusesComposer] allows. @override - final ChatComposerFocusRequests _composerFocus = ChatComposerFocusRequests(); + ChatComposerFocusRequests get _composerFocus => _runtime.composerFocus; - /// The list's folded sections, kept here so Next chat counts the rows the - /// list draws. - final ChatSectionFolds _folds = ChatSectionFolds(); + ChatSectionFolds get _folds => _runtime.folds; /// Whether the last build offered Next chat, so a list change rebuilds only /// when that changes. @@ -165,6 +136,10 @@ class _ChatScreenState extends State @override void initState() { super.initState(); + _runtime + ..gateway = widget.gateway + ..addListener(_runtimeChanged); + _sessions.onSessionReplaced = _replacedElsewhere; final initial = widget.initialSessionId; if (initial != null && initial.isNotEmpty) { _workspace.open(initial); @@ -184,6 +159,11 @@ class _ChatScreenState extends State _folds.addListener(_nextChanged); } + /// A row an open conversation is drawn from changed. + void _runtimeChanged() { + if (mounted) setState(() {}); + } + /// The chat after [id] as the list draws it (Starred, then Chats by /// directory, then Closed, skipping folded sections), wrapping around. The /// embedded list has no search field, so no query narrows it. @@ -255,7 +235,7 @@ class _ChatScreenState extends State _openedSessions[id] = session; _workspaceVisible = true; _workspace.open(id); - if (_startNotice?.id != id) _startNotice = null; + if (_runtime.startNotice?.id != id) _runtime.startNotice = null; final select = widget.onSessionSelected; if (select != null) { if (_publishedWorkspaceSession != id) { @@ -289,23 +269,16 @@ class _ChatScreenState extends State /// shared field (an omitted one is unset, so the old row is not merged in). /// A model switch accepted here in this visit moved with the chat. void _followNewSession(String previousId, JsonMap session, String notice) { - final id = '${session['id'] ?? ''}'; - final accepted = _acceptedModels[previousId]; - if (accepted != null) _acceptedModels[id] = accepted; - _startNotice = (id: id, notice: notice); - _openedSessions[id] = {...session}..remove('running'); + _runtime.movedToSession(previousId, session, notice); _forgetRecentSession(previousId); - _workspace.replaceSession(previousId, id); + _workspace.replaceSession(previousId, '${session['id'] ?? ''}'); if (_workspace.paneCount == 0) _open(session); } /// `/rename` was accepted for [id]: the opened row follows the shared title /// and the list re-reads it. void _renamed(String id, String title) { - final row = _openedSessions[id]; - if (row != null) { - setState(() => _openedSessions[id] = {...row, 'title': title}); - } + _runtime.renamed(id, title); unawaited(_sessions.refresh()); } @@ -348,31 +321,15 @@ class _ChatScreenState extends State if (row['closed_at'] == null && row['closed'] != true) '${row['id'] ?? ''}', }); - final selected = _selected; - final retained = _workspace.panes.map((pane) => pane.sessionId).toSet(); - final next = {}; - for (final row in rows) { - final id = '${row['id'] ?? ''}'; - if (id.isEmpty) continue; - final listed = {...row}..remove('running'); - final previous = _listedRows[id]; - _listedRows[id] = listed; - final opened = _openedSessions[id]; - if (opened == null && id != selected && !retained.contains(id)) continue; - if (opened != null && chatJsonEquals(previous, listed)) continue; - final adopted = {...?opened, ...listed}; - if (opened != null && opened.containsKey('running')) { - adopted['running'] = opened['running']; - } - if (!chatJsonEquals(opened, adopted)) next[id] = adopted; - } - if (next.isEmpty) return; - setState(() => _openedSessions.addAll(next)); + _runtime.adoptRows( + rows, + selected: _selected, + retained: _workspace.panes.map((pane) => pane.sessionId).toSet(), + ); } void _modelChanged(String id, ChatModelSelection applied) { - if (!mounted) return; - setState(() => _acceptedModels[id] = applied); + if (mounted) _runtime.modelChanged(id, applied); } /// An accepted mode switch updates the opened row, so reopening the chat in @@ -380,41 +337,24 @@ class _ChatScreenState extends State /// a listing already in flight from before the switch is superseded rather /// than adopted over the accepted mode. void _modeChanged(String id, String mode, String name) { - final row = _openedSessions[id]; - if (!mounted || row == null) return; - setState( - () => _openedSessions[id] = {...row, 'mode': mode, 'mode_name': name}, - ); + if (!mounted || !_runtime.modeChanged(id, mode, name)) return; unawaited(_sessions.refresh()); } /// An accepted thinking level updates the opened row like a mode switch. void _effortChanged(String id, ChatEffortState state) { - final row = _openedSessions[id]; - if (!mounted || row == null) return; - setState(() => _openedSessions[id] = state.applyTo(row)); + if (!mounted || !_runtime.effortChanged(id, state)) return; unawaited(_sessions.refresh()); } - /// The row to open for [id], with an accepted model folded in. @override - JsonMap? _rowFor(String id) { - final row = _openedSessions[id] ?? _listedRows[id]; - final accepted = _acceptedModels[id]; - if (row == null || accepted == null) return row; - return { - ...row, - 'model': accepted.model, - 'model_provider': accepted.provider, - 'model_selection': accepted.selection, - }; - } + JsonMap? _rowFor(String id) => _runtime.rowFor(id); @override void _back() { _workspaceVisible = false; _publishedWorkspaceSession = null; - _startNotice = null; + _runtime.startNotice = null; _composerFocus.cancel(); if (_workspace.paneCount == 0) widget.onWorkspaceEmpty?.call(); final back = widget.onBack; @@ -454,7 +394,7 @@ class _ChatScreenState extends State } } // Transcripts read through another gateway belong to that server. - if (oldWidget.gateway != widget.gateway) _transcripts.clear(); + _runtime.gateway = widget.gateway; } @override @@ -468,9 +408,13 @@ class _ChatScreenState extends State _workspace.dispose(); _sessions.removeListener(_nextChanged); _sessions.removeListener(_availableSessionsChanged); - _sessions.dispose(); - _folds.dispose(); - _composerFocus.dispose(); + _folds.removeListener(_nextChanged); + _runtime.removeListener(_runtimeChanged); + if (widget.runtime == null) { + _runtime.dispose(); + } else { + _sessions.onSessionReplaced = null; + } super.dispose(); } @@ -482,18 +426,16 @@ class _ChatScreenState extends State BuildContext? paneContext, }) { final row = _rowFor(selected); - final start = _startNotice; + final start = _runtime.startNotice; final thread = ChatThreadView( key: ValueKey('chat-session-$selected'), - gateway: widget.gateway is FederatedChatGateway - ? (widget.gateway as FederatedChatGateway).forChat(selected) - : widget.gateway, + gateway: _runtime.gatewayFor(selected), sessionId: selected, title: '${row?['title'] ?? ''}'.trim(), session: row, syncToken: widget.syncToken, - scrollPositions: _scrollPositions, - transcripts: _transcripts, + scrollPositions: _runtime.scrollPositions, + transcripts: _runtime.transcripts, initialNotice: start != null && start.id == selected ? start.notice : null, @@ -557,7 +499,7 @@ class _ChatScreenState extends State requests: _composerFocus, child: ServerContext.forServer( context, - '${row?['_server_id'] ?? parseFederatedChatId(selected)?.server ?? ''}', + _runtime.serverIdFor(selected), thread, ), ); diff --git a/app/test/features/chat/chat_runtime_test.dart b/app/test/features/chat/chat_runtime_test.dart new file mode 100644 index 00000000..4308bae6 --- /dev/null +++ b/app/test/features/chat/chat_runtime_test.dart @@ -0,0 +1,85 @@ +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/conversation/chat_models.dart'; + +class _Gateway implements ApiGateway { + @override + Stream get frames => const Stream.empty(); + @override + Future call(String type, [JsonMap fields = const {}]) async => {}; +} + +void main() { + late ChatRuntime runtime; + late int notified; + setUp(() { + runtime = ChatRuntime(gateway: _Gateway()); + notified = 0; + runtime.addListener(() => notified++); + }); + tearDown(() => runtime.dispose()); + + test('adopts listed rows for opened, selected and retained chats only', () { + runtime.opened['a'] = {'id': 'a', 'title': 'Old', 'running': true}; + runtime.adoptRows( + [ + {'id': 'a', 'title': 'New', 'running': false}, + {'id': 'b', 'title': 'B'}, + {'id': 'c', 'title': 'C'}, + {'id': 'd', 'title': 'D'}, + ], + selected: 'b', + retained: {'c'}, + ); + // The conversation keeps its own running flag. + expect(runtime.opened['a'], {'id': 'a', 'title': 'New', 'running': true}); + expect(runtime.opened.keys, ['a', 'b', 'c']); + expect(notified, 1); + // A chat that is only listed still resolves its row. + expect(runtime.rowFor('d')?['title'], 'D'); + expect(runtime.titleFor('zz'), 'zz'); + }); + + test('an unchanged listing never reverts an accepted mode', () { + final rows = [ + {'id': 'a', 'mode': 'ask'}, + ]; + runtime.adoptRows(rows, selected: 'a', retained: const {}); + expect(runtime.modeChanged('a', 'auto', 'Auto'), isTrue); + runtime.adoptRows(rows, selected: 'a', retained: const {}); + expect(runtime.opened['a']?['mode'], 'auto'); + expect(notified, 2); + expect(runtime.modeChanged('missing', 'auto', 'Auto'), isFalse); + }); + + test('an accepted model wins over the row and follows /new', () { + runtime.opened['a'] = {'id': 'a', 'model': 'old'}; + runtime.modelChanged('a', ( + provider: 'p', + model: 'new', + selection: 'p/new', + )); + expect(runtime.rowFor('a')?['model'], 'new'); + runtime.movedToSession('a', {'id': 'b', 'running': true}, 'Started'); + expect(runtime.rowFor('b'), { + 'id': 'b', + 'model': 'new', + 'model_provider': 'p', + 'model_selection': 'p/new', + }); + expect(runtime.startNotice, (id: 'b', notice: 'Started')); + }); + + test('rename updates the opened row; a new gateway drops transcripts', () { + runtime.opened['a'] = {'id': 'a', 'title': 'Old'}; + runtime.renamed('a', 'New'); + expect(runtime.titleFor('a'), 'New'); + expect(notified, 1); + final other = _Gateway(); + runtime.gateway = other; + expect(runtime.gateway, same(other)); + expect(runtime.gatewayFor('a'), same(other)); + expect(runtime.serverIdFor('a'), ''); + }); +} From 9695100faac1eec12c2d1d8d3124fd9ef375dd2d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 10 Nov 2026 21:05:41 +0000 Subject: [PATCH 2/5] Build chat panes through one content builder Phase 2.2 of docs/plans/floating-windows.md: buildChatPaneContent wraps a conversation in the scopes it needs and keys it by the runtime, so the tiling and (next) a floating window build the same subtree. The tiling uses it; behaviour is unchanged. --- app/lib/features/chat/chat_pane_content.dart | 111 ++++++++++++ app/lib/features/chat/chat_runtime.dart | 61 ++++++- .../features/chat/chat_screen_workspace.dart | 18 +- .../conversation/chat_background_tasks.dart | 2 +- app/lib/features/chat/screen.dart | 164 ++++++------------ .../workspace/chat_workspace_geometry.dart | 6 +- app/test/features/chat/chat_runtime_test.dart | 1 - 7 files changed, 227 insertions(+), 136 deletions(-) create mode 100644 app/lib/features/chat/chat_pane_content.dart diff --git a/app/lib/features/chat/chat_pane_content.dart b/app/lib/features/chat/chat_pane_content.dart new file mode 100644 index 00000000..d06369cc --- /dev/null +++ b/app/lib/features/chat/chat_pane_content.dart @@ -0,0 +1,111 @@ +import 'package:flutter/widgets.dart'; + +import '../../core/api_gateway.dart'; +import '../../core/servers/server_context.dart'; +import '../../shell/destination.dart'; +import '../../shell/detail_page.dart'; +import 'chat_runtime.dart'; +import 'conversation/chat_thread_view.dart'; +import 'conversation/composer_focus_request.dart'; + +/// Where an open chat is shown and what that place alone decides: its Back, +/// its pane menu, whether it takes pastes, and what follows `/new` and +/// `/close`. Everything else about the chat comes from its [ChatRuntime]. +class ChatPanePlacement { + const ChatPanePlacement({ + required this.onBack, + required this.onNewSession, + required this.onSessionClosed, + this.syncToken = 0, + this.useNativeBack = false, + this.showBackButton, + this.pasteTarget = false, + this.ownsPasteWhenFocused = false, + this.paneControls, + this.onNextChat, + }); + + final VoidCallback onBack; + + /// `/new` moved the chat to a fresh session (previous id, the new row and + /// the line the new conversation opens on). + final void Function(String previousId, JsonMap session, String notice) + onNewSession; + + /// `/close` was accepted. + final VoidCallback onSessionClosed; + + /// Advances when the socket is replaced; the conversation re-subscribes. + final int syncToken; + final bool useNativeBack; + final bool? showBackButton; + + /// Whether a paste with no field focused goes to this chat. + final bool pasteTarget; + + /// Whether this chat takes a paste while it has the keyboard, though it is + /// not the active pane (a chat in a window). + final bool ownsPasteWhenFocused; + + /// The pane menu's choices, built in the pane's own context. + final List Function(BuildContext paneContext)? paneControls; + final VoidCallback? onNextChat; +} + +/// One open chat with the scopes its conversation needs, the same in the +/// Chat destination's tiling and in a floating window. It is keyed by the +/// runtime ([ChatRuntime.viewKey]), so a chat that moves between the two in +/// one frame keeps its live view: transcript, scroll, draft and running turn. +Widget buildChatPaneContent({ + required ChatRuntime runtime, + required String sessionId, + required ChatPanePlacement placement, +}) => KeyedSubtree( + key: runtime.viewKey(sessionId), + child: DetailPane( + destination: AppDestination.chat, + implyBack: false, + builder: (context) { + final row = runtime.rowFor(sessionId); + final start = runtime.startNotice; + return ChatComposerFocusScope( + sessionId: sessionId, + requests: runtime.composerFocus, + child: ServerContext.forServer( + context, + runtime.serverIdFor(sessionId), + ChatThreadView( + key: ValueKey('chat-session-$sessionId'), + gateway: runtime.gatewayFor(sessionId), + sessionId: sessionId, + title: '${row?['title'] ?? ''}'.trim(), + session: row, + syncToken: placement.syncToken, + scrollPositions: runtime.scrollPositions, + transcripts: runtime.transcripts, + initialNotice: start != null && start.id == sessionId + ? start.notice + : null, + onBack: placement.onBack, + onModelChanged: (applied) => + runtime.modelChanged(sessionId, applied), + onModeChanged: (mode, name) => + runtime.acceptMode(sessionId, mode, name), + onEffortChanged: (state) => runtime.acceptEffort(sessionId, state), + onNewSession: placement.onNewSession, + onSessionRenamed: (title) => runtime.acceptRename(sessionId, title), + onSessionClosed: placement.onSessionClosed, + onColorSelected: (color) => + runtime.sessions.setColor(sessionId, color), + onNextChat: placement.onNextChat, + useNativeBack: placement.useNativeBack, + pasteTarget: placement.pasteTarget, + ownsPasteWhenFocused: placement.ownsPasteWhenFocused, + showBackButton: placement.showBackButton, + paneControls: placement.paneControls?.call(context) ?? const [], + ), + ), + ); + }, + ), +); diff --git a/app/lib/features/chat/chat_runtime.dart b/app/lib/features/chat/chat_runtime.dart index 7f43fb30..3c71cdc5 100644 --- a/app/lib/features/chat/chat_runtime.dart +++ b/app/lib/features/chat/chat_runtime.dart @@ -1,4 +1,6 @@ -import 'package:flutter/foundation.dart'; +import 'dart:async'; + +import 'package:flutter/widgets.dart'; import '../../core/api_gateway.dart'; import '../../core/servers/chat/chat_identity.dart'; @@ -20,9 +22,42 @@ import 'ui/sessions/chat_sessions_controller.dart'; /// /// It notifies when a row a conversation is drawn from changes. class ChatRuntime extends ChangeNotifier { - ChatRuntime({required ApiGateway gateway}) + ChatRuntime({required ApiGateway gateway, this.serverKey = ''}) : _gateway = gateway, - sessions = ChatSessionsController(ChatRepository(gateway)); + sessions = ChatSessionsController(ChatRepository(gateway)) { + sessions.onSessionReplaced = (previousId, session) { + for (final listener in _replaced.toList()) { + listener(previousId, session); + } + }; + } + + /// The server (or set of servers) these chats belong to; windows carry it. + final String serverKey; + + /// Advances when the socket is replaced, for chats shown outside the Chat + /// destination. + final ValueNotifier syncToken = ValueNotifier(0); + + final List _replaced = []; + + /// Calls [listener] when another device moved a chat to a new session. + void addSessionReplacedListener( + void Function(String previousId, JsonMap session) listener, + ) => _replaced.add(listener); + + void removeSessionReplacedListener( + void Function(String previousId, JsonMap session) listener, + ) => _replaced.remove(listener); + + final Map _viewKeys = {}; + + /// The key of [sessionId]'s live view, so it can move between the tiling + /// and a window without being rebuilt. + GlobalKey viewKey(String sessionId) => _viewKeys.putIfAbsent( + sessionId, + () => GlobalKey(debugLabel: 'chat view $sessionId'), + ); ApiGateway _gateway; @@ -128,6 +163,24 @@ class ChatRuntime extends ChangeNotifier { return true; } + /// An accepted mode switch also re-reads the list, so a listing already + /// in flight from before the switch is superseded rather than adopted over + /// the accepted mode. + void acceptMode(String id, String mode, String name) { + if (modeChanged(id, mode, name)) unawaited(sessions.refresh()); + } + + void acceptEffort(String id, ChatEffortState state) { + if (effortChanged(id, state)) unawaited(sessions.refresh()); + } + + /// `/rename` was accepted: the opened row follows the shared title and the + /// list re-reads it. + void acceptRename(String id, String title) { + renamed(id, title); + unawaited(sessions.refresh()); + } + /// `/rename` was accepted for [id]: the opened row follows the title. void renamed(String id, String title) { final row = opened[id]; @@ -183,6 +236,8 @@ class ChatRuntime extends ChangeNotifier { @override void dispose() { + _replaced.clear(); + syncToken.dispose(); sessions.dispose(); folds.dispose(); composerFocus.dispose(); diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 8c352f74..ebf4f4bb 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -14,12 +14,7 @@ mixin _ChatScreenWorkspace on State { ChatFloatFrames get _floatFrames; void _bindFloat(ChatFloatStore store, Future restored); void _unbindFloat(); - Widget _thread( - String selected, - VoidCallback onBack, { - ChatWorkspacePane? pane, - BuildContext? paneContext, - }); + Widget _thread(ChatWorkspacePane pane); ChatSidebarMode _sidebarMode = ChatSidebarMode.expanded; void _setSidebarMode(ChatSidebarMode mode) { @@ -390,16 +385,9 @@ mixin _ChatScreenWorkspace on State { // active pane the others fade theirs. child: ChatPaneActivity( inactive: _workspace.paneCount > 1 && !active, - child: DetailPane( + child: KeyedSubtree( key: ValueKey('chat-pane-detail-${pane.id}'), - destination: AppDestination.chat, - implyBack: false, - builder: (context) => _thread( - pane.sessionId, - _back, - pane: pane, - paneContext: context, - ), + child: _thread(pane), ), ), ), diff --git a/app/lib/features/chat/conversation/chat_background_tasks.dart b/app/lib/features/chat/conversation/chat_background_tasks.dart index 8097d308..8bc8f18f 100644 --- a/app/lib/features/chat/conversation/chat_background_tasks.dart +++ b/app/lib/features/chat/conversation/chat_background_tasks.dart @@ -202,7 +202,7 @@ class _ChatBackgroundTasksState extends State { // Level with the field's single line, beside Send. padding: const EdgeInsetsDirectional.only(end: 4, bottom: 4), child: Semantics( - identifier: 'chat-background-tasks-button', + identifier: 'chat-background-tasks-button', button: true, excludeSemantics: true, onTap: _open, diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index cc6d16aa..8a94c568 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -1,7 +1,7 @@ +import 'chat_pane_content.dart'; import 'chat_runtime.dart'; import 'workspace/federated_workspace_store.dart'; import '../../core/servers/chat/federated_chat_gateway.dart'; -import '../../core/servers/server_context.dart'; import '../../shell/destination.dart'; import '../../shell/shell_bar.dart'; import '../../shell/shell_destination_menu.dart'; @@ -27,8 +27,6 @@ import 'workspace/chat_workspace_binding.dart'; import 'workspace/chat_workspace_snapshot.dart'; import 'workspace/chat_workspace_store.dart'; import 'conversation/chat_bar_tint.dart'; -import 'conversation/chat_efforts.dart'; -import 'conversation/chat_models.dart'; import 'conversation/chat_pane_picker.dart'; import 'conversation/chat_add_pane_picker.dart'; import 'conversation/chat_sidebar_controls.dart'; @@ -40,7 +38,6 @@ import 'workspace/chat_center_stage_keys.dart'; import 'workspace/chat_pane_move_actions.dart'; import 'workspace/chat_workspace_entrance.dart'; import 'ui/sessions/chat_adaptive.dart'; -import 'conversation/chat_thread_view.dart'; import 'conversation/composer_focus_request.dart'; import 'conversation/composer_selection_focus.dart'; import 'domain/chat_commands.dart'; @@ -139,7 +136,7 @@ class _ChatScreenState extends State _runtime ..gateway = widget.gateway ..addListener(_runtimeChanged); - _sessions.onSessionReplaced = _replacedElsewhere; + _runtime.addSessionReplacedListener(_replacedElsewhere); final initial = widget.initialSessionId; if (initial != null && initial.isNotEmpty) { _workspace.open(initial); @@ -275,13 +272,6 @@ class _ChatScreenState extends State if (_workspace.paneCount == 0) _open(session); } - /// `/rename` was accepted for [id]: the opened row follows the shared title - /// and the list re-reads it. - void _renamed(String id, String title) { - _runtime.renamed(id, title); - unawaited(_sessions.refresh()); - } - /// `/close` was accepted: the conversation leaves, back to the list, which /// re-reads the closed row. void _closed(String sessionId) { @@ -328,25 +318,6 @@ class _ChatScreenState extends State ); } - void _modelChanged(String id, ChatModelSelection applied) { - if (mounted) _runtime.modelChanged(id, applied); - } - - /// An accepted mode switch updates the opened row, so reopening the chat in - /// this visit shows it before the list re-reads. The list then re-reads, so - /// a listing already in flight from before the switch is superseded rather - /// than adopted over the accepted mode. - void _modeChanged(String id, String mode, String name) { - if (!mounted || !_runtime.modeChanged(id, mode, name)) return; - unawaited(_sessions.refresh()); - } - - /// An accepted thinking level updates the opened row like a mode switch. - void _effortChanged(String id, ChatEffortState state) { - if (!mounted || !_runtime.effortChanged(id, state)) return; - unawaited(_sessions.refresh()); - } - @override JsonMap? _rowFor(String id) => _runtime.rowFor(id); @@ -410,97 +381,62 @@ class _ChatScreenState extends State _sessions.removeListener(_availableSessionsChanged); _folds.removeListener(_nextChanged); _runtime.removeListener(_runtimeChanged); - if (widget.runtime == null) { - _runtime.dispose(); - } else { - _sessions.onSessionReplaced = null; - } + _runtime.removeSessionReplacedListener(_replacedElsewhere); + if (widget.runtime == null) _runtime.dispose(); super.dispose(); } @override - Widget _thread( - String selected, - VoidCallback onBack, { - ChatWorkspacePane? pane, - BuildContext? paneContext, - }) { - final row = _rowFor(selected); - final start = _runtime.startNotice; - final thread = ChatThreadView( - key: ValueKey('chat-session-$selected'), - gateway: _runtime.gatewayFor(selected), + Widget _thread(ChatWorkspacePane pane) { + final selected = pane.sessionId; + return buildChatPaneContent( + runtime: _runtime, sessionId: selected, - title: '${row?['title'] ?? ''}'.trim(), - session: row, - syncToken: widget.syncToken, - scrollPositions: _runtime.scrollPositions, - transcripts: _runtime.transcripts, - initialNotice: start != null && start.id == selected - ? start.notice - : null, - onBack: onBack, - onModelChanged: (applied) => _modelChanged(selected, applied), - onModeChanged: (mode, name) => _modeChanged(selected, mode, name), - onEffortChanged: (state) => _effortChanged(selected, state), - onNewSession: _startedNewSession, - onSessionRenamed: (title) => _renamed(selected, title), - onSessionClosed: () => _closed(selected), - onColorSelected: (color) => _sessions.setColor(selected, color), - onNextChat: _nextAfter(selected) != null - ? () => _openNext(selected) - : null, - useNativeBack: _page.open, - pasteTarget: - _workspaceVisible && - (pane == null || pane.id == _workspace.activePaneId), - // A floating chat is never the active pane, so its composer takes a - // paste while it has the keyboard. - ownsPasteWhenFocused: pane != null && _workspace.isFloating(pane.id), - showBackButton: pane == null - ? null - : _page.open || !showsListBesideDetail(context), - paneControls: pane == null - ? const [] - : _workspace.isFloating(pane.id) - ? _floatControls(pane) - : [ - ChatBarAction( - label: 'Add chat pane', - onPressed: () => _addPane(paneContext ?? context), - materialIcon: Icons.add_box_outlined, - cupertinoIcon: CupertinoIcons.plus_square, - ), - if (_workspace.paneCount > 1) + placement: ChatPanePlacement( + syncToken: widget.syncToken, + onBack: _back, + onNewSession: _startedNewSession, + onSessionClosed: () => _closed(selected), + onNextChat: _nextAfter(selected) != null + ? () => _openNext(selected) + : null, + useNativeBack: _page.open, + pasteTarget: _workspaceVisible && pane.id == _workspace.activePaneId, + // 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: 'Open chats (${_workspace.paneCount})', - onPressed: () => _pickPane(paneContext ?? context), - materialIcon: Icons.view_quilt_outlined, - cupertinoIcon: CupertinoIcons.square_split_2x2, + label: 'Add chat pane', + onPressed: () => _addPane(paneContext), + materialIcon: Icons.add_box_outlined, + cupertinoIcon: CupertinoIcons.plus_square, ), - if (_workspace.paneCount > 1 && showsListBesideDetail(context)) - chatCenterStageAction(ChatCenterStageController.instance), - ...chatPaneMoveActions( - ChatWorkspacePaneScope.maybeOf(paneContext ?? context), - 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, + 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), ), - ], - ); - return ChatComposerFocusScope( - sessionId: selected, - requests: _composerFocus, - child: ServerContext.forServer( - context, - _runtime.serverIdFor(selected), - thread, + ..._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/workspace/chat_workspace_geometry.dart b/app/lib/features/chat/workspace/chat_workspace_geometry.dart index 3900ff44..0724cad8 100644 --- a/app/lib/features/chat/workspace/chat_workspace_geometry.dart +++ b/app/lib/features/chat/workspace/chat_workspace_geometry.dart @@ -142,8 +142,10 @@ class ChatWorkspaceGeometry { }; if (gap < -slack || gap > chatPaneDividerExtent + slack) continue; final overlap = horizontal - ? math.min(origin.bottom, rect.bottom) - math.max(origin.top, rect.top) - : math.min(origin.right, rect.right) - math.max(origin.left, rect.left); + ? math.min(origin.bottom, rect.bottom) - + math.max(origin.top, rect.top) + : math.min(origin.right, rect.right) - + math.max(origin.left, rect.left); if (overlap <= slack) continue; final centred = horizontal ? rect.top <= centre && centre < rect.bottom diff --git a/app/test/features/chat/chat_runtime_test.dart b/app/test/features/chat/chat_runtime_test.dart index 4308bae6..877b643c 100644 --- a/app/test/features/chat/chat_runtime_test.dart +++ b/app/test/features/chat/chat_runtime_test.dart @@ -1,7 +1,6 @@ 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/conversation/chat_models.dart'; class _Gateway implements ApiGateway { @override From fdc730422dcdb9db98158e42fdee3174dc228cb9 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 10 Nov 2026 21:17:40 +0000 Subject: [PATCH 3/5] 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); + }); +} From 16afda363468cc0ab8fc07291b859adc0c94f70c Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 10 Nov 2026 21:33:07 +0000 Subject: [PATCH 4/5] Close menus with Escape and keep a window's popups focused AppMenuAnchor is the app's one MenuAnchor: root overlay, takes the keyboard while open (Escape and arrows work wherever focus was) and gives it back. A window no longer takes the keyboard back from a popup its own press opened. In a window, Files opens as a page of that window and Chat details is in the More menu. --- .../conversation/chat_effort_control.dart | 5 +- .../chat/conversation/chat_thread_view.dart | 13 ++- .../pipelines/widgets/pipeline_controls.dart | 5 +- app/lib/shell/windows/window_focus.dart | 21 +++-- app/lib/shell/windows/window_host.dart | 3 + app/lib/shell/windows/window_layer.dart | 10 ++- app/lib/ui/adaptive/app_menu_anchor.dart | 82 +++++++++++++++++++ .../ui/adaptive/segmented_bar_overflow.dart | 5 +- .../shell/windows/window_layering_test.dart | 27 ++++++ .../windows/window_popup_rules_test.dart | 19 ++--- .../ui/adaptive/app_menu_anchor_test.dart | 61 ++++++++++++++ 11 files changed, 223 insertions(+), 28 deletions(-) create mode 100644 app/lib/ui/adaptive/app_menu_anchor.dart create mode 100644 app/test/ui/adaptive/app_menu_anchor_test.dart diff --git a/app/lib/features/chat/conversation/chat_effort_control.dart b/app/lib/features/chat/conversation/chat_effort_control.dart index 8ebe1e5e..ff86f1de 100644 --- a/app/lib/features/chat/conversation/chat_effort_control.dart +++ b/app/lib/features/chat/conversation/chat_effort_control.dart @@ -1,3 +1,4 @@ +import '../../../ui/adaptive/app_menu_anchor.dart'; import 'dart:async'; import 'package:flutter/cupertino.dart'; @@ -158,9 +159,7 @@ class _ChatEffortControlState extends State { ), ); } - return MenuAnchor( - // Above every floating window, and not clipped to one. - useRootOverlay: true, + return AppMenuAnchor( 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 5aa31dfc..c6a03f99 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -301,7 +301,18 @@ class _ChatThreadViewState extends State { _filesSheetOpen = true; final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; - final sheet = cupertino + // In a floating window the explorer is a page of that window, so a file + // it opens stays in the window too. + final sheet = WindowScope.maybeOf(context) != null + ? Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => Scaffold( + appBar: AppBar(title: const Text('Files')), + body: FilesPanel(controller: _files), + ), + ), + ) + : cupertino ? showCupertinoModalPopup( context: context, builder: (_) => Align( diff --git a/app/lib/features/pipelines/widgets/pipeline_controls.dart b/app/lib/features/pipelines/widgets/pipeline_controls.dart index deb81e3e..859b4bbc 100644 --- a/app/lib/features/pipelines/widgets/pipeline_controls.dart +++ b/app/lib/features/pipelines/widgets/pipeline_controls.dart @@ -1,3 +1,4 @@ +import '../../../ui/adaptive/app_menu_anchor.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -108,9 +109,7 @@ class PipelineSortButton extends StatelessWidget { ), ); } - return MenuAnchor( - // Above every floating window, and not clipped to one. - useRootOverlay: true, + return AppMenuAnchor( menuChildren: [ for (final option in PipelineSort.values) MenuItemButton( diff --git a/app/lib/shell/windows/window_focus.dart b/app/lib/shell/windows/window_focus.dart index 8be7d9ca..d3d55f9e 100644 --- a/app/lib/shell/windows/window_focus.dart +++ b/app/lib/shell/windows/window_focus.dart @@ -40,18 +40,29 @@ class WindowFocus { : current; } - /// Focuses [id]'s window once this frame has built it. + /// Whether something covers the windows and owns the keyboard (a sheet, + /// dialog or page over the app); set by the host. + bool Function()? covered; + + /// Focuses [id]'s window once this frame has built it, unless a popup the + /// same press opened has covered the windows meanwhile. void focusSoon(String id) { WidgetsBinding.instance ..addPostFrameCallback((_) { - final scope = _scopes[id]; - if (scope != null && scope.context != null && scope.canRequestFocus) { - scope.requestFocus(); - } + if (covered?.call() ?? false) return; + focusNow(id); }) ..ensureVisualUpdate(); } + /// Focuses [id]'s window if it is built. + void focusNow(String id) { + final scope = _scopes[id]; + if (scope != null && scope.context != null && scope.canRequestFocus) { + scope.requestFocus(); + } + } + /// Gives the keyboard back to what had it before the windows showed, if /// a window has it now. void release() { diff --git a/app/lib/shell/windows/window_host.dart b/app/lib/shell/windows/window_host.dart index 357bb895..5a13edbf 100644 --- a/app/lib/shell/windows/window_host.dart +++ b/app/lib/shell/windows/window_host.dart @@ -33,6 +33,9 @@ class _WindowHostState extends State { void initState() { super.initState(); widget.manager.addListener(_changed); + // The shell page is not the top route while a popup or page covers it. + _focus.covered = () => + mounted && !(ModalRoute.of(context)?.isCurrent ?? true); WidgetsBinding.instance.addPostFrameCallback((_) => _changed()); } diff --git a/app/lib/shell/windows/window_layer.dart b/app/lib/shell/windows/window_layer.dart index b30e78b8..5d7b927d 100644 --- a/app/lib/shell/windows/window_layer.dart +++ b/app/lib/shell/windows/window_layer.dart @@ -117,9 +117,12 @@ class _WindowLayerState extends State ); } + /// A press brings the window to the top and gives it the keyboard at + /// once, before the press does anything else (focus a field, open a + /// popup that takes the keyboard itself). void _pressed() { + if (!widget.focus.has(_id)) widget.focus.focusNow(_id); widget.manager.raise(_id); - if (!widget.focus.has(_id)) widget.focus.focusSoon(_id); } @override @@ -203,6 +206,7 @@ class _WindowLayerState extends State ], ); final center = widget.bounds.center(Offset.zero); + final current = ModalRoute.of(context)?.isCurrent ?? true; return AnimatedBuilder( animation: _reveal, builder: (context, child) { @@ -213,7 +217,9 @@ class _WindowLayerState extends State enabled: !offstage, child: SurfaceVisibility( shown: !offstage, - current: !hiding, + // Not while a page, sheet or dialog covers the app: the + // window's own route is always its navigator's current one. + current: !hiding && current, child: IgnorePointer( ignoring: hiding, child: ExcludeFocus(excluding: hiding, child: child!), diff --git a/app/lib/ui/adaptive/app_menu_anchor.dart b/app/lib/ui/adaptive/app_menu_anchor.dart new file mode 100644 index 00000000..e1aa31df --- /dev/null +++ b/app/lib/ui/adaptive/app_menu_anchor.dart @@ -0,0 +1,82 @@ +import 'package:flutter/material.dart'; + +/// The app's anchored menu: a [MenuAnchor] whose panel is in the root +/// overlay, so it opens above every floating window and is never clipped to +/// one, and which takes the keyboard while open, so Escape closes it and the +/// arrow keys move through it wherever the keyboard was. Closing gives the +/// keyboard back to what had it. +/// +/// Use it instead of [MenuAnchor] everywhere: any content can end up in a +/// window, where only the root overlay reaches past the window's edges. +class AppMenuAnchor extends StatefulWidget { + const AppMenuAnchor({ + super.key, + required this.menuChildren, + required this.builder, + this.controller, + this.style, + this.alignmentOffset, + this.child, + }); + + final List menuChildren; + final MenuAnchorChildBuilder builder; + final MenuController? controller; + final MenuStyle? style; + final Offset? alignmentOffset; + final Widget? child; + + @override + State createState() => _AppMenuAnchorState(); +} + +class _AppMenuAnchorState extends State { + final FocusNode _focus = FocusNode( + debugLabel: 'menu anchor', + skipTraversal: true, + ); + FocusNode? _previous; + + @override + void dispose() { + _focus.dispose(); + super.dispose(); + } + + void _opened() { + final current = FocusManager.instance.primaryFocus; + _previous = identical(current, _focus) ? null : current; + _focus.requestFocus(); + } + + void _closed() { + final previous = _previous; + _previous = null; + if (!_focus.hasPrimaryFocus) return; + if (previous != null && + previous.context != null && + previous.canRequestFocus) { + previous.requestFocus(); + } else { + _focus.unfocus(); + } + } + + @override + Widget build(BuildContext context) => MenuAnchor( + useRootOverlay: true, + controller: widget.controller, + style: widget.style, + alignmentOffset: widget.alignmentOffset, + childFocusNode: _focus, + onOpen: _opened, + onClose: _closed, + menuChildren: widget.menuChildren, + builder: (context, menu, child) => Focus( + focusNode: _focus, + includeSemantics: false, + child: widget.builder(context, menu, child), + ), + child: widget.child, + ); +} diff --git a/app/lib/ui/adaptive/segmented_bar_overflow.dart b/app/lib/ui/adaptive/segmented_bar_overflow.dart index 64ba8173..dffdfe12 100644 --- a/app/lib/ui/adaptive/segmented_bar_overflow.dart +++ b/app/lib/ui/adaptive/segmented_bar_overflow.dart @@ -1,3 +1,4 @@ +import 'app_menu_anchor.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -98,9 +99,7 @@ class SegmentedMoreButton extends StatelessWidget { ), ); } - return MenuAnchor( - // Above every floating window, and not clipped to one. - useRootOverlay: true, + return AppMenuAnchor( menuChildren: [ for (final entry in entries) if (entry.choices.isEmpty) diff --git a/app/test/shell/windows/window_layering_test.dart b/app/test/shell/windows/window_layering_test.dart index 55fe0163..a0371596 100644 --- a/app/test/shell/windows/window_layering_test.dart +++ b/app/test/shell/windows/window_layering_test.dart @@ -7,6 +7,8 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/shell/windows/window_manager.dart'; +import 'package:pipelines_app/ui/motion/surface_visibility.dart'; + import 'window_test_harness.dart'; /// Layering acceptance (docs/plans/floating-windows.md, Phase 1.4): every @@ -210,6 +212,31 @@ void main() { expect(find.text('Sheet item').hitTestable(), findsOneWidget); }); + testWidgets('a popup opened by the press that focuses its window keeps the ' + 'keyboard', (tester) async { + await open(tester, 0); + // The keyboard is in the app behind, as after using another tab. + FocusManager.instance.primaryFocus?.unfocus(); + await tester.pump(); + await tester.tap(find.byKey(const ValueKey('b-sheet'))); + await tester.pumpAndSettle(); + expect(find.text('Sheet item').hitTestable(), findsOneWidget); + final focus = FocusManager.instance.primaryFocus!.context!; + expect(ModalRoute.of(focus), isA>()); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(find.text('Sheet item'), findsNothing); + // The window content is not the current surface under a popup. + await tester.tap(find.byKey(const ValueKey('b-dialog'))); + await tester.pumpAndSettle(); + expect( + SurfaceVisibility.currentOf( + tester.element(find.byKey(const ValueKey('content-b'))), + ), + isFalse, + ); + }); + testWidgets('Escape closes the popup, not the window', (tester) async { await open(tester, 0); await tester.tap(find.byKey(const ValueKey('a-dialog'))); diff --git a/app/test/shell/windows/window_popup_rules_test.dart b/app/test/shell/windows/window_popup_rules_test.dart index 5178a005..a6dea366 100644 --- a/app/test/shell/windows/window_popup_rules_test.dart +++ b/app/test/shell/windows/window_popup_rules_test.dart @@ -3,23 +3,20 @@ 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. +/// so a menu panel, which may extend past the window, must be in the root +/// overlay. Any content can end up in a window, so the app's menus are all +/// `AppMenuAnchor`, the one place a `MenuAnchor` is built. void main() { - test('every MenuAnchor targets the root overlay', () { + test('MenuAnchor is used only through AppMenuAnchor', () { final offenders = []; for (final file in Directory('lib').listSync(recursive: true)) { if (file is! File || !file.path.endsWith('.dart')) continue; + if (file.path.endsWith('ui/adaptive/app_menu_anchor.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}'); - } + if (match.start > 0 && source[match.start - 1] == 'p') continue; + final line = '\n'.allMatches(source.substring(0, match.start)).length; + offenders.add('${file.path}:${line + 1}'); } } expect(offenders, isEmpty); diff --git a/app/test/ui/adaptive/app_menu_anchor_test.dart b/app/test/ui/adaptive/app_menu_anchor_test.dart new file mode 100644 index 00000000..19cc9043 --- /dev/null +++ b/app/test/ui/adaptive/app_menu_anchor_test.dart @@ -0,0 +1,61 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/adaptive/app_menu_anchor.dart'; + +void main() { + testWidgets('Escape closes the menu and the keyboard returns to the field', ( + tester, + ) async { + var picked = 0; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Column( + children: [ + const TextField(key: ValueKey('field')), + AppMenuAnchor( + menuChildren: [ + MenuItemButton( + onPressed: () => picked++, + child: const Text('First'), + ), + MenuItemButton( + onPressed: () => picked += 10, + child: const Text('Second'), + ), + ], + builder: (context, menu, _) => IconButton( + tooltip: 'More', + onPressed: () => menu.isOpen ? menu.close() : menu.open(), + icon: const Icon(Icons.more_vert), + ), + ), + ], + ), + ), + ), + ); + await tester.tap(find.byKey(const ValueKey('field'))); + await tester.pump(); + final field = FocusManager.instance.primaryFocus; + + await tester.tap(find.byTooltip('More')); + await tester.pumpAndSettle(); + expect(find.text('First'), findsOneWidget); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(find.text('First'), findsNothing); + expect(FocusManager.instance.primaryFocus, same(field)); + + // The arrow keys and Enter work from wherever the keyboard was. + await tester.tap(find.byTooltip('More')); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(picked, 10); + expect(find.text('First'), findsNothing); + }); +} From 9d533fcad97748d6269f702cf8429ed2def03c6a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 10 Nov 2026 21:43:37 +0000 Subject: [PATCH 5/5] Describe floating chats on the window system in the notes --- app/notes/chat-floating-pane.md | 186 ++++++++++++-------------------- app/notes/floating-windows.md | 12 ++- 2 files changed, 74 insertions(+), 124 deletions(-) diff --git a/app/notes/chat-floating-pane.md b/app/notes/chat-floating-pane.md index f74cb939..55fa714b 100644 --- a/app/notes/chat-floating-pane.md +++ b/app/notes/chat-floating-pane.md @@ -1,129 +1,75 @@ -# Floating chat pane +# Floating chats -On a wide layout chats can leave the split tiling and float in windows over -the app, like the floating terminal. Ctrl+Y (Cmd+Y on macOS) shows or hides -all of them together, on every destination. +On a wide layout a chat can leave the split tiling and float in a window over +the app. The windows belong to the shell's window system +(`notes/floating-windows.md`), not to the Chat destination: they show over +every destination and come back at app start without Chat being opened. ## Behaviour -- **Float**: a tiled pane's More menu offers `Float (Ctrl+Y)` (`Cmd+Y` on Apple - platforms) when another chat stays in the tiling. The last tiled chat cannot - float, because the tiling would be empty. Any number of chats can float; - floating one shows every floating chat. A new window opens at the default - frame stepped 32 px down and right per window already floating. -- **Show / hide**: the chord, a window's X and the menu's `Hide floating chats` - show or hide all floating windows at once. Each window keeps its own frame, - so they come back exactly where they were. -- **Window**: you drag it by its title bar and resize it from the lower right - corner. The title bar has Dock and Hide buttons. The window keeps its frame - inside the app when the browser window resizes (`fitChatFloat`). Grow and fade - in, and shrink and fade out, use `Motion.standard` through `Motion.of`, so - reduced motion and the animation speed apply. Each window animates on its - own, so a chat floated while others show grows in alone. -- **Floating chat's menu**: Dock (back into the tiling, right of the active pane, - which it becomes; the others keep floating), `Hide floating chats (Ctrl+Y)`, - and Close pane (removes it from the workspace; no backend close). If the last - tiled pane closes, the oldest floating chat docks in its place. -- **Shortcut**: Ctrl+Y on every platform, and Cmd+Y on macOS and iOS. It is an - early key handler, so it works from a composer or the terminal; Y, Shift+Y and - Alt+Y still type. When no chat floats, Ctrl+Y floats the tiled pane that has - the keyboard. When no pane has the keyboard, or that pane cannot float, the - chord is left alone. So in the terminal Ctrl+Y stays the shell's yank until a - chat floats. After that, on Windows, Linux and web, Ctrl+Y toggles even from - the terminal (yank is unavailable there, as with Ctrl+T). On macOS, Ctrl+Y in - a `TypingSurface` (terminal) always goes to the shell, and Cmd+Y toggles. -- **Focus**: showing the chat focuses its composer. Hiding it gives the keyboard - back to whatever had it before (as `TerminalFocus` does), otherwise the - keyboard is unfocused. -- **Where it shows**: on a wide layout, over every destination (Runs, - Pipelines, Settings...), like the floating terminal. The windows move, - resize, type, hide and dock there as on Chat. On narrow or phone layouts the - menu item is absent and the chord passes through; floating chats stay - floating, unpainted, with their state, and reappear when the window is wide - again. -- **Other destinations (how)**: the shell hides a destination with - `FadeThroughStack` (muted tickers, no input, no focus). The windows already - paint and hit-test in the root overlay; the host also re-enables tickers - around each window (`TickerMode`) and parents each floating pane's - `FocusScope` on the shell's `FloatingFocusRoot` - (`ui/floating/floating_layer.dart`, above the destination stack), so a - hidden destination's `ExcludeFocus` does not take its keyboard. Before this, - leaving Chat started the hide animation on a muted ticker: the window stayed - painted but ignored input, so it could not be moved or closed. -- **Persistence**: `pipelines.next.chatFloat.v1` is stored device-locally and - scoped like the workspace layout. Record version 2 holds the floating panes - (id and session, oldest first, at most 12), whether they are shown, and a - frame per pane id. A docked pane keeps its frame, so floating it again - returns it to the same place; a closed pane's frame is dropped. Version 1 - records (one pane, one frame) still load. It is restored after the workspace - layout. A saved float whose session is already open is dropped. +- **Float**: a tiled pane's More menu offers `Float (Alt+Y)` (`Option+Y` on + Apple platforms) when another chat stays in the tiling; the last tiled chat + cannot float. Any number of chats can float. A new window opens where that + chat's window last was, else at the default frame stepped 32 px per chat + window already open. +- **Window**: drag the title bar to move, the lower right corner to resize, + double click the title to maximise. The title bar has Dock, Minimise, + Maximise and Close. + - **Dock** puts the chat back into the tiling, right of the active pane. When + the Chat destination is not built it opens the chat there instead. + - **Minimise** hides that window; the chord brings it back. + - **Close (X)** closes the window and returns nothing to the tiling. The chat + itself is not closed on the server. +- **Chord**: Alt+Y, Ctrl+Y, and Cmd+Y on Apple platforms (`chatFloatShortcut`). + With chat windows open it hides or shows all of them. With none it floats the + active tiled pane, when that pane can float and Chat has the keyboard; + otherwise the key is left alone (so Ctrl+Y stays the shell's yank in a + terminal). On macOS Ctrl+Y in a terminal always goes to the shell. +- **Focus**: a window that shows or comes to the top puts the keyboard in its + composer; hiding the last window gives it back to what had it. +- **Popups**: sheets, dialogs, menus and tooltips opened from a floating chat + are above every window. Files opens as a page inside the window, and a file + opened from it stays in the window. Because the window's own title bar names + the chat, the More menu has `Chat details`. +- **Layout inside a window**: the chat is laid out for the window's size, so a + narrow window gets the compact action bar. +- **Narrow layouts**: no Float, the chord passes through, and chat windows are + hidden (kept, with their state) until the app is wide again. -## Design +## How -- `ChatWorkspaceController` keeps the floating panes outside the tree - (`chat_workspace_float.dart`, a `part` with the `ChatWorkspaceFloat` - extension: `floatingPanes`, `isFloating`, `dock(paneId)`, `restoreFloats`). - `panes` and `paneCount` stay tiled-only. A pane keeps its id through float, - hide and dock. Frames live in `ChatFloatFrames` (by pane id). -- `ChatWorkspace` gives each pane's content a `GlobalKey`. A floating chat is - that same keyed subtree, built by `ChatFloatHost` inside the workspace, so the - `ChatThreadView` State, draft, scroll and running turn move with it and are - not rebuilt. Its inherited context and focus tree stay in the workspace. -- `FloatingLayer` (`lib/ui/floating/`) paints a layer in the root overlay - through `OverlayPortal`. The chat window covers the whole app. The terminal's - floating window now uses the same layer, so the two share one z-order: the - last one pressed, focused or opened is on top. Without an overlay (bare - widget tests) the layer paints in place. -- New files: `chat_float_{host,window,binding,store,shortcut}.dart`, - `chat_workspace_float.dart`, `chat_screen_float.dart` and - `ui/floating/floating_layer.dart`. Existing files changed: workspace - controller hooks (open, split, close, replace, restore), the - `ChatWorkspace.floatFrame` parameter and keyed content, the pane controls and - `/close` and `/new` handling in `screen.dart`, the persistence wiring in - `chat_screen_workspace.dart`, and `terminal_stage.dart`. - -## Not done - -- The sidebar's "visible" highlight does not count floating chats. -- Floating windows need the Chat destination to have been built; the shell - builds every destination up front, so this holds today. -- Cmd+Y in a browser on macOS may be taken by the browser (History) before the - app sees it. Ctrl+Y works there. +- `ChatRuntime` (`features/chat/chat_runtime.dart`), one per server scope, kept + by `PipelinesApp`: the session list controller, opened rows, accepted models, + transcript positions and caches, composer focus requests. +- `buildChatPaneContent` (`chat_pane_content.dart`) builds a conversation with + its scopes, keyed by `ChatRuntime.viewKey`. The tiling and the chat window + kind both use it, so Float and Dock move the same live view (transcript, + scroll, draft, running turn) between them in one frame. +- `ChatWindows` (`features/chat/windows/`): the `chat` `WindowKind`, the chord, + Dock, and what `/new` and `/close` do to a chat in a window. It reads the + session list for its windows' rows when the Chat destination is not built. +- The workspace controller keeps no floating chats. `detach` takes a pane out, + `dock` puts a chat back, and `showOutside` lets it show a chat's window + instead of opening that chat a second time. A chat is drawn once: if the + tiling holds a chat that also has a window, the window closes. +- **Saved state**: chat windows are entries of `pipelines.windows.v1`, carrying + their server key. The older `pipelines.next.chatFloat.v1` record (versions 1 + and 2) is read once at start and turned into windows. ## Checks -### Multiple floats, every destination (2026-11-10) - -- `tool/memwatch/full.sh 'test/features/chat/chat_floating_pane_test.dart test/features/chat/workspace test/ui/floating'`: - 93 passed, 0 failed. `tool/analyze.sh lib test/features/chat`: clean. -- New tests: several floats toggled together by the chord and restored to - their frames, docking one keeps the other (`chat_floating_pane_test.dart`); - a float over another destination (a real `FadeThroughStack` page switch) - is hit-testable, drags, takes focus and typing, and hides by chord and its - X; controller, record v1/v2 and per-pane frame tests - (`chat_workspace_float_test.dart`). -- Fixed on the way: a drag read the frame from the last build, so several - pointer events in one frame lost movement; and a never-moved window's - cascaded frame shifted when another window docked (frames are now placed - when a chat floats). - -### Single float (earlier) - -- `tool/analyze.sh lib test/features/chat test/ui test/features/terminal`: clean - after the merge with main (pane moves, a410b9e5). In the merge, Float sits in - the pane menu right after the Move items. -- `tool/memwatch/full.sh 'test/features/chat test/features/terminal test/shell test/ui/floating'`: - 1395 passed, 0 failed; peak 1936 MB; 592 s. New tests are - `test/features/chat/workspace/chat_workspace_float_test.dart` (controller, - record and binding), `chat_float_shortcut_test.dart` (chord, typing Y, - terminal and macOS, narrow), `test/features/chat/chat_floating_pane_test.dart` - (menu Float and Dock keep the `ChatThreadView` State and draft, reload, - narrow) and `test/ui/floating/floating_layer_test.dart` (z-order and click - pass-through). -- Real-Chrome captures used the fixture (`chats=3&rich=1&colors=1`) at - 1280x800 and are in `/tmp/float-cap/c/`: the pane menu with Float, the - floating chat with a typed draft, the chat hidden by Control+y with focus back - in the tiled composer, two films of the chord, and the floating chat over the - terminal panel. Headless Chrome reports macOS, so the label reads `Cmd+Y` and - Control+y also toggles. Not captured: the chat floating over a floating - (rather than panel) terminal. +- `test/features/chat/chat_floating_pane_test.dart` (the Chat screen with the + window host), `test/features/chat/windows/chat_windows_test.dart`, + `test/features/chat/workspace/chat_workspace_float_test.dart`, + `chat_float_shortcut_test.dart`, `test/features/chat/chat_runtime_test.dart`. +- Real app (capture kit, 2026-11-10/11, 1280x800 and 1920x1080, light and + dark), from a floating chat over Chat and over Runs: chat details, model + dialog, mode sheet, thinking menu, More menu, title-bar and control tooltips, + typing; Files page with its sort menu, row menu and tooltip, a file opened + inside the window; reload restoring the window over Runs without visiting + Chat; hide and show by chord, maximise, minimise, Dock; a live turn + animating over Runs; the Turn changes page, a diff opened from it and a shell + command's full-screen page, each inside the window; a question card. +- Not captured: paste of text or an image, a question-card dropdown (the + fixture's question has radio options), the image viewer, and the + text-selection menu (the kit has no right-click). diff --git a/app/notes/floating-windows.md b/app/notes/floating-windows.md index c15a477d..954a7ea3 100644 --- a/app/notes/floating-windows.md +++ b/app/notes/floating-windows.md @@ -1,7 +1,7 @@ # Floating windows (window system core) -Plan: `docs/plans/floating-windows.md`. Phase 1 adds the shell-level window -system; no feature uses it yet (chats move in Phase 2, the terminal in Phase 3). +Plan: `docs/plans/floating-windows.md`. The shell-level window system hosts +floating chats (`notes/chat-floating-pane.md`); the terminal moves in Phase 3. ## Pieces (`lib/shell/windows/`) @@ -31,8 +31,12 @@ system; no feature uses it yet (chats move in Phase 2, the terminal in Phase 3). and never clipped to one. - The window's navigator covers the whole host so popups anchored to a button measure in app coordinates and tooltips paint outside the window; only the - content area takes input. So a `MenuAnchor` in window content needs - `useRootOverlay: true` (its panel may extend past the window). + content area takes input. So menus are `AppMenuAnchor` + (`ui/adaptive/app_menu_anchor.dart`), whose panel is in the root overlay; a + test rejects a bare `MenuAnchor`. +- A window takes the keyboard at the press, not after it, and never from a + popup that covers the app; its content is not the current surface + (`SurfaceVisibility`) while one does. - Known limit: a tooltip of a window that is not on top can be covered by a window above it where they overlap (tooltips paint in their own window's overlay). Pressing a window raises it, so menus are not affected.