Chat: Ctrl+K / Alt+K on Chat opens a quick switcher for the open chats

On Chat the chord now toggles a centred dialog (bottom sheet on a phone)
with an autofocused filter over the open chats in list order; Ctrl+N/Down
and Ctrl+P/Up move the wrapping selection, Enter opens the chat as Ctrl+Tab
does (pane reused, composer focused), Esc or the chord closes it. From other
destinations the chord still jumps to Chat. Ctrl+N/Ctrl+P are handled so the
web page prevents their defaults (Ctrl+P no longer prints); a browser tab
keeps Ctrl+N reserved, documented in the help and notes/chat-quick-switch.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-02 12:27:39 +00:00
parent 26b1c00094
commit 141661e355
17 changed files with 1127 additions and 4 deletions
+7
View File
@@ -810,6 +810,12 @@ class _PipelinesAppState extends State<PipelinesApp>
if (id != null) _chatRuntime.composerFocus.request(id);
}
/// Ctrl+K / Alt+K on Chat: the mounted chat screen's quick switcher, or
/// the open chat's composer while no chat screen is mounted to show it.
void _toggleChatQuickSwitch() {
if (!_chatRuntime.quickSwitch.toggle()) _focusOpenChatComposer();
}
void _selectDestination(AppDestination destination) {
// Settings is shown from its own nav item and has no Back, so its route
// (filed under the Pipelines tab) must not trap the Pipelines item: that
@@ -1029,6 +1035,7 @@ class _PipelinesAppState extends State<PipelinesApp>
onDestinationSelected: _selectDestination,
onDestinationReselected: _reselectDestination,
onOpenChat: _focusOpenChatComposer,
onChatQuickSwitch: _toggleChatQuickSwitch,
destinationBodies: {
AppDestination.pipelines: (_) => FirstRunWalkthroughGate(
store: _walkthroughStore,
+4
View File
@@ -11,6 +11,7 @@ import 'conversation/chat_row_widgets.dart';
import 'conversation/chat_scroll.dart';
import 'conversation/chat_transcript_cache.dart';
import 'conversation/chat_composer_controller.dart';
import 'conversation/chat_quick_switch_requests.dart';
import 'conversation/composer_focus_request.dart';
import 'data/chat_repository.dart';
import 'ui/sessions/chat_sessions_body.dart';
@@ -128,6 +129,9 @@ class ChatRuntime extends ChangeNotifier {
/// Puts the keyboard in an opened chat's composer once it is built.
final ChatComposerFocusRequests composerFocus = ChatComposerFocusRequests();
/// The Chat destination's quick switcher, toggled by Ctrl+K / Alt+K there.
final ChatQuickSwitchRequests quickSwitch = ChatQuickSwitchRequests();
/// Mounted composers are registered so external actions can append without
/// sending. A selection made before a pane mounts is queued here.
final Map<String, ChatComposerController> composers = {};
@@ -0,0 +1,58 @@
part of 'screen.dart';
/// The quick switcher Ctrl+K / Alt+K (Cmd+K on a Mac) shows when pressed on
/// the Chat destination: the open chats to jump to, filtered as the operator
/// types (see [showChatQuickSwitch]). Pressing the shortcut again closes it.
/// A chosen chat opens as a keyboard choice from the list does: its pane is
/// reused when it is already open, and its composer takes the keyboard.
mixin _ChatScreenQuickSwitch on State<ChatScreen>, _ChatScreenWorkspace {
ChatRuntime get _runtime;
ModalRoute<JsonMap>? _quickSwitchRoute;
void _bindQuickSwitch() => _runtime.quickSwitch.attach(_toggleQuickSwitch);
void _unbindQuickSwitch() {
_runtime.quickSwitch.detach(_toggleQuickSwitch);
final open = _quickSwitchRoute;
_quickSwitchRoute = null;
// The navigator is locked while this screen is torn down; close after.
if (open != null) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => closeChatQuickSwitch(open),
);
}
}
void _toggleQuickSwitch() {
final open = _quickSwitchRoute;
if (open != null && open.isActive) {
_quickSwitchRoute = null;
closeChatQuickSwitch(open);
return;
}
// Another popup or dialog over the chat keeps the keyboard.
if (!mounted || !_chatOwnsKeyboard()) return;
final route = showChatQuickSwitch(
context,
sessions: _runtime.sessions,
serverName: _quickSwitchServerName,
onSelected: (row) {
if (mounted) _openByShortcut(row);
},
);
_quickSwitchRoute = route;
route.popped.whenComplete(() {
if (identical(_quickSwitchRoute, route)) _quickSwitchRoute = null;
});
}
/// The machine a federated row is on, as the list names it.
String? _quickSwitchServerName(JsonMap row) {
final id = '${row['_server_id'] ?? ''}';
final named = mounted && id.isNotEmpty
? ServerContext.nameFor(context, id)
: null;
return named ?? row['_server_name'] as String?;
}
}
@@ -0,0 +1,221 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/app_popups.dart';
import '../domain/chat_quick_switch.dart';
import '../ui/sessions/chat_sessions_controller.dart';
import 'chat_quick_switch_keys.dart';
import 'chat_quick_switch_row.dart';
/// Shows the chat quick switcher over the Chat destination: a search field
/// with the keyboard in it above the open chats ([chatQuickSwitchCandidates]),
/// narrowed and ranked as the operator types ([chatQuickSwitchMatches]). The
/// first match is selected; Ctrl+N / Ctrl+P and Down / Up move the selection,
/// wrapping, and Enter or a click chooses it. Esc closes it.
///
/// A centred dialog on a wide app, a full-width bottom sheet on a phone, on
/// the root navigator either way. Returns the route so a second press of the
/// shortcut can close it; [onSelected] gets the chosen row once it closed.
ModalRoute<JsonMap> showChatQuickSwitch(
BuildContext context, {
required ChatSessionsController sessions,
required ValueChanged<JsonMap> onSelected,
String? Function(JsonMap session)? serverName,
}) {
final navigator = Navigator.of(context, rootNavigator: true);
Widget content(BuildContext context) =>
ChatQuickSwitch(sessions: sessions, serverName: serverName);
final ModalRoute<JsonMap> route = usesDesktopPopups(context)
? DialogRoute<JsonMap>(
context: context,
themes: InheritedTheme.capture(from: context, to: navigator.context),
barrierLabel: 'Close the chat switcher',
builder: (context) => Dialog(
alignment: const Alignment(0, -0.6),
clipBehavior: Clip.antiAlias,
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: 560,
maxHeight: MediaQuery.sizeOf(context).height * 0.7,
),
child: content(context),
),
),
)
: ModalBottomSheetRoute<JsonMap>(
builder: content,
isScrollControlled: true,
showDragHandle: true,
useSafeArea: true,
capturedThemes: InheritedTheme.capture(
from: context,
to: navigator.context,
),
barrierLabel: 'Close the chat switcher',
modalBarrierColor: Theme.of(
context,
).bottomSheetTheme.modalBarrierColor,
);
navigator.push(route).then((row) {
if (row != null) onSelected(row);
});
return route;
}
/// Closes a quick switcher [showChatQuickSwitch] opened, if it is still open.
void closeChatQuickSwitch(ModalRoute<JsonMap> route) {
final navigator = route.navigator;
if (navigator == null || !route.isActive) return;
if (route.isCurrent) {
navigator.pop();
} else {
navigator.removeRoute(route);
}
}
/// The switcher's content: the field and the matching chats.
class ChatQuickSwitch extends StatefulWidget {
const ChatQuickSwitch({super.key, required this.sessions, this.serverName});
final ChatSessionsController sessions;
final String? Function(JsonMap session)? serverName;
@override
State<ChatQuickSwitch> createState() => _ChatQuickSwitchState();
}
class _ChatQuickSwitchState extends State<ChatQuickSwitch> {
final _query = TextEditingController();
final _rowKeys = <String, GlobalKey>{};
int _selected = 0;
List<JsonMap> _shown = const [];
@override
void dispose() {
_query.dispose();
super.dispose();
}
void _queryChanged(String _) => setState(() => _selected = 0);
/// Moves the selection [step] rows, wrapping, and scrolls it into view at
/// the edge it moved towards.
void _step(int step) {
if (_shown.isEmpty) return;
final from = _selected.clamp(0, _shown.length - 1);
final index = (from + step) % _shown.length;
setState(() => _selected = index);
final id = '${_shown[index]['id'] ?? ''}';
final policy = step < 0
? ScrollPositionAlignmentPolicy.keepVisibleAtStart
: ScrollPositionAlignmentPolicy.keepVisibleAtEnd;
WidgetsBinding.instance.addPostFrameCallback((_) {
final row = _rowKeys[id]?.currentContext;
if (row != null) Scrollable.ensureVisible(row, alignmentPolicy: policy);
});
}
void _choose([JsonMap? row]) {
final chosen =
row ??
(_shown.isEmpty ? null : _shown[_selected.clamp(0, _shown.length - 1)]);
if (chosen != null) Navigator.of(context).pop(chosen);
}
@override
Widget build(BuildContext context) {
final field = Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: (_, event) => chatQuickSwitchKey(
event,
HardwareKeyboard.instance,
onStep: _step,
onChoose: _choose,
),
child: TextField(
key: const Key('chat-quick-switch-field'),
controller: _query,
autofocus: true,
onChanged: _queryChanged,
textInputAction: TextInputAction.go,
decoration: const InputDecoration(
hintText: 'Switch to a chat',
prefixIcon: Icon(Icons.search),
border: OutlineInputBorder(),
isDense: true,
),
),
),
);
final list = ListenableBuilder(
listenable: widget.sessions,
builder: (context, _) {
_shown = chatQuickSwitchMatches(
chatQuickSwitchCandidates(widget.sessions.sessions),
_query.text,
serverName: widget.serverName,
);
if (_shown.isEmpty) {
return Padding(
padding: const EdgeInsets.all(24),
child: Text(
widget.sessions.loading && widget.sessions.sessions.isEmpty
? 'Loading chats…'
: _query.text.trim().isEmpty
? 'No open chats.'
: 'No chats match.',
key: const Key('chat-quick-switch-empty'),
textAlign: TextAlign.center,
),
);
}
final selected = _selected.clamp(0, _shown.length - 1);
// Every row is built (open chats are few), so a wrap from the last
// row to the first can scroll to it.
return SingleChildScrollView(
padding: const EdgeInsets.only(bottom: 8),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final (index, row) in _shown.indexed)
ChatQuickSwitchRow(
key: _rowKeys.putIfAbsent(
'${row['id'] ?? ''}',
GlobalKey.new,
),
session: row,
serverName: widget.serverName?.call(row),
selected: index == selected,
onTap: () => _choose(row),
),
],
),
);
},
);
return Semantics(
label: 'Switch chat',
explicitChildNodes: true,
child: Material(
type: MaterialType.transparency,
child: Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.viewInsetsOf(context).bottom,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
field,
Flexible(child: list),
],
),
),
),
);
}
}
@@ -0,0 +1,49 @@
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
/// The chat quick switcher's keys, read while its field has the keyboard:
/// Ctrl+N and Down step the selection forward ([onStep] with 1), Ctrl+P and
/// Up back (-1), and Enter chooses it ([onChoose]). Control rather than Cmd
/// on Apple platforms too, as in Search and Emacs-style lists.
///
/// The chords are reported handled, also with nothing to select, so a
/// browser does not run its own default (Ctrl+P prints). A browser tab may
/// still keep Ctrl+N for itself (a new window) before the page sees it; Up
/// and Down always work, and an installed app window or the terminal's
/// "Capture browser keys" full screen passes Ctrl+N through.
KeyEventResult chatQuickSwitchKey(
KeyEvent event,
HardwareKeyboard keyboard, {
required ValueChanged<int> onStep,
required VoidCallback onChoose,
}) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
if (keyboard.isAltPressed || keyboard.isMetaPressed) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
final control = keyboard.isControlPressed;
final shift = keyboard.isShiftPressed;
final step = switch (key) {
LogicalKeyboardKey.keyN when control && !shift => 1,
LogicalKeyboardKey.keyP when control && !shift => -1,
LogicalKeyboardKey.arrowDown when !control && !shift => 1,
LogicalKeyboardKey.arrowUp when !control && !shift => -1,
_ => 0,
};
if (step != 0) {
onStep(step);
return KeyEventResult.handled;
}
if (event is KeyDownEvent &&
!control &&
!shift &&
(key == LogicalKeyboardKey.enter ||
key == LogicalKeyboardKey.numpadEnter)) {
onChoose();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@@ -0,0 +1,24 @@
import 'package:flutter/foundation.dart';
/// Where Ctrl+K / Alt+K pressed on the Chat destination goes: the mounted
/// chat screen attaches its quick switcher here, and the app toggles it.
class ChatQuickSwitchRequests {
VoidCallback? _toggle;
/// Makes [toggle] the switcher; the last attached one wins.
void attach(VoidCallback toggle) => _toggle = toggle;
/// Detaches [toggle] if it is still the attached one.
void detach(VoidCallback toggle) {
if (_toggle == toggle) _toggle = null;
}
/// Opens the switcher, or closes it when open. False when no chat screen
/// is mounted to show it.
bool toggle() {
final toggle = _toggle;
if (toggle == null) return false;
toggle();
return true;
}
}
@@ -0,0 +1,62 @@
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/chat_list_activity.dart';
import '../domain/chat_sessions.dart';
import '../ui/sessions/session_row_content.dart';
import '../ui/sessions/session_row_style.dart';
/// One chat in the quick switcher: the list's avatar (harness mark in the
/// chat's colour, with its running or awaiting badge), the title, and the
/// folder with the machine it is on. The selected row takes the selection
/// fill; hover and click work as on any list tile.
class ChatQuickSwitchRow extends StatelessWidget {
const ChatQuickSwitchRow({
super.key,
required this.session,
required this.selected,
required this.onTap,
this.serverName,
});
final JsonMap session;
final bool selected;
final VoidCallback onTap;
final String? serverName;
@override
Widget build(BuildContext context) {
final id = '${session['id'] ?? ''}';
final scheme = Theme.of(context).colorScheme;
final running = session['running'] == true;
final subtitle = [
homeRelativePath('${session['directory'] ?? ''}'.trim()),
?serverName,
].where((part) => part.isNotEmpty).join(' · ');
return ListTile(
key: Key('chat-quick-switch-row-$id'),
selected: selected,
selectedTileColor: scheme.secondaryContainer,
selectedColor: scheme.onSecondaryContainer,
visualDensity: VisualDensity.compact,
leading: ChatSessionAvatar(
session: session,
running: running,
backgroundTasks: running ? 0 : chatSessionBackgroundTasks(session),
awaitingOperator: chatSessionAwaitingOperator(session),
),
title: Text(
chatSessionTitle(session),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
subtitle: subtitle.isEmpty
? null
: Text(subtitle, maxLines: 1, overflow: TextOverflow.ellipsis),
trailing: session['starred'] == true
? Icon(Icons.star, color: scheme.primary, semanticLabel: 'Starred')
: null,
onTap: onTap,
);
}
}
@@ -0,0 +1,85 @@
import '../../../core/api_gateway.dart';
import 'chat_sessions.dart';
/// The chats the quick switcher (Ctrl+K on the Chat destination) offers with
/// no query: every open chat in the order the list draws them, starred first
/// (by name), then Chats by directory in server recency. Closed chats are left
/// out, and a folded section does not hide its rows here.
List<JsonMap> chatQuickSwitchCandidates(List<JsonMap> sessions) =>
chatSessionsInListOrder(
chatSessionSections(
sessions
.where((row) => row['closed_at'] == null && row['closed'] != true)
.toList(),
),
isOpen: (_) => true,
);
/// The harness a row runs, as the list's icon reads it (an unnamed one is
/// OpenCode).
String chatQuickSwitchHarness(JsonMap session) {
final backend = '${session['backend'] ?? ''}'.trim();
return backend.isEmpty ? 'opencode' : backend;
}
/// [candidates] narrowed to [query] and ranked, best first.
///
/// Every whitespace-separated word of the query must occur, ignoring case, in
/// the chat's title, directory, workspace, harness or machine name
/// ([serverName]; federated rows name their machine there). A word ranks by
/// where it matched, best first: the start of the title, the start of a word
/// in the title, the start of a word in the other fields, anywhere in the
/// title, anywhere else. A chat's rank is the sum over the query's words, and
/// equal ranks keep [candidates]' order.
List<JsonMap> chatQuickSwitchMatches(
List<JsonMap> candidates,
String query, {
String? Function(JsonMap session)? serverName,
}) {
final words = query.toLowerCase().split(RegExp(r'\s+'))
..removeWhere((word) => word.isEmpty);
if (words.isEmpty) return candidates;
final ranked = <({int rank, int index, JsonMap row})>[];
for (var index = 0; index < candidates.length; index++) {
final row = candidates[index];
final title = chatSessionTitle(row).toLowerCase();
final other = [
row['directory'],
row['workspace'],
chatQuickSwitchHarness(row),
serverName?.call(row) ?? row['_server_name'],
].where((value) => value != null).join('\u0000').toLowerCase();
var rank = 0;
for (final word in words) {
final tier = _tier(word, title, other);
if (tier == null) {
rank = -1;
break;
}
rank += tier;
}
if (rank >= 0) ranked.add((rank: rank, index: index, row: row));
}
ranked.sort((a, b) => a.rank != b.rank ? a.rank - b.rank : a.index - b.index);
return [for (final hit in ranked) hit.row];
}
int? _tier(String word, String title, String other) {
if (title.startsWith(word)) return 0;
if (_startsWord(title, word)) return 1;
if (_startsWord(other, word)) return 2;
if (title.contains(word)) return 3;
if (other.contains(word)) return 4;
return null;
}
/// Whether [word] occurs in [text] at the start of one of its words (after
/// anything that is not a letter or digit).
bool _startsWord(String text, String word) {
for (var at = text.indexOf(word); at >= 0; at = text.indexOf(word, at + 1)) {
if (at == 0 || !_alphanumeric.hasMatch(text[at - 1])) return true;
}
return false;
}
final _alphanumeric = RegExp(r'[\p{L}\p{N}]', unicode: true);
+8 -1
View File
@@ -20,6 +20,7 @@ import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import '../../core/api_gateway.dart';
import '../../core/servers/server_context.dart';
import '../../core/servers/server_scope.dart';
import '../../shell/windows/window_scope.dart';
import 'shell/chat_shell_dismiss.dart';
@@ -35,6 +36,7 @@ import 'workspace/chat_open_workspace_gateway.dart';
import 'conversation/chat_bar_tint.dart';
import 'conversation/chat_pane_picker.dart';
import 'conversation/chat_add_pane_picker.dart';
import 'conversation/chat_quick_switch_dialog.dart';
import 'conversation/chat_sidebar_controls.dart';
import 'ui/sessions/chat_compact_sidebar.dart';
import 'workspace/chat_workspace.dart';
@@ -60,6 +62,7 @@ import '../../ui/input/keyboard_owner.dart';
part 'chat_screen_float.dart';
part 'chat_screen_pane_menu.dart';
part 'chat_screen_keys.dart';
part 'chat_screen_quick_switch.dart';
part 'chat_screen_workspace.dart';
/// The Chat destination's list/detail switch.
@@ -117,9 +120,11 @@ class _ChatScreenState extends State<ChatScreen>
_ChatScreenWorkspace,
_ChatScreenKeys,
_ChatScreenFloat,
_ChatScreenPaneMenu {
_ChatScreenPaneMenu,
_ChatScreenQuickSwitch {
/// The chats' shared state: the list, opened rows, accepted models,
/// transcript positions and caches (see [ChatRuntime]).
@override
late final ChatRuntime _runtime =
widget.runtime ?? ChatRuntime(gateway: widget.gateway);
@@ -155,6 +160,7 @@ class _ChatScreenState extends State<ChatScreen>
..addListener(_runtimeChanged);
_runtime.addSessionReplacedListener(_replacedElsewhere);
_bindWindows();
_bindQuickSwitch();
final initial = widget.initialSessionId;
if (initial != null && initial.isNotEmpty) {
_workspace.open(initial);
@@ -454,6 +460,7 @@ class _ChatScreenState extends State<ChatScreen>
_workspaceBinding?.dispose();
_openWorkspace?.dispose();
_unbindWindows();
_unbindQuickSwitch();
_workspace.removeListener(_workspaceChanged);
_workspace.dispose();
_sessions.removeListener(_nextChanged);
@@ -96,8 +96,8 @@ class KeyboardShortcutRegistry {
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; ${_apple ? 'Option+K and Cmd+K still open' : 'Alt+K still opens'} Chat.',
? 'From another destination: shows the open chat and focuses its message input. On Chat it opens the chat switcher. The browser may reserve Ctrl+K.'
: 'From another destination: shows the open chat and focuses its message input. On Chat it opens the chat switcher. In the terminal Ctrl+K stays kill-line; ${_apple ? 'Option+K and Cmd+K still open' : 'Alt+K still opens'} Chat.',
),
const KeyboardShortcutEntry(
group: KeyboardShortcutGroup.navigation,
@@ -109,6 +109,13 @@ class KeyboardShortcutRegistry {
];
List<KeyboardShortcutEntry> get _chat => [
KeyboardShortcutEntry(
group: KeyboardShortcutGroup.chat,
action: 'Switch to another chat',
keys: shellChatShortcutLabels(platform).join(', '),
caveat:
'On Chat: type to filter the open chats, Ctrl+N or Down and Ctrl+P or Up to move, Enter to open, Esc or the shortcut again to close.${web ? ' A browser tab keeps Ctrl+N (new window) for itself; use Down, or the installed app.' : ''}',
),
KeyboardShortcutEntry(
group: KeyboardShortcutGroup.chat,
action: 'Focus the active chat composer',
+13 -1
View File
@@ -32,6 +32,7 @@ class AdaptiveShell extends StatefulWidget {
this.onDestinationReselected,
this.onSearch,
this.onOpenChat,
this.onChatQuickSwitch,
this.attentionCount = 0,
this.runningRunCount,
this.listPaneWidthStore = const SharedPreferencesListPaneWidthStore(),
@@ -71,6 +72,11 @@ class AdaptiveShell extends StatefulWidget {
/// was already shown), so the open chat's composer can take the keyboard.
final VoidCallback? onOpenChat;
/// Runs instead of [onOpenChat] when Ctrl+K or Alt+K is pressed while Chat
/// is already shown: the host toggles its chat quick switcher. Null keeps
/// the composer focus of [onOpenChat] there too.
final VoidCallback? onChatQuickSwitch;
/// Runs needing the operator today, retained in the tab's accessible label.
final int attentionCount;
@@ -459,8 +465,14 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
}
/// Shows Chat (the tab's own selection, so its open chat returns) and then
/// lets the app focus that chat's composer.
/// lets the app focus that chat's composer. On Chat already, the chord
/// toggles the host's chat quick switcher instead.
void _openChat() {
final quickSwitch = widget.onChatQuickSwitch;
if (_selected == AppDestination.chat && quickSwitch != null) {
quickSwitch();
return;
}
if (_selected != AppDestination.chat) _select(AppDestination.chat);
widget.onOpenChat?.call();
}
+44
View File
@@ -0,0 +1,44 @@
# Chat quick switcher (Ctrl+K / Alt+K on Chat)
Ctrl+K / Alt+K (Cmd+K / Option+K on a Mac) from another destination still
jumps to Chat and focuses the open chat's composer. On Chat it now toggles a
quick switcher: a centred dialog (full-width bottom sheet below 600 px) with
an autofocused field over the open chats.
- Wiring: `AdaptiveShell.onChatQuickSwitch` (shell, only when Chat is already
selected) -> `PipelinesApp._toggleChatQuickSwitch` ->
`ChatRuntime.quickSwitch` -> the mounted `ChatScreen`
(`lib/features/chat/chat_screen_quick_switch.dart`). A chosen chat opens
through `_openByShortcut`, the same path as Ctrl+Tab: an already-open pane
is reused (`ChatWorkspaceController.open`) and its composer takes focus.
Another popup or dialog over the chat keeps the keyboard (no switcher).
- Rows and ordering: `lib/features/chat/domain/chat_quick_switch.dart`. Empty
query = the list's order (Starred by name, then Chats by directory in server
recency), closed chats excluded, folds ignored. Query words must all match
title / directory / workspace / harness / machine name; rank per word: title
start, title word start, other word start, title substring, other substring.
- Keys (`chat_quick_switch_keys.dart`): Ctrl+N / Down, Ctrl+P / Up (wrap),
Enter, Esc. Control rather than Cmd on a Mac, as in Search.
## Browser reserved keys
Chromium `BrowserCommandController::IsReservedCommandOrKey`
(chrome/browser/ui/browser_command_controller.cc) and `kReservedCommandIds`
(chrome/browser/ui/accelerator_table.cc): IDC_NEW_WINDOW (Ctrl+N), IDC_NEW_TAB,
IDC_CLOSE_TAB, IDC_CLOSE_WINDOW, tab cycling etc. are reserved in a normal tab,
so the page never sees Ctrl+N there. IDC_PRINT is not reserved, so Ctrl+P is
cancellable. "In Apps mode, no keys are reserved" (TYPE_APP / TYPE_APP_POPUP:
the installed PWA window), and in fullscreen everything except exit/fullscreen
reaches the page; the terminal's "Capture browser keys" (Keyboard Lock in full
screen, `TerminalBrowserKeys.instance`) is page-wide, so it already covers the
switcher with no generalisation. Decision: keep Ctrl+N/Ctrl+P as asked
(handled -> Flutter web calls preventDefault), keep Up/Down as the always-working
pair, no extra Alt+N/Alt+P; the help entry says a browser tab keeps Ctrl+N.
## Evidence
`tool/capture/examples/chat-quick-switch.json` (fixture `chats=8&colors=1&activity=1`)
records keydown `defaultPrevented` through CDP: Alt+K, Ctrl+N, Ctrl+N and
Ctrl+P were all prevented in Chromium, light and dark. CDP key events bypass
the browser's own accelerators, so the reserved-key behaviour above comes from
the Chromium source, not from the capture.
@@ -0,0 +1,182 @@
import 'dart:convert';
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, replySubscribe, waitForRequest, webServer;
final _field = find.byKey(const Key('chat-quick-switch-field'));
Future<void> _replySessions(WidgetTester tester, FakeChannel channel) async {
final request = await waitForRequest(tester, channel, 'chat_sessions');
channel.incoming.add(
jsonEncode({
'id': request['id'],
'type': 'chat_sessions',
'chat_sessions': [
{'id': 's1', 'title': 'Wire chat', 'directory': '/workspace/demo'},
{'id': 's2', 'title': 'Second chat', 'directory': '/workspace/other'},
{'id': 's3', 'title': 'Third chat', 'directory': '/workspace/demo'},
],
}),
);
await tester.pump();
}
Future<FakeChannel> _mountOnChat(
WidgetTester tester,
PlatformRouteInformationProvider provider,
) async {
tester.view.physicalSize = const Size(1200, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
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);
return channel;
}
PlatformRouteInformationProvider _provider() {
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/chat/s1')),
);
addTearDown(provider.dispose);
return provider;
}
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(const Duration(milliseconds: 400));
}
bool _fieldFocused(WidgetTester tester) => tester
.widget<EditableText>(
find.descendant(of: _field, matching: find.byType(EditableText)),
)
.focusNode
.hasPrimaryFocus;
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> _teardown(WidgetTester tester) async {
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
}
void main() {
testWidgets('the chat shortcut toggles the switcher while on Chat', (
tester,
) async {
await _mountOnChat(tester, _provider());
await _chord(tester, LogicalKeyboardKey.altLeft);
expect(_field, findsOneWidget);
expect(_fieldFocused(tester), isTrue);
await _chord(tester, LogicalKeyboardKey.altLeft);
await tester.pumpAndSettle();
expect(_field, findsNothing);
await _chord(tester, LogicalKeyboardKey.controlLeft);
expect(_field, findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
expect(_field, findsNothing);
expect(tester.takeException(), isNull);
await _teardown(tester);
});
testWidgets('Enter opens the chosen chat in place, focusing its composer', (
tester,
) async {
final provider = _provider();
final channel = await _mountOnChat(tester, provider);
await _chord(tester, LogicalKeyboardKey.controlLeft);
await tester.enterText(_field, 'second');
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
await replySubscribe(tester, channel, index: 1);
await replyHistory(tester, channel, index: 1);
await tester.pumpAndSettle();
expect(_field, findsNothing);
expect(provider.value.uri.path, '/chat/s2');
// The chat replaced the open one rather than adding a pane.
expect(find.byType(ChatThreadView), findsOneWidget);
expect(_composerFocused(tester, 's2'), isTrue);
// Choosing the chat already open keeps the one pane.
await _chord(tester, LogicalKeyboardKey.controlLeft);
await tester.enterText(_field, 'second');
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(provider.value.uri.path, '/chat/s2');
expect(find.byType(ChatThreadView), findsOneWidget);
expect(_composerFocused(tester, 's2'), isTrue);
expect(tester.takeException(), isNull);
await _teardown(tester);
});
testWidgets('elsewhere the shortcut still jumps to Chat', (tester) async {
final provider = _provider();
await _mountOnChat(tester, provider);
await tester.tap(find.byKey(const ValueKey('shell.destination.runs')));
await tester.pump(const Duration(milliseconds: 600));
FocusManager.instance.primaryFocus?.unfocus();
await tester.pump();
await _chord(tester, LogicalKeyboardKey.controlLeft);
await tester.pumpAndSettle();
expect(provider.value.uri.path, '/chat/s1');
expect(_field, findsNothing);
expect(_composerFocused(tester, 's1'), isTrue);
await _teardown(tester);
});
testWidgets(
'Cmd+K toggles the switcher on Chat on a Mac',
(tester) async {
await _mountOnChat(tester, _provider());
await _chord(tester, LogicalKeyboardKey.metaLeft);
expect(_field, findsOneWidget);
expect(_fieldFocused(tester), isTrue);
await _chord(tester, LogicalKeyboardKey.metaLeft);
await tester.pumpAndSettle();
expect(_field, findsNothing);
await _teardown(tester);
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
}
@@ -0,0 +1,226 @@
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/conversation/chat_quick_switch_dialog.dart';
import 'package:pipelines_app/features/chat/data/chat_repository.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_controller.dart';
import 'package:pipelines_app/features/chat/ui/sessions/session_row_content.dart';
import '../ui/sessions/chat_test_harness.dart' show MemoryChatSessionLocalStore;
import '../ui/sessions/fake_chat_gateway.dart';
final rows = <JsonMap>[
{'id': 'one', 'title': 'Build app', 'directory': '/home/a/app'},
{
'id': 'two',
'title': 'Deploy server',
'directory': '/home/a/server',
'backend': 'codex',
'running': true,
},
{'id': 'three', 'title': 'Notes', 'directory': '/home/a/app'},
{'id': 'gone', 'title': 'Closed build', 'closed_at': 3},
];
class _Switcher {
ModalRoute<JsonMap>? route;
final chosen = <String>[];
}
Future<_Switcher> _open(
WidgetTester tester, {
Size size = const Size(900, 800),
}) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final gateway = FakeChatGateway()..sessionsReply = {'chat_sessions': rows};
final controller = ChatSessionsController(
ChatRepository(gateway),
localStore: MemoryChatSessionLocalStore(),
);
addTearDown(controller.dispose);
addTearDown(gateway.pushed.close);
await controller.refresh();
final switcher = _Switcher();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (context) => Center(
child: TextButton(
onPressed: () => switcher.route = showChatQuickSwitch(
context,
sessions: controller,
onSelected: (row) => switcher.chosen.add('${row['id']}'),
),
child: const Text('Open'),
),
),
),
),
),
);
await tester.tap(find.text('Open'));
await tester.pump(const Duration(milliseconds: 400));
return switcher;
}
List<String> _shown(WidgetTester tester) => [
for (final tile in tester.widgetList<ListTile>(
find.byWidgetPredicate(
(widget) =>
widget is ListTile &&
'${widget.key}'.contains('chat-quick-switch-row-'),
),
))
(tile.key! as ValueKey<String>).value.replaceFirst(
'chat-quick-switch-row-',
'',
),
];
String? _selected(WidgetTester tester) {
for (final id in _shown(tester)) {
final tile = tester.widget<ListTile>(
find.byKey(Key('chat-quick-switch-row-$id')),
);
if (tile.selected) return id;
}
return null;
}
Future<bool> _chord(WidgetTester tester, LogicalKeyboardKey key) async {
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
final handled = await tester.sendKeyDownEvent(key);
await tester.sendKeyUpEvent(key);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
return handled;
}
Future<void> _key(WidgetTester tester, LogicalKeyboardKey key) async {
await tester.sendKeyEvent(key);
await tester.pump();
}
void main() {
testWidgets(
'opens focused on its field with the open chats, first selected',
(tester) async {
await _open(tester);
expect(find.byType(Dialog), findsOneWidget);
final field = tester.widget<EditableText>(
find.descendant(
of: find.byKey(const Key('chat-quick-switch-field')),
matching: find.byType(EditableText),
),
);
expect(field.focusNode.hasPrimaryFocus, isTrue);
expect(_shown(tester), ['one', 'three', 'two']);
expect(_selected(tester), 'one');
// The list's avatar carries the harness, colour and activity badge.
expect(find.byType(ChatSessionAvatar), findsNWidgets(3));
expect(find.text('~/app'), findsNWidgets(2));
},
);
testWidgets(
'Ctrl+N, Ctrl+P, Down and Up move the selection and wrap',
(tester) async {
await _open(tester);
expect(await _chord(tester, LogicalKeyboardKey.keyN), isTrue);
expect(_selected(tester), 'three');
await _key(tester, LogicalKeyboardKey.arrowDown);
expect(_selected(tester), 'two');
await _key(tester, LogicalKeyboardKey.arrowDown);
expect(_selected(tester), 'one');
expect(await _chord(tester, LogicalKeyboardKey.keyP), isTrue);
expect(_selected(tester), 'two');
await _key(tester, LogicalKeyboardKey.arrowUp);
expect(_selected(tester), 'three');
},
variant: TargetPlatformVariant.desktop(),
);
testWidgets('typing filters, ranks and selects the first match', (
tester,
) async {
final switcher = await _open(tester);
await _key(tester, LogicalKeyboardKey.arrowDown);
await tester.enterText(
find.byKey(const Key('chat-quick-switch-field')),
'app',
);
await tester.pump();
expect(_shown(tester), ['one', 'three']);
expect(_selected(tester), 'one');
await tester.enterText(
find.byKey(const Key('chat-quick-switch-field')),
'build',
);
await tester.pump();
// The closed chat titled "Closed build" is not offered.
expect(_shown(tester), ['one']);
await tester.enterText(
find.byKey(const Key('chat-quick-switch-field')),
'zzz',
);
await tester.pump();
expect(find.byKey(const Key('chat-quick-switch-empty')), findsOneWidget);
// Ctrl+P still belongs to the switcher with nothing to select, so the
// browser does not print.
expect(await _chord(tester, LogicalKeyboardKey.keyP), isTrue);
await _key(tester, LogicalKeyboardKey.enter);
expect(switcher.chosen, isEmpty);
});
testWidgets('Enter chooses the selected chat and closes', (tester) async {
final switcher = await _open(tester);
await _key(tester, LogicalKeyboardKey.arrowDown);
await _key(tester, LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(switcher.chosen, ['three']);
expect(find.byType(Dialog), findsNothing);
});
testWidgets('a click chooses a row; Esc closes without choosing', (
tester,
) async {
final switcher = await _open(tester);
await _key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
expect(find.byType(Dialog), findsNothing);
expect(switcher.chosen, isEmpty);
await tester.tap(find.text('Open'));
await tester.pump(const Duration(milliseconds: 400));
await tester.tap(find.text('Deploy server'));
await tester.pumpAndSettle();
expect(switcher.chosen, ['two']);
});
testWidgets('closeChatQuickSwitch closes it from outside', (tester) async {
final switcher = await _open(tester);
closeChatQuickSwitch(switcher.route!);
await tester.pumpAndSettle();
expect(find.byType(Dialog), findsNothing);
expect(switcher.chosen, isEmpty);
// A second close of a closed switcher does nothing.
closeChatQuickSwitch(switcher.route!);
await tester.pump();
});
testWidgets('a phone shows it as a full-width bottom sheet', (tester) async {
await _open(tester, size: const Size(400, 800));
expect(find.byType(Dialog), findsNothing);
expect(find.byType(BottomSheet), findsOneWidget);
expect(
tester.getSize(find.byKey(const Key('chat-quick-switch-row-one'))).width,
400,
);
expect(_selected(tester), 'one');
});
}
@@ -0,0 +1,84 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/domain/chat_quick_switch.dart';
final rows = <JsonMap>[
{'id': 'r1', 'title': 'Recent work', 'directory': '/home/a/alpha'},
{'id': 'z', 'title': 'Zeta notes', 'starred': true},
{
'id': 'r2',
'title': 'Older',
'directory': '/home/a/beta',
'backend': 'codex',
},
{'id': 'r3', 'title': 'Same folder', 'directory': '/home/a/alpha'},
{'id': 'a', 'title': 'Alpha starred', 'starred': true},
{'id': 'c', 'title': 'Closed one', 'closed_at': 5},
{'id': 'x', 'title': 'Closed flag', 'closed': true},
{
'id': 'f',
'title': 'Far away',
'_server_id': 'm2',
'_server_name': 'Studio',
},
];
List<String> ids(List<JsonMap> rows) => [
for (final row in rows) '${row['id']}',
];
void main() {
test('no query lists open chats in list order, starred first', () {
// Starred by name, then Chats by directory group in server recency.
expect(ids(chatQuickSwitchCandidates(rows)), [
'a',
'z',
'r1',
'r3',
'r2',
'f',
]);
});
test('a query narrows by title, directory, harness and machine', () {
final open = chatQuickSwitchCandidates(rows);
expect(ids(chatQuickSwitchMatches(open, 'beta')), ['r2']);
expect(ids(chatQuickSwitchMatches(open, 'CODEX')), ['r2']);
expect(ids(chatQuickSwitchMatches(open, 'studio')), ['f']);
expect(
ids(chatQuickSwitchMatches(open, 'lab', serverName: (_) => 'Lab box')),
['a', 'z', 'r1', 'r3', 'r2', 'f'],
);
expect(ids(chatQuickSwitchMatches(open, 'closed')), isEmpty);
expect(ids(chatQuickSwitchMatches(open, 'nothing here')), isEmpty);
expect(ids(chatQuickSwitchMatches(open, ' ')), ids(open));
});
test('title starts rank before word starts, then substrings', () {
final open = chatQuickSwitchCandidates(<JsonMap>[
{'id': 'mid', 'title': 'kalpha'},
{'id': 'dir', 'title': 'Other', 'directory': '/src/alpha'},
{'id': 'word', 'title': 'The alpha plan'},
{'id': 'start', 'title': 'Alpha first'},
{'id': 'inner', 'title': 'Other', 'directory': '/src/xalphax'},
]);
expect(ids(chatQuickSwitchMatches(open, 'alp')), [
'start',
'word',
'dir',
'mid',
'inner',
]);
});
test('every word must match; ranks add up', () {
final open = chatQuickSwitchCandidates(rows);
expect(ids(chatQuickSwitchMatches(open, 'same alpha')), ['r3']);
expect(ids(chatQuickSwitchMatches(open, 'alpha')), ['a', 'r1', 'r3']);
});
test('an unnamed harness is OpenCode', () {
expect(chatQuickSwitchHarness({'id': 'q'}), 'opencode');
expect(chatQuickSwitchHarness({'backend': 'claude'}), 'claude');
});
}
@@ -41,6 +41,27 @@ void main() {
},
);
test('the chat switcher uses the Chat chord and names its keys', () {
KeyboardShortcutEntry switcher(
TargetPlatform platform, {
bool web = false,
}) => KeyboardShortcutRegistry(
platform: platform,
web: web,
).entries.firstWhere((entry) => entry.action == 'Switch to another chat');
expect(switcher(TargetPlatform.macOS).keys, 'Option+K, Cmd+K, Ctrl+K');
final linux = switcher(TargetPlatform.linux);
expect(linux.group, KeyboardShortcutGroup.chat);
expect(linux.keys, 'Alt+K, Ctrl+K');
expect(linux.caveat, contains('Ctrl+N'));
expect(linux.caveat, isNot(contains('browser tab')));
expect(
switcher(TargetPlatform.linux, web: true).caveat,
contains('A browser tab keeps Ctrl+N'),
);
});
test('Runs and Pipelines switch is Ctrl+A on every platform', () {
for (final platform in TargetPlatform.values) {
final entry = KeyboardShortcutRegistry(platform: platform, web: false)
@@ -0,0 +1,30 @@
{
"size": "1280x900",
"params": "chats=8&colors=1&activity=1",
"steps": [
{ "open": "/chat/perf-chat-0" },
{ "wait": 1500 },
{
"eval": "(window.__quickSwitchKeys = [], window.addEventListener('keydown', (e) => { if (e.ctrlKey || e.altKey) setTimeout(() => window.__quickSwitchKeys.push({ key: e.key, prevented: e.defaultPrevented })); }, true), true)",
"name": "record-keydown-defaults"
},
{ "press": "Alt+k", "wait": 800 },
{ "shot": "switcher-open" },
{ "press": "Control+n", "wait": 300 },
{ "press": "Control+n", "wait": 300 },
{ "shot": "switcher-ctrl-n-twice" },
{ "press": "Control+p", "wait": 300 },
{ "type": "s", "wait": 500 },
{ "shot": "switcher-filtered" },
{ "eval": "JSON.stringify(window.__quickSwitchKeys)", "name": "keydown-defaults" },
{
"expect": "window.__quickSwitchKeys.filter((k) => k.key === 'n' || k.key === 'p').length === 3 && window.__quickSwitchKeys.filter((k) => k.key === 'n' || k.key === 'p').every((k) => k.prevented)",
"name": "ctrl-n-and-ctrl-p-default-prevented"
},
{ "press": "Enter", "wait": 1200 },
{ "shot": "switched" },
{ "press": "Alt+k", "wait": 800 },
{ "press": "Alt+k", "wait": 800 },
{ "shot": "toggled-closed" }
]
}