Add global shortcuts for opening Chat

Allow Ctrl+K and Alt+K to switch to Chat from any destination, while preserving terminal Ctrl+K behavior and focusing the active composer. Register the shortcuts in help and cover matching, navigation, terminal handling, and composer focus with regression tests.
This commit is contained in:
2026-11-12 01:08:18 +00:00
parent 4f1b45571f
commit ac5f28bb83
8 changed files with 389 additions and 1 deletions
+8
View File
@@ -689,6 +689,13 @@ class _PipelinesAppState extends State<PipelinesApp>
AppRoute? _chatWorkspaceRoute;
Set<String>? _availableChatSessionIds;
/// After Ctrl+K or Alt+K shows Chat: the keyboard goes to the open chat's
/// composer, if a chat is open.
void _focusOpenChatComposer() {
final id = _chatWorkspaceRoute?.chatSessionId;
if (id != null) _chatRuntime.composerFocus.request(id);
}
void _selectDestination(AppDestination destination) {
final current = tabForRoute(_delegate.route);
final last = _tabRoutes[destination];
@@ -825,6 +832,7 @@ class _PipelinesAppState extends State<PipelinesApp>
runningRunCount: counts.running,
destination: _destinationOf(route.kind),
onDestinationSelected: _selectDestination,
onOpenChat: _focusOpenChatComposer,
onClosePage: () => _delegate.goTo(
_bodyRoutes[AppDestination.pipelines] ?? AppRoute.pipelines,
),
@@ -4,6 +4,7 @@ import '../chat/workspace/chat_center_stage_controller.dart';
import '../chat/workspace/chat_float_shortcut.dart';
import '../terminal/terminal_shortcuts.dart';
import '../../shell/windows/window_shortcuts.dart';
import '../../shell/shell_chat_shortcut.dart';
import '../../shell/shell_search_shortcut_labels.dart';
/// A shortcut entry shown in the in-app help. Keeping these entries together
@@ -53,6 +54,13 @@ class KeyboardShortcutRegistry {
caveat:
'Brings a chat forward from Terminal and focuses its message input.',
),
KeyboardShortcutEntry(
action: 'Open Chat',
keys: shellChatShortcutLabels(platform).join(', '),
caveat: web
? 'Shows the open chat and focuses its message input. The browser may reserve Ctrl+K.'
: 'Shows the open chat and focuses its message input. In the terminal Ctrl+K stays kill-line; Alt+K still opens Chat.',
),
KeyboardShortcutEntry(
action: 'Toggle Center Stage',
keys:
+21 -1
View File
@@ -9,6 +9,7 @@ import 'destination.dart';
import 'list_detail.dart';
import 'list_pane_widths.dart';
import 'shell_bar.dart';
import 'shell_chat_shortcut.dart';
import 'shell_list_shortcuts.dart';
import 'shell_search_shortcut_labels.dart';
import 'tab_history.dart';
@@ -22,6 +23,7 @@ class AdaptiveShell extends StatefulWidget {
this.onDestinationSelected,
this.onClosePage,
this.onSearch,
this.onOpenChat,
this.attentionCount = 0,
this.runningRunCount,
this.listPaneWidthStore = const SharedPreferencesListPaneWidthStore(),
@@ -47,6 +49,10 @@ class AdaptiveShell extends StatefulWidget {
/// shell tests and compositions without routing keep their tab set only.
final VoidCallback? onSearch;
/// Runs after Ctrl+K or Alt+K has shown the Chat destination (also when it
/// was already shown), so the open chat's composer can take the keyboard.
final VoidCallback? onOpenChat;
/// Runs needing the operator today, retained in the tab's accessible label.
final int attentionCount;
@@ -271,9 +277,16 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
/// fields. Split-pane navigation belongs to the chat workspace; tab changes
/// have no global keyboard chord.
bool _handleDestinationKeyEvent(KeyEvent event) {
final keyboard = HardwareKeyboard.instance;
// Ctrl+K is the terminal's kill-line while the terminal has the keyboard;
// Alt+K still opens Chat there.
if (shellChatShortcut(event, keyboard) &&
(keyboard.isAltPressed || !primaryFocusIsTypingSurface())) {
if (event is KeyDownEvent) _openChat();
return true;
}
// A terminal keeps its keys (Escape, Ctrl+/, Ctrl+digits).
if (primaryFocusIsTypingSurface()) return false;
final keyboard = HardwareKeyboard.instance;
if (_selected == AppDestination.search &&
event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.escape &&
@@ -299,6 +312,13 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
return _bar.lists.open(AppDestination.chat, listIndex);
}
/// Shows Chat (the tab's own selection, so its open chat returns) and then
/// lets the app focus that chat's composer.
void _openChat() {
if (_selected != AppDestination.chat) _select(AppDestination.chat);
widget.onOpenChat?.call();
}
/// A popup or nested viewer owns Escape before the underlying Search tab.
bool _searchEscape() {
final route = ModalRoute.of(context);
+29
View File
@@ -0,0 +1,29 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
/// Whether [event] opens the Chat destination from any destination: Ctrl+K,
/// or Alt+K (Option+K on Apple platforms). Alt+K is recognised by key position
/// too, because Option+K yields a dead-key symbol on a Mac. Shift, Cmd and
/// chords with both Ctrl and Alt are not the shortcut. Repeats of a held chord
/// match as well, so the caller can swallow them; only its first press acts.
bool shellChatShortcut(KeyEvent event, HardwareKeyboard keyboard) {
if (event is KeyUpEvent ||
keyboard.isShiftPressed ||
keyboard.isMetaPressed) {
return false;
}
final control = keyboard.isControlPressed;
final alt = keyboard.isAltPressed;
if (control == alt) return false;
if (event.logicalKey == LogicalKeyboardKey.keyK) return true;
return alt && event.physicalKey == PhysicalKeyboardKey.keyK;
}
/// The chords that open Chat as they read on this platform, for the help
/// page. Alt (Option on Apple platforms) leads, as it does for the floating
/// chats; Ctrl+K is the other chord everywhere.
List<String> shellChatShortcutLabels([TargetPlatform? platform]) {
final target = platform ?? defaultTargetPlatform;
final apple = target == TargetPlatform.macOS || target == TargetPlatform.iOS;
return [apple ? 'Option+K' : 'Alt+K', 'Ctrl+K'];
}
+32
View File
@@ -0,0 +1,32 @@
# Ctrl+K / Alt+K open Chat
Run 391 (ctrl-k-and-alt-k-open-chat), stage 01-implement. Not committed.
## Behaviour
- Ctrl+K, or Alt+K (Option+K on Apple platforms, matched by physical key so the dead-key symbol still counts), switches the shell to the Chat destination from any destination, then calls `AdaptiveShell.onOpenChat`.
- The app passes `_focusOpenChatComposer`, which requests the composer of the last workspace chat (`_chatWorkspaceRoute`) through `ChatRuntime.composerFocus`.
- Ctrl+K is left to the terminal while the terminal has the keyboard (`primaryFocusIsTypingSurface`). Alt+K still switches there.
- Shift, Meta, or Ctrl+Alt together do not match. Repeats are swallowed; only the first key-down acts.
- The help page has an "Open Chat" entry: `Option+K, Ctrl+K` on macOS, `Alt+K, Ctrl+K` elsewhere.
## Changed paths
- `app/lib/shell/shell_chat_shortcut.dart` (new): `shellChatShortcut`, `shellChatShortcutLabels`.
- `app/lib/shell/adaptive_shell.dart`: key handling, `_openChat`, `onOpenChat` parameter.
- `app/lib/application/pipelines_app.dart`: `_focusOpenChatComposer`, wired as `onOpenChat`.
- `app/lib/features/settings/keyboard_shortcuts_registry.dart`: "Open Chat" entry.
- `app/test/shell/shell_chat_shortcut_test.dart` (new): matcher, switch from another destination, controlled shell callback, terminal exception.
- `app/test/application/chat_open_shortcut_test.dart` (new): the full `PipelinesApp` opens `/chat/s1`, moves to Runs, then Alt+K and Ctrl+K each return to `/chat/s1` and put the keyboard in the `s1` composer (primary focus).
- `app/test/features/settings/keyboard_shortcuts_help_test.dart`: "Open Chat" help entry test.
## Focused results
- Review follow-up (composer focus), `tool/memwatch/full.sh 'test/application/chat_open_shortcut_test.dart test/shell/shell_chat_shortcut_test.dart test/features/settings/keyboard_shortcuts_help_test.dart'`: PASS, 12 passed, 0 failed, peak 1306 MB, 5s, exit 0. Run after `dart format` on the new test.
- Mutation check: with the `_focusOpenChatComposer` request removed from `pipelines_app.dart`, `chat_open_shortcut_test.dart` fails on the composer focus expectation. The source was restored afterwards; `git diff` shows the original wiring.
- Earlier stage run (not repeated here): `test/shell/destination_shortcuts_test.dart`, `test/shell/search_shortcuts_test.dart`, `test/features/chat/workspace/chat_float_shortcut_test.dart` passed with the shell test and help test (21 passed, 0 failed, peak 1062 MB).
- `tool/analyze.sh`: clean.
- Tests that press K chords: none outside the new files. The new shell check returns false for every other key, so the earlier typing-surface and search paths keep their order.
## Not covered
- The composer-focus test drives the real app with a fake channel; it does not cover a chat opened only through a route with no history yet.
- No UI capture or device run (ui-review owns that).
- Ctrl+Y: the float chord is not left to the terminal. `chatFloatShortcut` matches Ctrl+Y on every platform, and `chat_floating_pane_test.dart` covers Ctrl+Y from the terminal on macOS. Ctrl+K was made the only terminal exception, as the task asked.
- On web, the browser may keep Ctrl+K (address/search focus); the help caveat says so.
@@ -0,0 +1,93 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/application/pipelines_app.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import '../core/transport/pipelines_client_test.dart' show FakeChannel;
import 'chat_registration_test.dart'
show replyHistory, replySessions, replySubscribe, webServer;
bool _composerFocused(WidgetTester tester, String id) => tester
.widget<EditableText>(
find.descendant(
of: find.byKey(ValueKey('chat-composer-$id')),
matching: find.byType(EditableText),
),
)
.focusNode
.hasPrimaryFocus;
Future<void> _chord(WidgetTester tester, LogicalKeyboardKey modifier) async {
await tester.sendKeyDownEvent(modifier);
await tester.sendKeyEvent(LogicalKeyboardKey.keyK);
await tester.sendKeyUpEvent(modifier);
await tester.pump();
await tester.pump();
}
void main() {
testWidgets(
'Ctrl+K and Alt+K from another destination focus the open chat composer',
(tester) async {
tester.view.physicalSize = const Size(900, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/chat/s1')),
);
addTearDown(provider.dispose);
await tester.pumpWidget(
PipelinesApp(
androidSupported: false,
server: webServer(),
client: client,
routeInformationProvider: provider,
),
);
await tester.pump();
await replySessions(tester, channel);
await replySubscribe(tester, channel);
await replyHistory(tester, channel);
await tester.pumpAndSettle();
expect(find.byType(ChatThreadView), findsOneWidget);
expect(_composerFocused(tester, 's1'), isFalse);
// Leave Chat for another destination, then clear any focus left over.
await tester.tap(find.byKey(const ValueKey('shell.destination.runs')));
await tester.pump(const Duration(milliseconds: 600));
FocusManager.instance.primaryFocus?.unfocus();
await tester.pump();
expect(provider.value.uri.path, '/runs');
await _chord(tester, LogicalKeyboardKey.altLeft);
expect(provider.value.uri.path, '/chat/s1');
expect(find.byType(ChatThreadView), findsOneWidget);
expect(_composerFocused(tester, 's1'), isTrue);
expect(tester.takeException(), isNull);
// Ctrl+K does the same from another destination.
await tester.tap(find.byKey(const ValueKey('shell.destination.runs')));
await tester.pump(const Duration(milliseconds: 600));
FocusManager.instance.primaryFocus?.unfocus();
await tester.pump();
expect(_composerFocused(tester, 's1'), isFalse);
await _chord(tester, LogicalKeyboardKey.controlLeft);
expect(provider.value.uri.path, '/chat/s1');
expect(find.byType(ChatThreadView), findsOneWidget);
expect(_composerFocused(tester, 's1'), isTrue);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
},
);
}
@@ -23,6 +23,23 @@ void main() {
expect(search.caveat, contains('browser'));
});
test(
'Open Chat lists Option+K or Alt+K with Ctrl+K and the terminal rule',
() {
KeyboardShortcutEntry openChat(TargetPlatform platform) =>
KeyboardShortcutRegistry(
platform: platform,
web: false,
).entries.firstWhere((entry) => entry.action == 'Open Chat');
expect(openChat(TargetPlatform.macOS).keys, 'Option+K, Ctrl+K');
final linux = openChat(TargetPlatform.linux);
expect(linux.keys, 'Alt+K, Ctrl+K');
expect(linux.caveat, contains('kill-line'));
expect(openChat(TargetPlatform.windows).keys, 'Alt+K, Ctrl+K');
},
);
test('uses the shell primary modifier rule on iOS', () {
final entries = const KeyboardShortcutRegistry(
platform: TargetPlatform.iOS,
@@ -0,0 +1,181 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/shell/adaptive_shell.dart';
import 'package:pipelines_app/shell/destination.dart';
import 'package:pipelines_app/shell/shell_chat_shortcut.dart';
import 'package:pipelines_app/ui/input/keyboard_owner.dart';
const _k = KeyDownEvent(
physicalKey: PhysicalKeyboardKey.keyK,
logicalKey: LogicalKeyboardKey.keyK,
timeStamp: Duration.zero,
);
void main() {
test('Ctrl+K and Alt+K open Chat; other modifiers and plain K do not', () {
bool chord(Set<LogicalKeyboardKey> held, [KeyEvent event = _k]) =>
shellChatShortcut(event, _FakeKeyboard(held));
expect(chord({}), isFalse);
expect(chord({LogicalKeyboardKey.controlLeft}), isTrue);
expect(chord({LogicalKeyboardKey.altLeft}), isTrue);
expect(
chord({LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.altLeft}),
isFalse,
);
expect(
chord({LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.shiftLeft}),
isFalse,
);
expect(chord({LogicalKeyboardKey.metaLeft}), isFalse);
expect(
chord({LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.metaLeft}),
isFalse,
);
expect(
shellChatShortcut(
const KeyUpEvent(
physicalKey: PhysicalKeyboardKey.keyK,
logicalKey: LogicalKeyboardKey.keyK,
timeStamp: Duration.zero,
),
_FakeKeyboard({LogicalKeyboardKey.controlLeft}),
),
isFalse,
);
});
test('Option+K matches by key position though it types a symbol', () {
// On a Mac, Option+K produces ˚: the logical key is not K.
const ring = KeyDownEvent(
physicalKey: PhysicalKeyboardKey.keyK,
logicalKey: LogicalKeyboardKey(0x02da),
character: '˚',
timeStamp: Duration.zero,
);
expect(
shellChatShortcut(ring, _FakeKeyboard({LogicalKeyboardKey.altLeft})),
isTrue,
);
// Without Alt the same symbol is ordinary typing.
expect(shellChatShortcut(ring, _FakeKeyboard({})), isFalse);
});
test('labels name the Option chord on Apple platforms', () {
expect(shellChatShortcutLabels(TargetPlatform.linux), ['Alt+K', 'Ctrl+K']);
expect(shellChatShortcutLabels(TargetPlatform.macOS), [
'Option+K',
'Ctrl+K',
]);
});
testWidgets('Ctrl+K and Alt+K show Chat from another destination', (
tester,
) async {
var opened = 0;
await tester.pumpWidget(
MaterialApp(
home: AdaptiveShell(
destinationBodies: {
for (final destination in shellTabDestinations)
destination: (_) => Text('${destination.name} body'),
},
onOpenChat: () => opened++,
),
),
);
expect(find.text('pipelines body'), isOnstage);
// Chat is built on its first visit only.
expect(find.text('chat body'), findsNothing);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyK);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
// The outgoing tab fades out while still mounted, so Chat being built
// and onstage is the switch.
expect(find.text('chat body'), isOnstage);
expect(opened, 1);
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyK);
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
expect(find.text('chat body'), isOnstage);
// Already in Chat, the chord still hands the keyboard to the composer.
expect(opened, 2);
expect(tester.takeException(), isNull);
});
testWidgets('a controlled shell reports the switch to Chat', (tester) async {
final selected = <AppDestination>[];
await tester.pumpWidget(
MaterialApp(
home: AdaptiveShell(
destination: AppDestination.runs,
onDestinationSelected: selected.add,
destinationBodies: {
for (final destination in shellTabDestinations)
destination: (_) => Text('${destination.name} body'),
},
),
),
);
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyK);
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
expect(selected, [AppDestination.chat]);
});
testWidgets(
'terminal keeps Ctrl+K for kill-line but Alt+K still opens Chat',
(tester) async {
final terminal = FocusNode();
addTearDown(terminal.dispose);
var opened = 0;
await tester.pumpWidget(
MaterialApp(
home: AdaptiveShell(
onOpenChat: () => opened++,
destinationBodies: {
AppDestination.pipelines: (_) => TypingSurface(
child: Focus(
focusNode: terminal,
child: const Text('terminal'),
),
),
AppDestination.chat: (_) => const Text('chat body'),
},
),
),
);
terminal.requestFocus();
await tester.pump();
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyK);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(find.text('chat body'), findsNothing);
expect(find.text('terminal'), isOnstage);
expect(opened, 0);
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyK);
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
await tester.pump();
expect(find.text('chat body'), isOnstage);
expect(opened, 1);
expect(tester.takeException(), isNull);
},
);
}
class _FakeKeyboard extends HardwareKeyboard {
_FakeKeyboard(this.pressed);
final Set<LogicalKeyboardKey> pressed;
@override
bool isLogicalKeyPressed(LogicalKeyboardKey key) => pressed.contains(key);
}