Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(desktop): add isolated keybinding dispatch foundation

deed68034cbcca0
diff --git a/desktop/lib/shortcuts/app_keymap.dart b/desktop/lib/shortcuts/app_keymap.dart
new file mode 100644
index 000000000..2053afb7d
--- /dev/null
+++ b/desktop/lib/shortcuts/app_keymap.dart
@@ -0,0 +1,167 @@
+import 'dart:io';
+
+import 'package:flutter/widgets.dart';
+
+import 'app_shortcuts.dart';
+import 'keymap.dart';
+import 'keymap_commands.dart';
+import 'keymap_store.dart';
+
+/// A window's configuration, injectable so tests never read a user's dotfiles.
+class AppKeymap extends ChangeNotifier {
+ AppKeymap({this.store}) {
+ store?.addListener(_changed);
+ }
+ final KeymapStore? store;
+ int version = 0;
+ ResolvedKeymap get current => store?.current ?? harnessDefaultKeymap;
+ String? get error => store?.error;
+ String? get path => store?.file.path;
+ void _changed() {
+ version++;
+ notifyListeners();
+ }
+
+ Future<void> start() async {
+ await store?.start();
+ }
+
+ static KeymapStore fileStore() => KeymapStore(
+ file: File(KeymapStore.defaultPath()),
+ defaults: harnessDefaultBindings,
+ commands: harnessCommandById.keys.toSet(),
+ validate: (map) => validateNativeKeys(map, macOS: Platform.isMacOS),
+ );
+
+ Iterable<KeyBinding> bindings(
+ String command, {
+ KeymapContext context = KeymapContext.workspace,
+ }) => current
+ .bindingsFor(context)
+ .where((binding) => binding.command == command);
+
+ String? hint(
+ String command, {
+ KeymapContext context = KeymapContext.workspace,
+ }) {
+ final binding = bindings(command, context: context).firstOrNull;
+ return binding == null ? null : describeKeyBinding(binding);
+ }
+
+ /// These are names of actual AppKit commands, not all system shortcuts.
+ /// The second stroke of an explicit sequence can still use an editing key.
+ static void validateNativeKeys(ResolvedKeymap map, {required bool macOS}) {
+ if (!macOS) return;
+ final reserved = {
+ for (final chord in [
+ 'cmd+q',
+ 'cmd+m',
+ 'cmd+h',
+ 'cmd+alt+h',
+ 'cmd+ctrl+f',
+ 'cmd+c',
+ 'cmd+v',
+ 'cmd+x',
+ 'cmd+a',
+ 'cmd+z',
+ 'cmd+shift+z',
+ 'cmd+alt+shift+v',
+ 'cmd+backquote',
+ 'cmd+shift+backquote',
+ ])
+ KeyStroke.parse(chord),
+ };
+ for (final context in KeymapContext.values) {
+ for (final binding in map.bindingsFor(context)) {
+ if (binding.custom && reserved.contains(binding.keys.first)) {
+ throw FormatException(
+ '${binding.keys.first} belongs to a native Mac editing or window command; choose another first key',
+ );
+ }
+ }
+ }
+ }
+
+ @override
+ void dispose() {
+ store?.removeListener(_changed);
+ super.dispose();
+ }
+}
+
+/// InheritedTheme lets dialogs/routes carry the same live configuration.
+/// The provider rebuilds only on config changes, never on individual keys.
+class KeymapProvider extends StatelessWidget {
+ const KeymapProvider({super.key, required this.keymap, required this.child});
+ final AppKeymap keymap;
+ final Widget child;
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: keymap,
+ builder: (context, _) =>
+ KeymapTheme(keymap: keymap, version: keymap.version, child: child),
+ );
+}
+
+class KeymapTheme extends InheritedTheme {
+ const KeymapTheme({
+ super.key,
+ required this.keymap,
+ required this.version,
+ required super.child,
+ });
+ final AppKeymap keymap;
+ final int version;
+ static AppKeymap? of(BuildContext context, {bool listen = true}) =>
+ (listen
+ ? context.dependOnInheritedWidgetOfExactType<KeymapTheme>()
+ : context.getInheritedWidgetOfExactType<KeymapTheme>())
+ ?.keymap;
+ @override
+ bool updateShouldNotify(KeymapTheme oldWidget) =>
+ keymap != oldWidget.keymap || version != oldWidget.version;
+ @override
+ Widget wrap(BuildContext context, Widget child) =>
+ KeymapProvider(keymap: keymap, child: child);
+}
+
+/// Pickers provide their own actions. A terminal only changes scope/IME state;
+/// the containing workspace continues to own its navigation commands.
+class KeymapRegion extends InheritedWidget {
+ const KeymapRegion({
+ super.key,
+ required this.contextKind,
+ this.actions,
+ this.composing,
+ required super.child,
+ });
+ final KeymapContext contextKind;
+ final Map<String, VoidCallback>? actions;
+ final bool Function()? composing;
+ static KeymapRegion? of(BuildContext context) =>
+ context.getInheritedWidgetOfExactType<KeymapRegion>();
+ @override
+ bool updateShouldNotify(KeymapRegion oldWidget) => false;
+}
+
+String? effectiveShortcutHint(BuildContext context, ShortcutAction action) {
+ final command = harnessCommands
+ .where((command) => command.action == action)
+ .firstOrNull;
+ final map = KeymapTheme.of(context);
+ if (command == null) return null;
+ final binding = (map?.current ?? harnessDefaultKeymap)
+ .bindingsFor(KeymapContext.workspace)
+ .where((binding) => binding.command == command.id)
+ .firstOrNull;
+ return binding == null ? null : describeKeyBinding(binding);
+}
+
+String withEffectiveShortcutHint(
+ BuildContext context,
+ String label,
+ ShortcutAction action,
+) {
+ final hint = effectiveShortcutHint(context, action);
+ return hint == null ? label : '$label $hint';
+}
diff --git a/desktop/lib/shortcuts/keymap.dart b/desktop/lib/shortcuts/keymap.dart
index 1bc429c71..e994e7746 100644
--- a/desktop/lib/shortcuts/keymap.dart
+++ b/desktop/lib/shortcuts/keymap.dart
@@ -266,11 +266,11 @@ class ResolvedKeymap {
}
}
- if (context == KeymapContext.terminal) {
+ if (context != KeymapContext.workspace) {
apply(defaults, KeymapContext.workspace);
}
apply(defaults, context);
- if (context == KeymapContext.terminal) {
+ if (context != KeymapContext.workspace) {
apply(config.bindings, KeymapContext.workspace);
}
apply(config.bindings, context);
@@ -300,6 +300,16 @@ class ResolvedKeymap {
List<KeyBinding> bindingsFor(KeymapContext context) => _bindings[context]!;
+ Iterable<KeyBinding> continuations(
+ KeymapContext context,
+ List<KeyStroke> prefix,
+ ) => _bindings[context]!.where(
+ (binding) =>
+ binding.keys.length > prefix.length &&
+ Iterable.generate(prefix.length)
+ .every((i) => binding.keys[i] == prefix[i]),
+ );
+
KeymapMatch match(KeymapContext context, Iterable<KeyStroke> keys) {
var node = _roots[context]!;
for (final key in keys) {
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
new file mode 100644
index 000000000..660317e8c
--- /dev/null
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -0,0 +1,422 @@
+import '../logging/debug_surface.dart';
+import 'app_shortcuts.dart';
+import 'keymap.dart';
+
+/// Stable identities are the public dotfile interface. Labels, defaults,
+/// native menus and the command picker read this same catalog.
+class HarnessCommand {
+ const HarnessCommand(
+ this.id,
+ this.label,
+ this.group, {
+ this.keys = const [],
+ this.action,
+ this.nativeAction,
+ this.context = KeymapContext.workspace,
+ this.repeatable = false,
+ });
+ final String id, label;
+ final ShortcutGroup group;
+ final List<String> keys;
+ final ShortcutAction? action;
+ final String? nativeAction;
+ final KeymapContext context;
+ final bool repeatable;
+}
+
+final harnessCommands = <HarnessCommand>[
+ const HarnessCommand(
+ 'navigation.quick_open',
+ 'Search agents, swarms, machines and projects',
+ ShortcutGroup.navigate,
+ keys: ['cmd+p'],
+ action: ShortcutAction.switchAgent,
+ nativeAction: 'jump',
+ ),
+ const HarnessCommand(
+ 'navigation.commands',
+ 'Search commands',
+ ShortcutGroup.actions,
+ keys: ['cmd+shift+p'],
+ nativeAction: 'commands',
+ ),
+ const HarnessCommand(
+ 'swarm.new',
+ 'New swarm',
+ ShortcutGroup.navigate,
+ keys: ['cmd+t'],
+ action: ShortcutAction.newSwarm,
+ nativeAction: 'new',
+ ),
+ const HarnessCommand(
+ 'swarm.close',
+ 'Close this swarm',
+ ShortcutGroup.navigate,
+ keys: ['cmd+w'],
+ action: ShortcutAction.closeSwarm,
+ nativeAction: 'closeActive',
+ ),
+ const HarnessCommand(
+ 'swarm.reopen',
+ 'Reopen closed swarm',
+ ShortcutGroup.navigate,
+ keys: ['cmd+shift+t'],
+ action: ShortcutAction.reopenClosedSwarm,
+ nativeAction: 'reopen',
+ ),
+ const HarnessCommand(
+ 'swarm.next',
+ 'Next swarm',
+ ShortcutGroup.navigate,
+ keys: ['cmd+shift+]'],
+ action: ShortcutAction.nextSwarm,
+ nativeAction: 'next',
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'swarm.previous',
+ 'Previous swarm',
+ ShortcutGroup.navigate,
+ keys: ['cmd+shift+['],
+ action: ShortcutAction.previousSwarm,
+ nativeAction: 'previous',
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'swarm.rename',
+ 'Rename this swarm',
+ ShortcutGroup.actions,
+ action: ShortcutAction.renameSwarm,
+ nativeAction: 'renameActive',
+ ),
+ const HarnessCommand(
+ 'navigation.back',
+ 'Go back',
+ ShortcutGroup.navigate,
+ keys: ['cmd+['],
+ action: ShortcutAction.previousAgent,
+ nativeAction: 'historyBack',
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'navigation.forward',
+ 'Go forward',
+ ShortcutGroup.navigate,
+ keys: ['cmd+]'],
+ action: ShortcutAction.nextAgent,
+ nativeAction: 'historyForward',
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'navigation.history',
+ 'Show full history',
+ ShortcutGroup.navigate,
+ keys: ['cmd+y'],
+ action: ShortcutAction.showHistory,
+ nativeAction: 'showHistory',
+ ),
+ const HarnessCommand(
+ 'navigation.needs_input',
+ 'Show agents needing input',
+ ShortcutGroup.navigate,
+ keys: ['cmd+shift+i'],
+ action: ShortcutAction.showAttention,
+ nativeAction: 'notifications',
+ ),
+ for (var i = 1; i <= 9; i++)
+ HarnessCommand(
+ 'swarm.select_$i',
+ i == 9 ? 'Select the last swarm' : 'Select swarm $i',
+ ShortcutGroup.navigate,
+ keys: ['cmd+$i'],
+ ),
+ for (var i = 1; i <= 9; i++)
+ HarnessCommand(
+ 'pane.focus_$i',
+ 'Focus pane $i',
+ ShortcutGroup.panes,
+ keys: ['cmd+alt+$i'],
+ ),
+ const HarnessCommand(
+ 'pane.focus_left',
+ 'Focus the pane to the left',
+ ShortcutGroup.panes,
+ keys: ['cmd+alt+left'],
+ action: ShortcutAction.focusPaneLeft,
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'pane.focus_right',
+ 'Focus the pane to the right',
+ ShortcutGroup.panes,
+ keys: ['cmd+alt+right'],
+ action: ShortcutAction.focusPaneRight,
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'pane.focus_above',
+ 'Focus the pane above',
+ ShortcutGroup.panes,
+ keys: ['cmd+alt+up'],
+ action: ShortcutAction.focusPaneAbove,
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'pane.focus_below',
+ 'Focus the pane below',
+ ShortcutGroup.panes,
+ keys: ['cmd+alt+down'],
+ action: ShortcutAction.focusPaneBelow,
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'pane.move_left',
+ 'Move the pane left',
+ ShortcutGroup.panes,
+ keys: ['cmd+alt+shift+left'],
+ action: ShortcutAction.movePaneLeft,
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'pane.move_right',
+ 'Move the pane right',
+ ShortcutGroup.panes,
+ keys: ['cmd+alt+shift+right'],
+ action: ShortcutAction.movePaneRight,
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'pane.move_up',
+ 'Move the pane up',
+ ShortcutGroup.panes,
+ keys: ['cmd+alt+shift+up'],
+ action: ShortcutAction.movePaneUp,
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'pane.move_down',
+ 'Move the pane down',
+ ShortcutGroup.panes,
+ keys: ['cmd+alt+shift+down'],
+ action: ShortcutAction.movePaneDown,
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'pane.zoom',
+ 'Zoom or restore the focused pane',
+ ShortcutGroup.panes,
+ keys: ['cmd+shift+enter'],
+ action: ShortcutAction.zoomPane,
+ nativeAction: 'zoomPane',
+ ),
+ const HarnessCommand(
+ 'pane.close',
+ 'Remove the focused agent from this swarm',
+ ShortcutGroup.panes,
+ keys: ['cmd+alt+w'],
+ action: ShortcutAction.closePane,
+ nativeAction: 'closePane',
+ ),
+ const HarnessCommand(
+ 'pane.last',
+ 'Return to the last pane',
+ ShortcutGroup.panes,
+ action: ShortcutAction.lastPane,
+ ),
+ const HarnessCommand(
+ 'pane.pin',
+ 'Pin or unpin the focused pane',
+ ShortcutGroup.panes,
+ action: ShortcutAction.pinPane,
+ ),
+ const HarnessCommand(
+ 'pane.layout',
+ 'Choose a layout',
+ ShortcutGroup.panes,
+ action: ShortcutAction.showLayout,
+ nativeAction: 'layout',
+ ),
+ const HarnessCommand(
+ 'terminal.find',
+ 'Find in the focused terminal',
+ ShortcutGroup.navigate,
+ keys: ['cmd+f'],
+ action: ShortcutAction.findTerminal,
+ nativeAction: 'findTerminal',
+ ),
+ const HarnessCommand(
+ 'terminal.find_next',
+ 'Next terminal match',
+ ShortcutGroup.navigate,
+ keys: ['cmd+g'],
+ action: ShortcutAction.findNext,
+ nativeAction: 'findNext',
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'terminal.find_previous',
+ 'Previous terminal match',
+ ShortcutGroup.navigate,
+ keys: ['cmd+shift+g'],
+ action: ShortcutAction.findPrevious,
+ nativeAction: 'findPrevious',
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'agent.new',
+ 'New agent',
+ ShortcutGroup.actions,
+ keys: ['cmd+n'],
+ action: ShortcutAction.newAgent,
+ nativeAction: 'newAgent',
+ ),
+ const HarnessCommand(
+ 'machine.link',
+ 'Link machine',
+ ShortcutGroup.actions,
+ nativeAction: 'linkMachine',
+ ),
+ const HarnessCommand(
+ 'project.add',
+ 'Add project',
+ ShortcutGroup.actions,
+ nativeAction: 'addProject',
+ ),
+ const HarnessCommand(
+ 'machines.refresh',
+ 'Refresh machines and agents',
+ ShortcutGroup.actions,
+ keys: ['cmd+r'],
+ action: ShortcutAction.reload,
+ nativeAction: 'reload',
+ ),
+ const HarnessCommand(
+ 'task.route',
+ 'Route a task',
+ ShortcutGroup.actions,
+ action: ShortcutAction.routeTask,
+ ),
+ const HarnessCommand(
+ 'app.settings',
+ 'Open Settings',
+ ShortcutGroup.actions,
+ keys: ['cmd+comma'],
+ action: ShortcutAction.showSettings,
+ nativeAction: 'settings',
+ ),
+ const HarnessCommand(
+ 'keyboard.help',
+ 'Keyboard shortcuts',
+ ShortcutGroup.actions,
+ keys: ['cmd+slash'],
+ action: ShortcutAction.showShortcuts,
+ nativeAction: 'showShortcuts',
+ ),
+ const HarnessCommand(
+ 'keyboard.open_config',
+ 'Open keyboard config',
+ ShortcutGroup.actions,
+ nativeAction: 'openKeymap',
+ ),
+ if (kDebugSurfaceEnabled)
+ const HarnessCommand(
+ 'app.debug',
+ 'Open the debug log',
+ ShortcutGroup.actions,
+ action: ShortcutAction.showDebug,
+ ),
+ const HarnessCommand(
+ 'picker.next',
+ 'Next result',
+ ShortcutGroup.navigate,
+ keys: ['down', 'ctrl+n', 'ctrl+j'],
+ context: KeymapContext.picker,
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'picker.previous',
+ 'Previous result',
+ ShortcutGroup.navigate,
+ keys: ['up', 'ctrl+p', 'ctrl+k'],
+ context: KeymapContext.picker,
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'picker.accept',
+ 'Open the selected result',
+ ShortcutGroup.navigate,
+ keys: ['enter'],
+ context: KeymapContext.picker,
+ ),
+ const HarnessCommand(
+ 'picker.add_here',
+ 'Add the selected agent to this swarm',
+ ShortcutGroup.actions,
+ keys: ['cmd+enter'],
+ context: KeymapContext.picker,
+ ),
+ const HarnessCommand(
+ 'picker.cancel',
+ 'Close search',
+ ShortcutGroup.navigate,
+ keys: ['escape', 'ctrl+g'],
+ context: KeymapContext.picker,
+ ),
+ const HarnessCommand(
+ 'picker.back',
+ 'Return to all results',
+ ShortcutGroup.navigate,
+ keys: ['cmd+['],
+ context: KeymapContext.picker,
+ ),
+];
+
+final harnessCommandById = {
+ for (final command in harnessCommands) command.id: command,
+};
+final harnessDefaultBindings = [
+ for (final command in harnessCommands)
+ for (final keys in command.keys)
+ KeyBinding(
+ keys: keys.split(' ').map(KeyStroke.parse),
+ command: command.id,
+ context: command.context,
+ ),
+];
+final harnessDefaultKeymap = ResolvedKeymap(
+ harnessDefaultBindings,
+ const KeymapConfig.empty(),
+);
+
+String describeKeyStroke(KeyStroke stroke) => [
+ if (stroke.control) '⌃',
+ if (stroke.alt) '⌥',
+ if (stroke.shift) '⇧',
+ if (stroke.command) '⌘',
+ const {
+ 'left': '←',
+ 'right': '→',
+ 'up': '↑',
+ 'down': '↓',
+ 'enter': '↵',
+ 'escape': 'Esc',
+ 'tab': '⇥',
+ 'space': 'Space',
+ 'comma': ',',
+ 'period': '.',
+ 'slash': '/',
+ 'backslash': r'\',
+ 'semicolon': ';',
+ 'quote': "'",
+ 'backquote': '`',
+ 'bracketleft': '[',
+ 'bracketright': ']',
+ 'minus': '-',
+ 'equal': '=',
+ 'backspace': '⌫',
+ 'delete': '⌦',
+ }[stroke.key] ??
+ stroke.key.toUpperCase(),
+].join();
+String describeKeyBinding(KeyBinding binding) =>
+ binding.keys.map(describeKeyStroke).join(' ');
diff --git a/desktop/lib/shortcuts/keymap_dispatch.dart b/desktop/lib/shortcuts/keymap_dispatch.dart
new file mode 100644
index 000000000..2d8bbe91e
--- /dev/null
+++ b/desktop/lib/shortcuts/keymap_dispatch.dart
@@ -0,0 +1,107 @@
+import 'keymap.dart';
+
+enum KeymapKeyPhase { down, repeat, up }
+
+class KeymapDispatchResult {
+ const KeymapDispatchResult({this.handled = false, this.command});
+ final bool handled;
+ final String? command;
+}
+
+/// Dispatch is synchronous and bounded. An unmatched sequence is consumed,
+/// never replayed into an agent. Modifiers still follow their normal route.
+class KeymapDispatch {
+ KeymapDispatch(this._map);
+ ResolvedKeymap _map;
+ final _prefix = <KeyStroke>[];
+ final _pressed = <Object>{};
+ Object? _owner;
+ KeymapContext? _context;
+
+ List<KeyStroke> get pending => List.unmodifiable(_prefix);
+ bool get hasPending => _prefix.isNotEmpty;
+ bool release(Object physicalKey) => _pressed.remove(physicalKey);
+
+ void update(ResolvedKeymap map) {
+ if (identical(_map, map)) return;
+ _map = map;
+ cancel();
+ }
+
+ void cancel() {
+ _prefix.clear();
+ _owner = null;
+ _context = null;
+ }
+
+ /// Called on window blur, when the platform may never deliver held key-ups.
+ void suspend() {
+ cancel();
+ _pressed.clear();
+ }
+
+ KeymapDispatchResult dispatch({
+ required KeyStroke? stroke,
+ required Object physicalKey,
+ required KeymapKeyPhase phase,
+ required KeymapContext context,
+ required Object owner,
+ required bool Function(String) canExecute,
+ bool Function(String)? canRepeat,
+ bool composing = false,
+ bool modifier = false,
+ }) {
+ if (phase == KeymapKeyPhase.up) {
+ return KeymapDispatchResult(handled: release(physicalKey));
+ }
+ if (composing) {
+ cancel();
+ return const KeymapDispatchResult();
+ }
+ if (hasPending && (!identical(owner, _owner) || context != _context)) {
+ cancel();
+ }
+ if (stroke == null) {
+ if (!modifier && hasPending) {
+ cancel();
+ _pressed.add(physicalKey);
+ return const KeymapDispatchResult(handled: true);
+ }
+ return const KeymapDispatchResult();
+ }
+ if (phase == KeymapKeyPhase.repeat && hasPending) {
+ return KeymapDispatchResult(handled: _pressed.contains(physicalKey));
+ }
+ final wasPending = hasPending;
+ if (wasPending && stroke == const KeyStroke('escape')) {
+ cancel();
+ _pressed.add(physicalKey);
+ return const KeymapDispatchResult(handled: true);
+ }
+ final sequence = [..._prefix, stroke];
+ final match = _map.match(context, sequence);
+ if (match.prefix) {
+ _prefix.add(stroke);
+ _owner = owner;
+ _context = context;
+ _pressed.add(physicalKey);
+ return const KeymapDispatchResult(handled: true);
+ }
+ cancel();
+ final command = match.command;
+ if (command != null) {
+ _pressed.add(physicalKey);
+ return KeymapDispatchResult(
+ handled: true,
+ command:
+ canExecute(command) &&
+ (phase != KeymapKeyPhase.repeat ||
+ canRepeat?.call(command) == true)
+ ? command
+ : null,
+ );
+ }
+ if (wasPending) _pressed.add(physicalKey);
+ return KeymapDispatchResult(handled: wasPending);
+ }
+}
diff --git a/desktop/lib/shortcuts/keymap_host.dart b/desktop/lib/shortcuts/keymap_host.dart
new file mode 100644
index 000000000..9f9b18a35
--- /dev/null
+++ b/desktop/lib/shortcuts/keymap_host.dart
@@ -0,0 +1,161 @@
+import 'package:flutter/services.dart';
+import 'package:flutter/widgets.dart';
+
+import 'app_keymap.dart';
+import 'keymap.dart';
+import 'keymap_commands.dart';
+import 'keymap_dispatch.dart';
+import 'keymap_keyboard.dart';
+
+/// Runs before a focused terminal/editor. Unmatched events are returned intact
+/// to that original owner; there is no disk access or deferred key replay.
+class KeymapHost extends StatefulWidget {
+ const KeymapHost({
+ super.key,
+ required this.keymap,
+ required this.actions,
+ required this.enabled,
+ required this.child,
+ this.canExecute,
+ this.onPending,
+ });
+ final AppKeymap keymap;
+ final Map<String, VoidCallback> actions;
+ final bool Function() enabled;
+ final bool Function(String)? canExecute;
+ final ValueChanged<String>? onPending;
+ final Widget child;
+ @override
+ State<KeymapHost> createState() => _KeymapHostState();
+}
+
+class _KeymapHostState extends State<KeymapHost> with WidgetsBindingObserver {
+ late final _dispatch = KeymapDispatch(widget.keymap.current);
+ FocusNode? _owner;
+ String _pending = '';
+ static final _modifiers = {
+ LogicalKeyboardKey.shiftLeft,
+ LogicalKeyboardKey.shiftRight,
+ LogicalKeyboardKey.controlLeft,
+ LogicalKeyboardKey.controlRight,
+ LogicalKeyboardKey.altLeft,
+ LogicalKeyboardKey.altRight,
+ LogicalKeyboardKey.metaLeft,
+ LogicalKeyboardKey.metaRight,
+ LogicalKeyboardKey.capsLock,
+ LogicalKeyboardKey.fn,
+ };
+
+ @override
+ void initState() {
+ super.initState();
+ FocusManager.instance.addEarlyKeyEventHandler(_handle);
+ FocusManager.instance.addListener(_focusChanged);
+ widget.keymap.addListener(_keymapChanged);
+ WidgetsBinding.instance.addObserver(this);
+ }
+
+ void _keymapChanged() {
+ _dispatch.update(widget.keymap.current);
+ _notifyPending();
+ }
+
+ void _focusChanged() {
+ final next = FocusManager.instance.primaryFocus;
+ if (identical(next, _owner)) return;
+ _owner = next;
+ _dispatch.cancel();
+ _notifyPending();
+ }
+
+ void _notifyPending() {
+ final next = _dispatch.pending.map(describeKeyStroke).join(' ');
+ if (next == _pending) return;
+ _pending = next;
+ widget.onPending?.call(next);
+ }
+
+ @override
+ void didUpdateWidget(KeymapHost oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.keymap != widget.keymap) {
+ oldWidget.keymap.removeListener(_keymapChanged);
+ widget.keymap.addListener(_keymapChanged);
+ _keymapChanged();
+ }
+ }
+
+ @override
+ void didChangeAppLifecycleState(AppLifecycleState state) {
+ if (state != AppLifecycleState.resumed) {
+ _dispatch.suspend();
+ _notifyPending();
+ }
+ }
+
+ KeyEventResult _handle(KeyEvent event) {
+ if (event is KeyUpEvent) {
+ return _dispatch.release(event.physicalKey)
+ ? KeyEventResult.handled
+ : KeyEventResult.ignored;
+ }
+ final focus = FocusManager.instance.primaryFocus;
+ final context = focus?.context;
+ if (context == null ||
+ KeymapTheme.of(context, listen: false) != widget.keymap) {
+ _dispatch.cancel();
+ _notifyPending();
+ return KeyEventResult.ignored;
+ }
+ final region = KeymapRegion.of(context);
+ final localActions = region?.actions;
+ if (localActions == null && !widget.enabled()) {
+ _dispatch.cancel();
+ _notifyPending();
+ return KeyEventResult.ignored;
+ }
+ final actions = localActions ?? widget.actions;
+ final value = context
+ .findAncestorStateOfType<EditableTextState>()
+ ?.widget
+ .controller
+ .value;
+ final composing =
+ region?.composing?.call() == true ||
+ (value != null &&
+ value.composing.isValid &&
+ !value.composing.isCollapsed);
+ final result = _dispatch.dispatch(
+ stroke: keyStrokeForEvent(event),
+ physicalKey: event.physicalKey,
+ phase: event is KeyUpEvent
+ ? KeymapKeyPhase.up
+ : event is KeyRepeatEvent
+ ? KeymapKeyPhase.repeat
+ : KeymapKeyPhase.down,
+ context: region?.contextKind ?? KeymapContext.workspace,
+ owner: focus!,
+ composing: composing,
+ modifier: _modifiers.contains(event.logicalKey),
+ canExecute: (id) =>
+ actions.containsKey(id) &&
+ (localActions != null || widget.canExecute?.call(id) != false),
+ canRepeat: (id) => harnessCommandById[id]?.repeatable == true,
+ );
+ _notifyPending();
+ if (result.command != null) actions[result.command!]?.call();
+ return result.handled ? KeyEventResult.handled : KeyEventResult.ignored;
+ }
+
+ @override
+ void dispose() {
+ FocusManager.instance.removeEarlyKeyEventHandler(_handle);
+ FocusManager.instance.removeListener(_focusChanged);
+ widget.keymap.removeListener(_keymapChanged);
+ WidgetsBinding.instance.removeObserver(this);
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) => widget.child;
+}
diff --git a/desktop/lib/shortcuts/keymap_keyboard.dart b/desktop/lib/shortcuts/keymap_keyboard.dart
new file mode 100644
index 000000000..c4941e211
--- /dev/null
+++ b/desktop/lib/shortcuts/keymap_keyboard.dart
@@ -0,0 +1,128 @@
+import 'package:flutter/services.dart';
+
+import 'keymap.dart';
+
+/// Canonical logical keys, shared by configured bindings and keyboard events.
+/// This does not guess a QWERTY position for a letter on another layout.
+final _logicalKeys = <LogicalKeyboardKey, String>{
+ LogicalKeyboardKey.enter: 'enter',
+ LogicalKeyboardKey.numpadEnter: 'enter',
+ LogicalKeyboardKey.escape: 'escape',
+ LogicalKeyboardKey.arrowLeft: 'left',
+ LogicalKeyboardKey.arrowRight: 'right',
+ LogicalKeyboardKey.arrowUp: 'up',
+ LogicalKeyboardKey.arrowDown: 'down',
+ LogicalKeyboardKey.pageUp: 'pageup',
+ LogicalKeyboardKey.pageDown: 'pagedown',
+ LogicalKeyboardKey.home: 'home',
+ LogicalKeyboardKey.end: 'end',
+ LogicalKeyboardKey.delete: 'delete',
+ LogicalKeyboardKey.backspace: 'backspace',
+ LogicalKeyboardKey.tab: 'tab',
+ LogicalKeyboardKey.space: 'space',
+ LogicalKeyboardKey.comma: 'comma',
+ LogicalKeyboardKey.period: 'period',
+ LogicalKeyboardKey.slash: 'slash',
+ LogicalKeyboardKey.backslash: 'backslash',
+ LogicalKeyboardKey.semicolon: 'semicolon',
+ LogicalKeyboardKey.quote: 'quote',
+ LogicalKeyboardKey.backquote: 'backquote',
+ LogicalKeyboardKey.bracketLeft: 'bracketleft',
+ LogicalKeyboardKey.bracketRight: 'bracketright',
+ LogicalKeyboardKey.minus: 'minus',
+ LogicalKeyboardKey.equal: 'equal',
+ LogicalKeyboardKey.insert: 'insert',
+ for (final key in [
+ LogicalKeyboardKey.keyA,
+ LogicalKeyboardKey.keyB,
+ LogicalKeyboardKey.keyC,
+ LogicalKeyboardKey.keyD,
+ LogicalKeyboardKey.keyE,
+ LogicalKeyboardKey.keyF,
+ LogicalKeyboardKey.keyG,
+ LogicalKeyboardKey.keyH,
+ LogicalKeyboardKey.keyI,
+ LogicalKeyboardKey.keyJ,
+ LogicalKeyboardKey.keyK,
+ LogicalKeyboardKey.keyL,
+ LogicalKeyboardKey.keyM,
+ LogicalKeyboardKey.keyN,
+ LogicalKeyboardKey.keyO,
+ LogicalKeyboardKey.keyP,
+ LogicalKeyboardKey.keyQ,
+ LogicalKeyboardKey.keyR,
+ LogicalKeyboardKey.keyS,
+ LogicalKeyboardKey.keyT,
+ LogicalKeyboardKey.keyU,
+ LogicalKeyboardKey.keyV,
+ LogicalKeyboardKey.keyW,
+ LogicalKeyboardKey.keyX,
+ LogicalKeyboardKey.keyY,
+ LogicalKeyboardKey.keyZ,
+ LogicalKeyboardKey.digit0,
+ LogicalKeyboardKey.digit1,
+ LogicalKeyboardKey.digit2,
+ LogicalKeyboardKey.digit3,
+ LogicalKeyboardKey.digit4,
+ LogicalKeyboardKey.digit5,
+ LogicalKeyboardKey.digit6,
+ LogicalKeyboardKey.digit7,
+ LogicalKeyboardKey.digit8,
+ LogicalKeyboardKey.digit9,
+ LogicalKeyboardKey.f1,
+ LogicalKeyboardKey.f2,
+ LogicalKeyboardKey.f3,
+ LogicalKeyboardKey.f4,
+ LogicalKeyboardKey.f5,
+ LogicalKeyboardKey.f6,
+ LogicalKeyboardKey.f7,
+ LogicalKeyboardKey.f8,
+ LogicalKeyboardKey.f9,
+ LogicalKeyboardKey.f10,
+ LogicalKeyboardKey.f11,
+ LogicalKeyboardKey.f12,
+ LogicalKeyboardKey.f13,
+ LogicalKeyboardKey.f14,
+ LogicalKeyboardKey.f15,
+ LogicalKeyboardKey.f16,
+ LogicalKeyboardKey.f17,
+ LogicalKeyboardKey.f18,
+ LogicalKeyboardKey.f19,
+ LogicalKeyboardKey.f20,
+ LogicalKeyboardKey.f21,
+ LogicalKeyboardKey.f22,
+ LogicalKeyboardKey.f23,
+ LogicalKeyboardKey.f24,
+ ])
+ key: key.keyLabel.toLowerCase(),
+};
+
+KeyStroke? keyStrokeFor(
+ LogicalKeyboardKey key, {
+ bool control = false,
+ bool alt = false,
+ bool command = false,
+ bool shift = false,
+}) {
+ final name = _logicalKeys[key];
+ return name == null
+ ? null
+ : KeyStroke(
+ name,
+ control: control,
+ alt: alt,
+ command: command,
+ shift: shift,
+ );
+}
+
+KeyStroke? keyStrokeForEvent(KeyEvent event) {
+ final keyboard = HardwareKeyboard.instance;
+ return keyStrokeFor(
+ event.logicalKey,
+ control: keyboard.isControlPressed,
+ alt: keyboard.isAltPressed,
+ command: keyboard.isMetaPressed,
+ shift: keyboard.isShiftPressed,
+ );
+}
diff --git a/desktop/lib/shortcuts/keymap_store.dart b/desktop/lib/shortcuts/keymap_store.dart
index d8a56e220..37e16029a 100644
--- a/desktop/lib/shortcuts/keymap_store.dart
+++ b/desktop/lib/shortcuts/keymap_store.dart
@@ -16,15 +16,18 @@ class KeymapStore extends ChangeNotifier {
required Iterable<KeyBinding> defaults,
required Set<String> commands,
this.watchFiles = true,
+ this.validate,
}) : _defaults = List.unmodifiable(defaults),
_commands = Set.unmodifiable(commands) {
current = ResolvedKeymap(_defaults, const KeymapConfig.empty());
+ validate?.call(current);
_signature = _describe(current);
}
static const maximumBytes = 128 * 1024;
final File file;
final bool watchFiles;
+ final void Function(ResolvedKeymap)? validate;
final List<KeyBinding> _defaults;
final Set<String> _commands;
late ResolvedKeymap current;
@@ -87,6 +90,7 @@ class KeymapStore extends ChangeNotifier {
_defaults,
KeymapConfig.parse(source, commands: _commands),
);
+ validate?.call(next);
if (_disposed || generation != _generation) return;
final signature = _describe(next);
if (_signature != signature) {
diff --git a/desktop/test/keymap_dispatch_test.dart b/desktop/test/keymap_dispatch_test.dart
new file mode 100644
index 000000000..7ec0d9ff0
--- /dev/null
+++ b/desktop/test/keymap_dispatch_test.dart
@@ -0,0 +1,182 @@
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shortcuts/keymap.dart';
+import 'package:harness/shortcuts/keymap_dispatch.dart';
+import 'package:harness/shortcuts/keymap_keyboard.dart';
+
+KeyBinding binding(String sequence, String? command) => KeyBinding(
+ keys: sequence.split(' ').map(KeyStroke.parse),
+ command: command,
+);
+ResolvedKeymap keymap([KeymapConfig config = const KeymapConfig.empty()]) =>
+ ResolvedKeymap([
+ binding('cmd+p', 'search.open'),
+ binding('cmd+t', 'swarm.new'),
+ binding('cmd+alt+left', 'pane.left'),
+ binding('ctrl+space h', 'pane.left'),
+ binding('ctrl+space l', 'pane.right'),
+ ], config);
+
+void main() {
+ late KeymapDispatch runtime;
+ late Object owner;
+ setUp(() {
+ runtime = KeymapDispatch(keymap());
+ owner = Object();
+ });
+ KeymapDispatchResult press(
+ String? key, {
+ KeymapKeyPhase phase = KeymapKeyPhase.down,
+ Object? focus,
+ bool composing = false,
+ bool enabled = true,
+ bool modifier = false,
+ }) => runtime.dispatch(
+ stroke: key == null ? null : KeyStroke.parse(key),
+ physicalKey: key ?? 'unmapped',
+ phase: phase,
+ context: KeymapContext.terminal,
+ owner: focus ?? owner,
+ canExecute: (_) => enabled,
+ canRepeat: (command) => command == 'pane.left',
+ composing: composing,
+ modifier: modifier,
+ );
+
+ test('ordinary terminal and native editing keys are untouched', () {
+ for (final key in [
+ 'h',
+ 'ctrl+b',
+ 'ctrl+w',
+ 'ctrl+r',
+ 'ctrl+c',
+ 'alt+c',
+ 'alt+enter',
+ 'ctrl+tab',
+ 'cmd+c',
+ 'cmd+v',
+ 'cmd+a',
+ 'escape',
+ ]) {
+ expect(press(key).handled, isFalse, reason: key);
+ expect(press(key, phase: KeymapKeyPhase.up).handled, isFalse);
+ }
+ expect(press('cmd+p').command, 'search.open');
+ expect(press('cmd+p', phase: KeymapKeyPhase.up).handled, isTrue);
+ });
+
+ test('sequences consume their prefix and release modifiers normally', () {
+ final first = press('ctrl+space');
+ expect(first.handled, isTrue);
+ expect(first.command, isNull);
+ expect(runtime.pending.map((key) => key.toString()), ['ctrl+space']);
+ expect(press(null, modifier: true).handled, isFalse);
+ expect(press('ctrl+space', phase: KeymapKeyPhase.up).handled, isTrue);
+ expect(press('h').command, 'pane.left');
+ expect(runtime.hasPending, isFalse);
+ expect(press('h', phase: KeymapKeyPhase.up).handled, isTrue);
+ });
+
+ test('wrong, unsupported and Escape sequence completions never become terminal input', () {
+ for (final key in ['x', 'escape', null]) {
+ press('ctrl+space');
+ final result = press(key);
+ expect(result.handled, isTrue, reason: '$key');
+ expect(result.command, isNull);
+ expect(runtime.hasPending, isFalse);
+ expect(press(key, phase: KeymapKeyPhase.up).handled, isTrue);
+ expect(press('h').handled, isFalse);
+ }
+ });
+
+ test(
+ 'changing focus cancels the old sequence before interpreting a new key',
+ () {
+ press('ctrl+space');
+ final result = press('h', focus: Object());
+ expect(result.handled, isFalse);
+ expect(result.command, isNull);
+ expect(runtime.hasPending, isFalse);
+ },
+ );
+
+ test('reload cancels a pending sequence and unbinding restores the ordinary route', () {
+ press('ctrl+space');
+ runtime.update(
+ keymap(
+ KeymapConfig([
+ binding('ctrl+space', null),
+ binding('cmd+p', null),
+ binding('cmd+o', 'search.open'),
+ ]),
+ ),
+ );
+ expect(runtime.hasPending, isFalse);
+ expect(press('h').handled, isFalse);
+ expect(press('cmd+p').handled, isFalse);
+ expect(press('cmd+o').command, 'search.open');
+ expect(press('ctrl+space', phase: KeymapKeyPhase.up).handled, isTrue);
+ });
+
+ test('repeat cannot create swarms or advance a sequence; directional commands can repeat', () {
+ expect(press('cmd+t').command, 'swarm.new');
+ expect(press('cmd+t', phase: KeymapKeyPhase.repeat).handled, isTrue);
+ expect(press('cmd+t', phase: KeymapKeyPhase.repeat).command, isNull);
+ expect(
+ press('cmd+alt+left', phase: KeymapKeyPhase.repeat).command,
+ 'pane.left',
+ );
+ press('ctrl+space');
+ expect(press('ctrl+space', phase: KeymapKeyPhase.repeat).command, isNull);
+ expect(runtime.pending.length, 1);
+ expect(press('l').command, 'pane.right');
+ });
+
+ test('IME keeps composing keys and window blur clears held-key state', () {
+ press('ctrl+space');
+ expect(press('h', composing: true).handled, isFalse);
+ expect(runtime.hasPending, isFalse);
+ expect(press('cmd+p', composing: true).handled, isFalse);
+ runtime.suspend();
+ expect(press('ctrl+space', phase: KeymapKeyPhase.up).handled, isFalse);
+ });
+
+ test(
+ 'a configured but disabled command cannot type its key into an agent',
+ () {
+ runtime.update(
+ ResolvedKeymap([
+ binding('x', 'swarm.close'),
+ ], const KeymapConfig.empty()),
+ );
+ final result = press('x', enabled: false);
+ expect(result.handled, isTrue);
+ expect(result.command, isNull);
+ expect(press('x', phase: KeymapKeyPhase.up).handled, isTrue);
+ },
+ );
+
+ test(
+ 'Flutter adapter distinguishes logical keys, punctuation and modifiers',
+ () {
+ expect(
+ keyStrokeFor(LogicalKeyboardKey.keyH, command: true, alt: true),
+ KeyStroke.parse('cmd+alt+h'),
+ );
+ expect(
+ keyStrokeFor(
+ LogicalKeyboardKey.bracketRight,
+ command: true,
+ shift: true,
+ ),
+ KeyStroke.parse('cmd+shift+]'),
+ );
+ expect(
+ keyStrokeFor(LogicalKeyboardKey.numpadEnter),
+ KeyStroke.parse('enter'),
+ );
+ expect(keyStrokeFor(LogicalKeyboardKey.f24), KeyStroke.parse('f24'));
+ expect(keyStrokeFor(LogicalKeyboardKey.shiftLeft, shift: true), isNull);
+ },
+ );
+}
diff --git a/desktop/test/keymap_host_test.dart b/desktop/test/keymap_host_test.dart
new file mode 100644
index 000000000..2ac098283
--- /dev/null
+++ b/desktop/test/keymap_host_test.dart
@@ -0,0 +1,220 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap.dart';
+import 'package:harness/shortcuts/keymap_commands.dart';
+import 'package:harness/shortcuts/keymap_host.dart';
+import 'package:harness/shortcuts/keymap_keyboard.dart';
+
+class MemoryKeymap extends AppKeymap {
+ ResolvedKeymap map = harnessDefaultKeymap;
+ @override
+ ResolvedKeymap get current => map;
+ void apply(String source) {
+ map = ResolvedKeymap(
+ harnessDefaultBindings,
+ KeymapConfig.parse(source, commands: harnessCommandById.keys.toSet()),
+ );
+ version++;
+ notifyListeners();
+ }
+}
+
+Future<void> key(
+ WidgetTester tester,
+ LogicalKeyboardKey key, {
+ bool cmd = false,
+ bool ctrl = false,
+ bool alt = false,
+ bool shift = false,
+}) async {
+ final mods = [
+ if (cmd) LogicalKeyboardKey.metaLeft,
+ if (ctrl) LogicalKeyboardKey.controlLeft,
+ if (alt) LogicalKeyboardKey.altLeft,
+ if (shift) LogicalKeyboardKey.shiftLeft,
+ ];
+ for (final modifier in mods) {
+ await tester.sendKeyDownEvent(modifier);
+ }
+ await tester.sendKeyEvent(key);
+ for (final modifier in mods.reversed) {
+ await tester.sendKeyUpEvent(modifier);
+ }
+ await tester.pump();
+}
+
+void main() {
+ test(
+ 'new defaults separate swarm selection, pane focus and terminal input',
+ () {
+ String? command(
+ String keys, [
+ KeymapContext context = KeymapContext.terminal,
+ ]) => harnessDefaultKeymap
+ .match(context, keys.split(' ').map(KeyStroke.parse))
+ .command;
+ expect(command('cmd+1'), 'swarm.select_1');
+ expect(command('cmd+9'), 'swarm.select_9');
+ expect(command('cmd+alt+1'), 'pane.focus_1');
+ expect(command('cmd+alt+left'), 'pane.focus_left');
+ expect(command('cmd+shift+enter'), 'pane.zoom');
+ expect(command('cmd+shift+p'), 'navigation.commands');
+ for (final chord in [
+ 'ctrl+tab',
+ 'ctrl+b',
+ 'alt+c',
+ 'cmd+h',
+ 'cmd+s',
+ 'cmd+b',
+ 'cmd+d',
+ 'cmd+shift+w',
+ ]) {
+ expect(command(chord), isNull, reason: chord);
+ }
+ expect(command('ctrl+n', KeymapContext.picker), 'picker.next');
+ expect(command('cmd+p', KeymapContext.picker), 'navigation.quick_open');
+ expect(command('cmd+['), 'navigation.back');
+ expect(command('cmd+[', KeymapContext.picker), 'picker.back');
+ },
+ );
+
+ test(
+ 'Mac native editing and window conflicts are rejected before activation',
+ () {
+ for (final keys in ['cmd+h', 'cmd+q', 'cmd+c', 'cmd+alt+h']) {
+ final map = ResolvedKeymap(
+ harnessDefaultBindings,
+ KeymapConfig.parse(
+ '{"bindings":[{"keys":"$keys","command":"pane.focus_left"}]}',
+ commands: harnessCommandById.keys.toSet(),
+ ),
+ );
+ expect(
+ () => AppKeymap.validateNativeKeys(map, macOS: true),
+ throwsFormatException,
+ );
+ AppKeymap.validateNativeKeys(map, macOS: false);
+ }
+ final map = ResolvedKeymap(
+ harnessDefaultBindings,
+ KeymapConfig.parse(
+ '{"bindings":[{"keys":"cmd+k cmd+c","command":"pane.focus_left"}]}',
+ commands: harnessCommandById.keys.toSet(),
+ ),
+ );
+ AppKeymap.validateNativeKeys(map, macOS: true);
+ },
+ );
+
+ testWidgets(
+ 'configured bindings dispatch before the focused owner and unbinding restores its route',
+ (tester) async {
+ final map = MemoryKeymap();
+ final focus = FocusNode();
+ final delivered = <String>[];
+ var searches = 0;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: KeymapProvider(
+ keymap: map,
+ child: KeymapHost(
+ keymap: map,
+ enabled: () => true,
+ actions: {'navigation.quick_open': () => searches++},
+ child: KeymapRegion(
+ contextKind: KeymapContext.terminal,
+ child: Focus(
+ focusNode: focus,
+ autofocus: true,
+ onKeyEvent: (_, event) {
+ final stroke = keyStrokeForEvent(event);
+ if (event is KeyDownEvent && stroke != null) {
+ delivered.add(stroke.toString());
+ }
+ return KeyEventResult.handled;
+ },
+ child: const SizedBox(width: 100, height: 100),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ expect(searches, 1);
+ expect(delivered, isEmpty);
+ await key(tester, LogicalKeyboardKey.keyB, ctrl: true);
+ await key(tester, LogicalKeyboardKey.keyC, alt: true);
+ await key(tester, LogicalKeyboardKey.tab, ctrl: true);
+ expect(delivered, ['ctrl+b', 'alt+c', 'ctrl+tab']);
+ map.apply(
+ '{"bindings":[{"keys":"cmd+p","command":null},{"keys":"ctrl+o","command":"navigation.quick_open","when":"terminal"}]}',
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ await key(tester, LogicalKeyboardKey.keyO, ctrl: true);
+ expect(searches, 2);
+ expect(delivered.last, 'cmd+p');
+ await tester.pumpWidget(const SizedBox());
+ focus.dispose();
+ map.dispose();
+ },
+ );
+
+ testWidgets(
+ 'modal picker actions stay local and respect active text composition',
+ (tester) async {
+ final map = MemoryKeymap();
+ final focus = FocusNode();
+ final text = TextEditingController(text: 'draft');
+ var selected = 0, swarms = 0;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: KeymapProvider(
+ keymap: map,
+ child: KeymapHost(
+ keymap: map,
+ enabled: () => false,
+ actions: {'swarm.new': () => swarms++},
+ child: KeymapRegion(
+ contextKind: KeymapContext.picker,
+ actions: {
+ 'picker.next': () => selected++,
+ 'picker.accept': () => selected += 10,
+ },
+ child: Material(
+ child: TextField(
+ controller: text,
+ focusNode: focus,
+ autofocus: true,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyN, ctrl: true);
+ expect(selected, 1);
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ expect(swarms, 0);
+ text.value = text.value.copyWith(
+ composing: const TextRange(start: 0, end: 5),
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(selected, 1);
+ text.clearComposing();
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(selected, 11);
+ expect(text.text, 'draft');
+ await tester.pumpWidget(const SizedBox());
+ focus.dispose();
+ text.dispose();
+ map.dispose();
+ },
+ );
+}
diff --git a/desktop/test/keymap_test.dart b/desktop/test/keymap_test.dart
index 241002bb6..489634587 100644
--- a/desktop/test/keymap_test.dart
+++ b/desktop/test/keymap_test.dart
@@ -91,7 +91,10 @@ void main() {
match(map, 'cmd+p', KeymapContext.workspace).command,
'navigation.quick_open',
);
- expect(match(map, 'cmd+p', KeymapContext.picker).matched, false);
+ expect(
+ match(map, 'cmd+p', KeymapContext.picker).command,
+ 'navigation.quick_open',
+ );
expect(match(map, 'ctrl+n', KeymapContext.picker).command, 'picker.next');
expect(match(map, 'ctrl+n', KeymapContext.terminal).matched, false);
});