From de0c06cec19bd5ca76f921719de1e7f4e68d39f8 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 7 Nov 2026 00:46:02 +0000 Subject: [PATCH] Chat: slash focuses the composer; Ctrl+Tab over one pane toggles recent chats A bare / typed outside any text field puts the keyboard in the active chat's composer through the existing focus request, after the frame, so the slash is not typed into it. Ctrl+Tab with a single pane now swaps in the chat shown before the current one and back; two or more panes keep cycling panes. The visit remembers its shown chats most-recent-first, dropping closed, /new-moved and other-server ids. --- app/lib/features/chat/chat_screen_keys.dart | 96 +++++++++ .../features/chat/chat_screen_workspace.dart | 26 +-- app/lib/features/chat/screen.dart | 10 +- app/notes/chat-keyboard-focus.md | 26 +++ .../chat/chat_keyboard_focus_test.dart | 190 ++++++++++++++++++ 5 files changed, 335 insertions(+), 13 deletions(-) create mode 100644 app/lib/features/chat/chat_screen_keys.dart create mode 100644 app/notes/chat-keyboard-focus.md create mode 100644 app/test/features/chat/chat_keyboard_focus_test.dart diff --git a/app/lib/features/chat/chat_screen_keys.dart b/app/lib/features/chat/chat_screen_keys.dart new file mode 100644 index 00000000..2d4535a9 --- /dev/null +++ b/app/lib/features/chat/chat_screen_keys.dart @@ -0,0 +1,96 @@ +part of 'screen.dart'; + +/// How many chats the visit remembers for Ctrl+Tab over a single pane. +const chatRecentSessionLimit = 8; + +/// Keys the Chat destination answers from anywhere in it, also while the +/// sidebar or a toolbar owns focus: a bare `/` puts the keyboard in the open +/// chat's composer, and Ctrl+Tab over a single pane returns to the chat shown +/// before it (and back again). Both are handled before the focus tree, like +/// the workspace's pane cycling, and leave other destinations, popups, +/// dialogs and any focused text field alone. +mixin _ChatScreenKeys on State, _ChatScreenWorkspace { + void _open(JsonMap session, {bool focusComposer}); + + /// The chats this visit has shown in the workspace, most recent first; the + /// active one leads it. In memory only: a reopened app starts afresh. + final List _recentSessions = []; + + /// Moves the active pane's chat to the front. Called on every workspace + /// change, including a restored layout, so the chat opened before the + /// current one is always the second entry. + @override + void _noteRecentSession() { + final id = _workspace.activePane?.sessionId; + if (id == null || id.isEmpty || _recentSessions.firstOrNull == id) return; + _recentSessions + ..remove(id) + ..insert(0, id); + if (_recentSessions.length > chatRecentSessionLimit) { + _recentSessions.removeLast(); + } + } + + /// Drops [id]: a closed chat, or one `/new` moved to a fresh session. + void _forgetRecentSession(String id) => _recentSessions.remove(id); + + /// Drops every remembered chat: ids belong to one server. + @override + void _forgetRecentSessions() => _recentSessions.clear(); + + /// Over a single pane, opens the chat shown before the active one with its + /// composer focused; false when this visit has shown no other chat. + @override + bool _toggleRecentChat() { + final current = _workspace.activePane?.sessionId; + final previous = _recentSessions + .where((id) => id != current) + .firstOrNull; + if (previous == null) return false; + _open(_rowFor(previous) ?? {'id': previous}, focusComposer: true); + return true; + } + + /// Whether the shown destination is Chat with no popup, dialog or other + /// route over it, so a key pressed now is meant for the open chat. + @override + bool _chatOwnsKeyboard() { + final destination = ShellBarScope.maybeOf(context)?.registry.focus; + if (destination != null && destination != AppDestination.chat) return false; + final focusContext = FocusManager.instance.primaryFocus?.context; + final route = focusContext == null + ? ModalRoute.of(context) + : ModalRoute.of(focusContext); + return route is! PopupRoute && (route == null || route.isCurrent); + } + + /// A bare `/` typed outside any text field focuses the active chat's + /// composer. The composer takes focus after this frame (see + /// [ChatComposerFocusRequests]), once the host has finished delivering the + /// keystroke, so the slash itself is not typed into it. Inside a text field + /// (the composer, a dialog's field) `/` stays an ordinary character. + bool _slashFocusKey(KeyEvent event) { + final keyboard = HardwareKeyboard.instance; + if (event is! KeyDownEvent || + event.character != '/' || + keyboard.isControlPressed || + keyboard.isMetaPressed || + keyboard.isAltPressed || + !_workspaceVisible) { + return false; + } + final id = _workspace.activePane?.sessionId; + if (id == null || _textFieldHasFocus() || !_chatOwnsKeyboard()) { + return false; + } + _composerFocus.request(id); + return true; + } + + /// Whether an editable text control holds focus, wherever it is. + bool _textFieldHasFocus() { + final context = FocusManager.instance.primaryFocus?.context; + final editable = context?.findAncestorWidgetOfExactType(); + return editable != null && !editable.readOnly; + } +} diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 07456661..eea0bb68 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -4,6 +4,10 @@ part of 'screen.dart'; mixin _ChatScreenWorkspace on State { Map get _openedSessions; ChatComposerFocusRequests get _composerFocus; + bool _chatOwnsKeyboard(); + bool _toggleRecentChat(); + void _noteRecentSession(); + void _forgetRecentSessions(); JsonMap? _rowFor(String id); void _back(); bool get _pageOpen; @@ -89,6 +93,7 @@ mixin _ChatScreenWorkspace on State { _workspaceBinding = null; if (_workspaceScope != null && scope != _workspaceScope) { _workspace.restoreLayout(ChatWorkspaceSnapshot.fromLayout(null, null)!); + _forgetRecentSessions(); _workspaceVisible = false; _usedWorkspace = true; _sidebarMode = ChatSidebarMode.expanded; @@ -111,7 +116,9 @@ mixin _ChatScreenWorkspace on State { String _workspaceSignature = ''; /// Ctrl+Tab cycles retained panes even when the sidebar or toolbar owns - /// focus. Command+Tab stays with the operating system's application switcher. + /// focus. Over a single pane it swaps in the chat shown before this one + /// instead, and back again (see [_toggleRecentChat]). Command+Tab stays + /// with the operating system's application switcher. bool _cycleChatKey(KeyEvent event) { final keyboard = HardwareKeyboard.instance; if (event is! KeyDownEvent || @@ -120,19 +127,12 @@ mixin _ChatScreenWorkspace on State { keyboard.isMetaPressed || keyboard.isAltPressed || !_workspaceVisible || - _workspace.paneCount == 0) { - return false; - } - final destination = ShellBarScope.maybeOf(context)?.registry.focus; - if (destination != null && destination != AppDestination.chat) return false; - final focusContext = FocusManager.instance.primaryFocus?.context; - final route = focusContext == null - ? ModalRoute.of(context) - : ModalRoute.of(focusContext); - if (route is PopupRoute || (route != null && !route.isCurrent)) { + _workspace.paneCount == 0 || + !_chatOwnsKeyboard()) { return false; } final panes = _workspace.panes; + if (panes.length == 1 && _toggleRecentChat()) return true; final active = panes.indexWhere( (pane) => pane.id == _workspace.activePaneId, ); @@ -156,7 +156,9 @@ mixin _ChatScreenWorkspace on State { } void _workspaceChanged() { - if (!mounted || _workspaceBinding?.isRestoring == true) return; + if (!mounted) return; + _noteRecentSession(); + if (_workspaceBinding?.isRestoring == true) return; final signature = '${_workspace.activePaneId}:${_workspace.panes.map((p) => '${p.id}=${p.sessionId}').join(',')}'; if (_workspaceSignature == signature) return; diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index d67fbc9d..3dfbc011 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -35,6 +35,7 @@ import 'ui/sessions/chat_sessions_body.dart'; import 'ui/sessions/chat_sessions_controller.dart'; import 'ui/sessions/chat_sessions_screen.dart'; +part 'chat_screen_keys.dart'; part 'chat_screen_workspace.dart'; /// The Chat destination's list/detail switch. @@ -73,7 +74,8 @@ class ChatScreen extends StatefulWidget { State createState() => _ChatScreenState(); } -class _ChatScreenState extends State with _ChatScreenWorkspace { +class _ChatScreenState extends State + with _ChatScreenWorkspace, _ChatScreenKeys { /// 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 @@ -141,10 +143,12 @@ class _ChatScreenState extends State with _ChatScreenWorkspace { _workspace.open(initial); _workspaceVisible = true; _publishedWorkspaceSession = initial; + _noteRecentSession(); } _workspace.addListener(_workspaceChanged); _bindWorkspacePersistence(); HardwareKeyboard.instance.addHandler(_cycleChatKey); + HardwareKeyboard.instance.addHandler(_slashFocusKey); // Seen from now on, so the press that chooses the first chat counts. LastPointerKind.instance; _sessions.addListener(_nextChanged); @@ -201,6 +205,7 @@ class _ChatScreenState extends State with _ChatScreenWorkspace { void _openBySelection(JsonMap session) => _open(session, focusComposer: chatSelectionFocusesComposer(session)); + @override void _open(JsonMap session, {bool focusComposer = false}) { final id = '${session['id'] ?? ''}'; if (id.isEmpty) return; @@ -254,6 +259,7 @@ class _ChatScreenState extends State with _ChatScreenWorkspace { if (accepted != null) _acceptedModels[id] = accepted; _startNotice = (id: id, notice: notice); _openedSessions[id] = {...session}..remove('running'); + _forgetRecentSession(previousId); _workspace.replaceSession(previousId, id); if (_workspace.paneCount == 0) _open(session); } @@ -271,6 +277,7 @@ class _ChatScreenState extends State with _ChatScreenWorkspace { /// `/close` was accepted: the conversation leaves, back to the list, which /// re-reads the closed row. void _closed(String sessionId) { + _forgetRecentSession(sessionId); for (final pane in _workspace.panes .where((pane) => pane.sessionId == sessionId) @@ -391,6 +398,7 @@ class _ChatScreenState extends State with _ChatScreenWorkspace { @override void dispose() { HardwareKeyboard.instance.removeHandler(_cycleChatKey); + HardwareKeyboard.instance.removeHandler(_slashFocusKey); _page.dispose(); _workspaceBinding?.dispose(); _workspace.removeListener(_workspaceChanged); diff --git a/app/notes/chat-keyboard-focus.md b/app/notes/chat-keyboard-focus.md new file mode 100644 index 00000000..2b7faa40 --- /dev/null +++ b/app/notes/chat-keyboard-focus.md @@ -0,0 +1,26 @@ +# Slash focuses the composer; Ctrl+Tab over one pane toggles recent chats + +`lib/features/chat/chat_screen_keys.dart` (a part of `screen.dart`) adds two +Chat-destination keys, registered on `HardwareKeyboard` for the screen's +lifetime like the pane cycling in `chat_screen_workspace.dart`: + +- A bare `/` (matched on the typed character, so it follows the keyboard + layout; Ctrl/Alt/Meta chords are left alone, Ctrl+/ stays the shell's Search) + requests focus for the active pane's composer through the existing + `ChatComposerFocusRequests`. The composer takes it after the frame, once the + host has finished delivering the keystroke, so the slash is not typed into + it. Nothing happens while any editable text field has focus, while a popup + or dialog is open, or on another destination. +- Ctrl+Tab (and Ctrl+Shift+Tab) over a single pane swaps in the chat shown + before the active one, composer focused, and back again. With no earlier + chat this visit it still just focuses the composer; with two or more panes + the existing pane cycling is unchanged. + +The visit keeps a most-recent-first list of the chats the workspace has shown +(bounded to eight, in memory). It is noted on every workspace change, including +a restored layout and the routed first chat; a chat `/close`d or moved by +`/new` is dropped, and a server switch clears it. + +Tests: `test/features/chat/chat_keyboard_focus_test.dart`. Widget tests cannot +show a browser's text insertion, so "the slash is not typed" rests on the +post-frame focus request; the composer text is asserted empty. diff --git a/app/test/features/chat/chat_keyboard_focus_test.dart b/app/test/features/chat/chat_keyboard_focus_test.dart new file mode 100644 index 00000000..f5fbbce2 --- /dev/null +++ b/app/test/features/chat/chat_keyboard_focus_test.dart @@ -0,0 +1,190 @@ +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/screen.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/session_actions.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'conversation/chat_thread_fixtures.dart'; + +class _Gateway extends FakeChatGateway { + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final id in ['a', 'b', 'c']) {'id': id, 'title': 'Chat $id'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + return super.call(type, fields); + } +} + +Finder _input(String id) => find.descendant( + of: find.byKey(ValueKey('chat-composer-$id')), + matching: find.byType(EditableText), +); +EditableText _editable(WidgetTester tester, String id) => + tester.widget(_input(id)); +Finder _actions(String id) => find.byWidgetPredicate( + (widget) => widget is SessionActionsButton && widget.session['id'] == id, +); +ChatWorkspaceController _workspace(WidgetTester tester) => + tester.widget(find.byType(ChatWorkspace)).controller; + +Future _setup(WidgetTester tester) async { + SharedPreferences.setMockInitialValues({}); + tester.view.physicalSize = const Size(1800, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = _Gateway()..history = (_) async => chatPage([]); + addTearDown(gateway.close); + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destination: AppDestination.chat, + destinationBodies: { + AppDestination.chat: (_) => ChatScreen(gateway: gateway), + }, + ), + ), + ); + await tester.pumpAndSettle(); +} + +Future _openRow(WidgetTester tester, String id) async { + await tester.tap(find.byKey(Key('chat-row-$id'))); + await tester.pumpAndSettle(); +} + +/// Puts focus on a sidebar control, outside every text field. +Future _focusSidebar(WidgetTester tester) async { + final icon = find + .descendant(of: _actions('a'), matching: find.byType(Icon)) + .first; + Focus.of(tester.element(icon)).requestFocus(); + await tester.pumpAndSettle(); +} + +Future _slash(WidgetTester tester) async { + final handled = await tester.sendKeyEvent(LogicalKeyboardKey.slash); + await tester.pumpAndSettle(); + return handled; +} + +Future _controlTab(WidgetTester tester, {bool shift = false}) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + if (shift) await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + if (shift) await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets('slash outside a text field focuses the composer, untyped', ( + tester, + ) async { + await _setup(tester); + await _openRow(tester, 'a'); + await _focusSidebar(tester); + expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isFalse); + + expect(await _slash(tester), isTrue); + expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isTrue); + expect(_editable(tester, 'a').controller.text, isEmpty); + + // Inside the composer a slash is an ordinary character for the field. + expect(await _slash(tester), isFalse); + expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isTrue); + + // Shift+/ (a question mark) and Alt+/ are not the shortcut; Ctrl+/ is + // the shell's own Search chord. + await _focusSidebar(tester); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.slash, character: '?'); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.slash); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pumpAndSettle(); + expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isFalse); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('slash leaves a dialog text field and a popup alone', ( + tester, + ) async { + await _setup(tester); + await _openRow(tester, 'a'); + await tester.tap(_actions('a')); + await tester.pumpAndSettle(); + expect(await _slash(tester), isFalse); + expect(find.text('Rename…'), findsOneWidget); + await tester.tap(find.text('Rename…')); + await tester.pumpAndSettle(); + final dialogField = find.descendant( + of: find.byType(Dialog), + matching: find.byType(EditableText), + ); + expect(dialogField, findsOneWidget); + await tester.tap(dialogField); + await tester.pumpAndSettle(); + expect(await _slash(tester), isFalse); + expect(find.byType(Dialog), findsOneWidget); + expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isFalse); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('Control Tab over one pane returns to the previous chat', ( + tester, + ) async { + await _setup(tester); + await _openRow(tester, 'a'); + final workspace = _workspace(tester); + // Nothing shown before: the chord only focuses the composer. + await _controlTab(tester); + expect(workspace.activePane?.sessionId, 'a'); + expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isTrue); + + await _openRow(tester, 'b'); + await tester.enterText(_input('b'), 'Draft B'); + await _focusSidebar(tester); + for (final id in ['a', 'b', 'a']) { + await _controlTab(tester); + expect(workspace.paneCount, 1); + expect(workspace.activePane?.sessionId, id); + expect(_editable(tester, id).focusNode.hasPrimaryFocus, isTrue); + } + await _controlTab(tester, shift: true); + expect(workspace.activePane?.sessionId, 'b'); + expect(_editable(tester, 'b').controller.text, 'Draft B'); + + // A third chat makes the pair c and b; a is no longer one step away. + await _openRow(tester, 'c'); + await _controlTab(tester); + expect(workspace.activePane?.sessionId, 'b'); + await _controlTab(tester); + expect(workspace.activePane?.sessionId, 'c'); + + // Two panes cycle the panes as before, not the history. + await tester.tap(_actions('a')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Open to the right')); + await tester.pumpAndSettle(); + expect(workspace.paneCount, 2); + expect(workspace.activePane?.sessionId, 'a'); + await _controlTab(tester); + expect(workspace.activePane?.sessionId, 'c'); + await _controlTab(tester); + expect(workspace.activePane?.sessionId, 'a'); + expect(workspace.paneCount, 2); + await tester.pumpWidget(const SizedBox.shrink()); + }); +}