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
+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',