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.

Enable coherent file-based keyboard customization

deebf7f37d7b643
diff --git a/desktop/lib/main.dart b/desktop/lib/main.dart
index 1b436d246..10db79eeb 100644
--- a/desktop/lib/main.dart
+++ b/desktop/lib/main.dart
@@ -22,6 +22,7 @@ import 'widgets/flash_firmware_dialog.dart';
import 'core/startup.dart';
import 'logging/app_log.dart';
import 'logging/install.dart';
+import 'shortcuts/app_keymap.dart';
import 'widgets/shortcuts_sheet.dart';
import 'widgets/update_notice.dart';
import 'widgets/window_chrome.dart';
@@ -34,14 +35,17 @@ Future<void> main() async {
CrashLog.install();
appLog.info('app', 'launched');
await loadPersistedSettings();
+ final keymap = AppKeymap(store: AppKeymap.fileStore());
+ await keymap.start();
// After the settings: the window shows itself once it is ready, and the
// first frame it shows must already wear the saved theme.
await configureDesktopWindow();
- runApp(const ProviderScope(child: DesktopApp()));
+ runApp(ProviderScope(child: DesktopApp(keymap: keymap)));
}
class DesktopApp extends StatelessWidget {
- const DesktopApp({super.key});
+ const DesktopApp({super.key, this.keymap});
+ final AppKeymap? keymap;
@override
Widget build(BuildContext context) {
@@ -108,7 +112,14 @@ class DesktopApp extends StatelessWidget {
builder: (context, child) => MediaQuery.withClampedTextScaling(
minScaleFactor: scale,
maxScaleFactor: scale,
- child: _GridTokenScope(child: child ?? const SizedBox.shrink()),
+ child: _GridTokenScope(
+ child: keymap == null
+ ? child ?? const SizedBox.shrink()
+ : KeymapProvider(
+ keymap: keymap!,
+ child: child ?? const SizedBox.shrink(),
+ ),
+ ),
),
home: const AnalyticsLifecycle(child: RootShell()),
);
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 9806ec1a9..029d9a1ad 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -12,7 +12,12 @@ import '../settings/settings_screen.dart';
import '../settings/settings_section.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shortcuts/app_shortcuts.dart';
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.dart';
import '../shortcuts/keymap_commands.dart';
+import '../shortcuts/keymap_host.dart';
+import '../shortcuts/keymap_native.dart';
+import '../shortcuts/keymap_settings.dart';
import '../state/app_state.dart';
import '../state/pane_arrangement.dart';
import '../terminal/terminal_viewport.dart';
@@ -78,16 +83,23 @@ class _SwarmScreenState extends State<SwarmScreen> {
String? _nativeState;
ModelsMenuController? _modelsMenu;
String? _modelsState;
+ final _defaultKeymap = AppKeymap();
+ AppKeymap? _providedKeymap;
+ AppKeymap get _keymap => _providedKeymap ?? _defaultKeymap;
+ String? _nativeKeyContext;
+ String _pendingKeys = '';
AppNotifier get app => widget.notifier;
@override
void initState() {
super.initState();
+ _keymap.addListener(_keymapChanged);
app.hasNavigationRail = false;
app.railFocused = false;
_recordNavigation();
app.addListener(_recordNavigation);
FocusManager.instance.addListener(_restoreEmptyFocus);
+ FocusManager.instance.addListener(_syncKeyContext);
_searchFocus.addListener(_searchFocusChanged);
grid.AppTheme.palette.addListener(_paletteChanged);
unawaited(_projects.load());
@@ -107,6 +119,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
@override
void didChangeDependencies() {
super.didChangeDependencies();
+ final keymap = KeymapTheme.of(context);
+ if (keymap != _providedKeymap) {
+ _keymap.removeListener(_keymapChanged);
+ _providedKeymap = keymap;
+ _keymap.addListener(_keymapChanged);
+ }
+ _syncKeymap();
final current = ModalRoute.isCurrentOf(context) ?? true;
if (_routeIsCurrent == current) return;
_routeIsCurrent = current;
@@ -120,9 +139,12 @@ class _SwarmScreenState extends State<SwarmScreen> {
@override
void dispose() {
+ _keymap.removeListener(_keymapChanged);
+ _defaultKeymap.dispose();
grid.AppTheme.palette.removeListener(_paletteChanged);
app.removeListener(_recordNavigation);
FocusManager.instance.removeListener(_restoreEmptyFocus);
+ FocusManager.instance.removeListener(_syncKeyContext);
_searchOverlay?.remove();
_searchOverlay?.dispose();
_search?.dispose();
@@ -146,6 +168,50 @@ class _SwarmScreenState extends State<SwarmScreen> {
super.dispose();
}
+ AppKeymap? _sentKeymap;
+ int? _sentKeymapVersion;
+ void _syncKeymap() {
+ if (!_native ||
+ (_sentKeymap == _keymap && _sentKeymapVersion == _keymap.version)) {
+ return;
+ }
+ _sentKeymap = _keymap;
+ _sentKeymapVersion = _keymap.version;
+ unawaited(
+ _channel.invokeMethod<void>('keymapState', nativeKeymapSnapshot(_keymap)),
+ );
+ }
+
+ void _keymapChanged() {
+ _syncKeymap();
+ if (mounted) setState(() {});
+ _search?.refreshCommands();
+ }
+
+ void _syncKeyContext() {
+ if (!_native) return;
+ final focus = FocusManager.instance.primaryFocus?.context;
+ final kind = focus == null
+ ? KeymapContext.workspace
+ : KeymapRegion.of(focus)?.contextKind ?? KeymapContext.workspace;
+ if (_nativeKeyContext == kind.name) return;
+ _nativeKeyContext = kind.name;
+ unawaited(
+ _channel.invokeMethod<void>('keymapContext', {'context': kind.name}),
+ );
+ }
+
+ bool get _shortcutsEnabled =>
+ mounted && _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen;
+
+ void _runShortcut(String id) {
+ if (!_canExecuteCommand(id)) return;
+ if (id != 'navigation.quick_open' && id != 'navigation.commands') {
+ _closeSearch();
+ }
+ _commands[id]?.call();
+ }
+
void _recordNavigation() {
_navigation.record(app);
if (_search != null && _search!.targetId != app.activeSwarmId) {
@@ -249,6 +315,18 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
Future<void> _onNative(MethodCall call) async {
+ if (mounted && call.method == 'keymapPending') {
+ final keys = (call.arguments as Map?)?['keys'];
+ if (keys is List &&
+ keys.length <= 4 &&
+ keys.every((key) => key is String)) {
+ final pending = keys
+ .map((key) => describeKeyStroke(KeyStroke.parse(key)))
+ .join(' ');
+ if (_pendingKeys != pending) setState(() => _pendingKeys = pending);
+ }
+ return;
+ }
if (!mounted ||
_dialogOpen ||
_spokenPaletteOpen ||
@@ -280,10 +358,25 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
return;
}
- if (call.method == 'searchCommand') {
+ if (call.method == 'keymapCommand' &&
+ !(args['command'] as String? ?? '').startsWith('picker.')) {
+ if (args['command'] is String) _runShortcut(args['command']);
+ return;
+ }
+ if (call.method == 'searchCommand' || call.method == 'keymapCommand') {
final search = _search;
if (search == null) return;
- switch (args['command']) {
+ final command =
+ const {
+ 'picker.next': 'next',
+ 'picker.previous': 'previous',
+ 'picker.preview': 'preview',
+ 'picker.accept': 'submit',
+ 'picker.add_here': 'add',
+ 'picker.cancel': 'close',
+ }[args['command']] ??
+ args['command'];
+ switch (command) {
case 'next':
search.move(1);
case 'previous':
@@ -859,8 +952,16 @@ class _SwarmScreenState extends State<SwarmScreen> {
for (final command in harnessCommands)
if (command.action != null && _actionHandlers.containsKey(command.action))
command.id: _actionHandlers[command.action]!,
+ for (var i = 1; i <= kAgentDigitCount; i++)
+ 'pane.focus_$i': () => app.focusPaneByIndex(i - 1),
+ 'navigation.commands': () {
+ _openSearch();
+ _search?.setQuery('> ');
+ _focusSearch();
+ },
'machine.link': () => _dialog(() => showSwarmLinkDialog(context, app)),
'project.add': _addProject,
+ 'keyboard.open_config': () => openKeyboardConfig(context),
'pane.resize': app.beginPaneResize,
'pane.reset_sizes': app.resetPaneSizes,
'pane.split_right': () => _splitAgent(PaneResizeAxis.x),
@@ -874,9 +975,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
_spokenPaletteOpen) {
return false;
}
- if (id == 'navigation.quick_open') {
- return false;
- }
+ if (id == 'keyboard.open_config') return _keymap.store != null;
+ if (id == 'pane.layout' || id == 'task.route') return true;
if (id == 'swarm.new') return app.swarms.length < AppNotifier.maxSwarms;
if (id == 'swarm.reopen') return app.canReopenLastClosed;
if (id == 'swarm.next' || id == 'swarm.previous') {
@@ -907,7 +1007,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
List<SwarmDestination> _searchCommands() => [
for (final command in harnessCommands)
- if (_canExecuteCommand(command.id))
+ if (command.id != 'navigation.quick_open' &&
+ command.id != 'navigation.commands' &&
+ !RegExp(r'^pane\.focus_[1-9]$').hasMatch(command.id) &&
+ _canExecuteCommand(command.id))
SwarmDestination(
id: 'command:${command.id}',
title: command.label,
@@ -915,13 +1018,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
swarmId: null,
current: false,
commandId: command.id,
- shortcut: command.keys.isEmpty
- ? null
- : describeKeyBinding(
- harnessDefaultBindings.firstWhere(
- (binding) => binding.command == command.id,
- ),
- ),
+ shortcut: _keymap.hint(command.id),
searchFields: [command.id],
),
];
@@ -937,125 +1034,169 @@ class _SwarmScreenState extends State<SwarmScreen> {
(_) => _restoreEmptyFocus(),
);
}
- return CallbackShortcuts(
- bindings: {
- ...buildShortcutBindings(
- handlers: _actionHandlers,
- onSelectPaneIndex: app.focusPaneByIndex,
- ),
- },
- child: Focus(
- focusNode: _shellFocus,
- autofocus: true,
- child: Scaffold(
- backgroundColor: grid.AppPalette.swarmField,
- body: Column(
- children: [
- if (!_native) _tabStrip(),
- if (_projects.error != null || app.lastError != null)
- Material(
- color: grid.AppPalette.panelBg,
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16),
- child: Row(
- children: [
- const Icon(
- Icons.info_outline,
- size: 16,
- color: Colors.orangeAccent,
- ),
- const SizedBox(width: 10),
- Expanded(
- child: Text(
- _projects.error ?? app.lastError!,
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: const TextStyle(fontSize: 12),
+ return KeymapProvider(
+ keymap: _keymap,
+ child: KeymapHost(
+ keymap: _keymap,
+ enabled: () => _shortcutsEnabled,
+ canExecute: _canExecuteCommand,
+ actions: {
+ for (final id in _commands.keys) id: () => _runShortcut(id),
+ },
+ onPending: (keys) => setState(() => _pendingKeys = keys),
+ child: Focus(
+ focusNode: _shellFocus,
+ autofocus: true,
+ child: Scaffold(
+ backgroundColor: grid.AppPalette.swarmField,
+ body: Column(
+ children: [
+ if (!_native) _tabStrip(),
+ if (_keymap.error != null)
+ Material(
+ color: grid.AppPalette.panelBg,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(
+ children: [
+ const Expanded(
+ child: Text(
+ 'Keyboard config has an error. Using the last working shortcuts.',
+ style: TextStyle(fontSize: 12),
+ ),
),
- ),
- if (_projects.error == null && app.lastErrorRetryable)
TextButton(
- onPressed: app.retryMachines,
- child: const Text('Retry'),
+ onPressed: () =>
+ _dialog(() => showShortcutsSheet(context)),
+ child: const Text('Details'),
),
- IconButton(
- onPressed: _projects.error != null
- ? _projects.dismissError
- : app.dismissError,
- tooltip: 'Dismiss',
- icon: const Icon(Icons.close, size: 16),
+ ],
+ ),
+ ),
+ ),
+ if (_pendingKeys.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 16,
+ vertical: 4,
+ ),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Text(
+ '$_pendingKeys … Esc to cancel',
+ style: TextStyle(
+ fontSize: 12,
+ color: grid.AppPalette.textSecondary,
),
- ],
+ ),
),
),
- ),
- Expanded(
- child: Stack(
- fit: StackFit.expand,
- children: [
- if (app.panes.isEmpty)
- const RepaintBoundary(child: SwarmWallpaper()),
- Padding(
- padding: app.panes.isEmpty
- ? EdgeInsets.zero
- : const EdgeInsets.all(10),
- child: Stack(
+ if (_projects.error != null || app.lastError != null)
+ Material(
+ color: grid.AppPalette.panelBg,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(
children: [
- Positioned.fill(
- child: PaneGrid(
- notifier: app,
- swarmMode: true,
- empty: SwarmWelcome(
- key: ValueKey(app.activeSwarmId),
+ const Icon(
+ Icons.info_outline,
+ size: 16,
+ color: Colors.orangeAccent,
+ ),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ _projects.error ?? app.lastError!,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 12),
+ ),
+ ),
+ if (_projects.error == null &&
+ app.lastErrorRetryable)
+ TextButton(
+ onPressed: app.retryMachines,
+ child: const Text('Retry'),
+ ),
+ IconButton(
+ onPressed: _projects.error != null
+ ? _projects.dismissError
+ : app.dismissError,
+ tooltip: 'Dismiss',
+ icon: const Icon(Icons.close, size: 16),
+ ),
+ ],
+ ),
+ ),
+ ),
+ Expanded(
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ if (app.panes.isEmpty)
+ const RepaintBoundary(child: SwarmWallpaper()),
+ Padding(
+ padding: app.panes.isEmpty
+ ? EdgeInsets.zero
+ : const EdgeInsets.all(10),
+ child: Stack(
+ children: [
+ Positioned.fill(
+ child: PaneGrid(
notifier: app,
- projects: _projects.projects,
- onNewAgent: _newAgent,
- onAgent: (entry) => _activateSearch(
- SwarmSearchSelection(
- SwarmDestination(
- id: agentDestinationId(
- entry.machineId,
- entry.agent.id,
+ swarmMode: true,
+ empty: SwarmWelcome(
+ key: ValueKey(app.activeSwarmId),
+ notifier: app,
+ projects: _projects.projects,
+ onNewAgent: _newAgent,
+ onAgent: (entry) => _activateSearch(
+ SwarmSearchSelection(
+ SwarmDestination(
+ id: agentDestinationId(
+ entry.machineId,
+ entry.agent.id,
+ ),
+ title: entry.agent.name,
+ detail:
+ entry.machine.machine.displayName,
+ swarmId: null,
+ current: false,
+ machineId: entry.machineId,
+ agentId: entry.agent.id,
+ engine: entry.agent.engine,
),
- title: entry.agent.name,
- detail:
- entry.machine.machine.displayName,
- swarmId: null,
- current: false,
- machineId: entry.machineId,
- agentId: entry.agent.id,
- engine: entry.agent.engine,
),
+ app.activeSwarmId,
),
- app.activeSwarmId,
- ),
- searchField: SwarmInlineSearch(
- key: ValueKey(
- 'welcome-search:${app.activeSwarmId}',
+ searchField: SwarmInlineSearch(
+ key: ValueKey(
+ 'welcome-search:${app.activeSwarmId}',
+ ),
+ app: app,
+ projects: _projects,
+ recent: _navigation.recent,
+ commands: _searchCommands,
+ onChoose: _activateSearch,
),
- app: app,
- projects: _projects,
- recent: _navigation.recent,
- commands: _searchCommands,
- onChoose: _activateSearch,
- ),
- onAddProject: _addProject,
- onLinkMachine: () => _dialog(
- () => showSwarmLinkDialog(context, app),
+ onAddProject: _addProject,
+ onLinkMachine: () => _dialog(
+ () => showSwarmLinkDialog(context, app),
+ ),
+ onMachine: _machine,
+ onProject: _project,
+ onProjectAgents: _projectAgents,
),
- onMachine: _machine,
- onProject: _project,
- onProjectAgents: _projectAgents,
),
),
- ),
- ],
+ ],
+ ),
),
- ),
- ],
+ ],
+ ),
),
- ),
- ],
+ ],
+ ),
),
),
),
@@ -1133,7 +1274,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
),
IconButton(
- tooltip: withShortcutHint('New swarm', ShortcutAction.newSwarm),
+ tooltip: withEffectiveShortcutHint(
+ context,
+ 'New swarm',
+ ShortcutAction.newSwarm,
+ ),
onPressed: app.swarms.length < AppNotifier.maxSwarms
? app.newSwarm
: null,
@@ -1194,12 +1339,24 @@ class _SwarmScreenState extends State<SwarmScreen> {
width: 36,
height: 32,
),
- suffixIcon: _search == null
- ? const Padding(
- padding: EdgeInsets.only(right: 12),
- child: Text(
- '⌘P',
- style: TextStyle(fontSize: 11),
+ suffixIcon:
+ _search == null &&
+ _keymap.hint('navigation.quick_open') !=
+ null
+ ? Padding(
+ padding: const EdgeInsets.only(right: 12),
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(
+ maxWidth: 80,
+ ),
+ child: Text(
+ _keymap.hint(
+ 'navigation.quick_open',
+ )!,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 11),
+ ),
),
)
: null,
@@ -1246,7 +1403,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
),
IconButton(
- tooltip: withShortcutHint('Settings', ShortcutAction.showSettings),
+ tooltip: withEffectiveShortcutHint(
+ context,
+ 'Settings',
+ ShortcutAction.showSettings,
+ ),
onPressed: _settings,
icon: const Icon(Icons.settings_outlined, size: 18),
),
diff --git a/desktop/lib/settings/sections/shortcuts_section.dart b/desktop/lib/settings/sections/shortcuts_section.dart
index 528182a54..7659ef840 100644
--- a/desktop/lib/settings/sections/shortcuts_section.dart
+++ b/desktop/lib/settings/sections/shortcuts_section.dart
@@ -2,6 +2,9 @@ import 'package:flutter/material.dart';
import '../../shared/widgets/section_scaffold.dart';
import '../../shortcuts/shortcuts_list.dart';
+import '../../shortcuts/app_keymap.dart';
+import '../../shortcuts/keymap.dart';
+import '../../shortcuts/keymap_settings.dart';
/// Settings ▸ Keyboard shortcuts — the same rows the ⌘/ sheet shows, in the
/// place someone looks when they don't yet know the sheet exists.
@@ -11,23 +14,43 @@ import '../../shortcuts/shortcuts_list.dart';
/// and the pane read as a dialog someone had pasted into a screen. It gets
/// [ShortcutsDeck] instead — the same rows, laid out across the room this
/// screen has.
-class ShortcutsSection extends StatelessWidget {
+class ShortcutsSection extends StatefulWidget {
const ShortcutsSection({super.key});
+ @override
+ State<ShortcutsSection> createState() => _ShortcutsSectionState();
+}
+
+class _ShortcutsSectionState extends State<ShortcutsSection> {
+ KeymapContext _contextKind = KeymapContext.workspace;
+
@override
Widget build(BuildContext context) {
+ final hint = effectiveCommandHint(context, 'keyboard.help');
return SectionScaffold(
title: 'Keyboard shortcuts',
- subtitle: 'Every key this app takes. Press ⌘/ to see them anywhere.',
+ subtitle: hint == null
+ ? 'Your current shortcuts.'
+ : 'Your current shortcuts. Press $hint to see them in your workspace.',
// A SingleChildScrollView, never a ListView — same reason as Appearance
// and Terminal: a lazy list keeps children across a rebuild and strands
// them on the palette they first mounted with.
- child: const SingleChildScrollView(
+ child: SingleChildScrollView(
child: Padding(
// Room under the last card so a scrolled-to-bottom pane does not end
// flush against the window edge.
- padding: EdgeInsets.only(bottom: 8),
- child: ShortcutsDeck(),
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ KeymapSettings(
+ contextKind: _contextKind,
+ onContextChanged: (value) =>
+ setState(() => _contextKind = value),
+ ),
+ ShortcutsDeck(contextKind: _contextKind),
+ ],
+ ),
),
),
);
diff --git a/desktop/lib/shortcuts/app_keymap.dart b/desktop/lib/shortcuts/app_keymap.dart
index 0ec8853ce..597746d67 100644
--- a/desktop/lib/shortcuts/app_keymap.dart
+++ b/desktop/lib/shortcuts/app_keymap.dart
@@ -49,7 +49,7 @@ class AppKeymap extends ChangeNotifier {
}
/// These are names of actual AppKit commands, not all system shortcuts.
- /// The second stroke of an explicit sequence can still use an editing key.
+ /// Native editing is dispatched before Flutter, including sequence suffixes.
static void validateNativeKeys(ResolvedKeymap map, {required bool macOS}) {
if (!macOS) return;
final reserved = {
@@ -67,14 +67,19 @@ class AppKeymap extends ChangeNotifier {
'cmd+alt+shift+v',
'cmd+backquote',
'cmd+shift+backquote',
+ 'cmd+0',
+ 'cmd+equal',
+ 'cmd+shift+equal',
+ 'cmd+minus',
])
KeyStroke.parse(chord),
};
for (final context in KeymapContext.values) {
for (final binding in map.bindingsFor(context)) {
- if (binding.custom && reserved.contains(binding.keys.first)) {
+ final conflict = binding.keys.where(reserved.contains).firstOrNull;
+ if (binding.custom && conflict != null) {
throw FormatException(
- '${binding.keys.first} belongs to a native Mac editing or window command; choose another first key',
+ '$conflict belongs to a native Mac editing, font or window command; choose another key',
);
}
}
@@ -164,3 +169,76 @@ String withEffectiveShortcutHint(
final hint = effectiveShortcutHint(context, action);
return hint == null ? label : '$label $hint';
}
+
+String? effectiveCommandHint(
+ BuildContext context,
+ String command, {
+ KeymapContext contextKind = KeymapContext.workspace,
+}) {
+ final bindings = (KeymapTheme.of(context)?.current ?? harnessDefaultKeymap)
+ .bindingsFor(contextKind);
+ final binding = bindings
+ .where((binding) => binding.command == command)
+ .firstOrNull;
+ return binding == null ? null : describeKeyBinding(binding);
+}
+
+List<ShortcutRow> effectiveShortcutRows(
+ BuildContext context,
+ KeymapContext contextKind,
+) {
+ final map = KeymapTheme.of(context)?.current;
+ if (map == null && contextKind == KeymapContext.workspace) {
+ return shortcutRows();
+ }
+ final bindings = (map ?? harnessDefaultKeymap).bindingsFor(contextKind);
+ final defaultDigits =
+ contextKind != KeymapContext.picker &&
+ List.generate(kAgentDigitCount, (i) {
+ final matches = bindings
+ .where((b) => b.command == 'pane.focus_${i + 1}')
+ .toList();
+ return matches.length == 1 &&
+ matches.single.keys.length == 1 &&
+ matches.single.keys.single == KeyStroke.parse('cmd+${i + 1}');
+ }).every((value) => value);
+ final shortcuts = appShortcuts();
+ return [
+ for (final command in harnessCommands)
+ if ((command.context == KeymapContext.workspace ||
+ command.context == contextKind) &&
+ (!defaultDigits ||
+ !RegExp(r'^pane\.focus_[1-9]$').hasMatch(command.id)))
+ if (command.action != null ||
+ bindings.any((b) => b.command == command.id))
+ ShortcutRow(
+ label:
+ shortcuts
+ .where((s) => s.action == command.action)
+ .firstOrNull
+ ?.label ??
+ command.label,
+ chords: [
+ for (final binding in bindings.where(
+ (b) => b.command == command.id,
+ ))
+ binding.keys.length == 1
+ ? describeKeyStrokeKeys(binding.keys.single)
+ : [
+ describeKeyBinding(binding)
+ .replaceAll('↵', 'Return')
+ .replaceAll('⇥', 'Tab'),
+ ],
+ ],
+ group: command.group,
+ ),
+ if (defaultDigits)
+ const ShortcutRow(
+ label: 'Focus the 1st–9th pane',
+ chords: [
+ ['⌘', '1 – 9'],
+ ],
+ group: ShortcutGroup.panes,
+ ),
+ ];
+}
diff --git a/desktop/lib/shortcuts/key_cap.dart b/desktop/lib/shortcuts/key_cap.dart
index 1a3b47e64..216503250 100644
--- a/desktop/lib/shortcuts/key_cap.dart
+++ b/desktop/lib/shortcuts/key_cap.dart
@@ -42,16 +42,25 @@ class KeyCap extends StatelessWidget {
// and a label squeezed to a character per line beside it.
child: Center(
widthFactor: 1,
- child: Text(
- label,
- style: TextStyle(
- color: grid.AppPalette.textPrimary,
- fontSize: 11.5,
- height: 1,
- // Tabular so ⌘1 – ⌘9 and ⌘W keep the same cap width.
- fontFeatures: const [FontFeature.tabularFigures()],
- ),
- ),
+ child: label == '⇥' || label == '↵' || label == '⏎'
+ ? Semantics(
+ label: label == '⇥' ? 'Tab' : 'Return',
+ child: Icon(
+ label == '⇥' ? Icons.keyboard_tab : Icons.keyboard_return,
+ size: 14,
+ color: grid.AppPalette.textPrimary,
+ ),
+ )
+ : Text(
+ label,
+ style: TextStyle(
+ color: grid.AppPalette.textPrimary,
+ fontSize: 11.5,
+ height: 1,
+ // Tabular so ⌘1 – ⌘9 and ⌘W keep the same cap width.
+ fontFeatures: const [FontFeature.tabularFigures()],
+ ),
+ ),
),
);
}
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index a660ae466..c1ce91a5b 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -389,7 +389,7 @@ final harnessDefaultKeymap = ResolvedKeymap(
const KeymapConfig.empty(),
);
-String describeKeyStroke(KeyStroke stroke) => [
+List<String> describeKeyStrokeKeys(KeyStroke stroke) => [
if (stroke.control) '⌃',
if (stroke.alt) '⌥',
if (stroke.shift) '⇧',
@@ -418,6 +418,8 @@ String describeKeyStroke(KeyStroke stroke) => [
'delete': '⌦',
}[stroke.key] ??
stroke.key.toUpperCase(),
-].join();
+];
+String describeKeyStroke(KeyStroke stroke) =>
+ describeKeyStrokeKeys(stroke).join();
String describeKeyBinding(KeyBinding binding) =>
binding.keys.map(describeKeyStroke).join(' ');
diff --git a/desktop/lib/shortcuts/keymap_host.dart b/desktop/lib/shortcuts/keymap_host.dart
index 9f9b18a35..5f65665e6 100644
--- a/desktop/lib/shortcuts/keymap_host.dart
+++ b/desktop/lib/shortcuts/keymap_host.dart
@@ -114,7 +114,6 @@ class _KeymapHostState extends State<KeymapHost> with WidgetsBindingObserver {
_notifyPending();
return KeyEventResult.ignored;
}
- final actions = localActions ?? widget.actions;
final value = context
.findAncestorStateOfType<EditableTextState>()
?.widget
@@ -138,12 +137,17 @@ class _KeymapHostState extends State<KeymapHost> with WidgetsBindingObserver {
composing: composing,
modifier: _modifiers.contains(event.logicalKey),
canExecute: (id) =>
- actions.containsKey(id) &&
- (localActions != null || widget.canExecute?.call(id) != false),
+ (localActions?.containsKey(id) == true ||
+ widget.actions.containsKey(id)) &&
+ (localActions?.containsKey(id) == true ||
+ (widget.enabled() && widget.canExecute?.call(id) != false)),
canRepeat: (id) => harnessCommandById[id]?.repeatable == true,
);
_notifyPending();
- if (result.command != null) actions[result.command!]?.call();
+ if (result.command != null) {
+ (localActions?[result.command!] ?? widget.actions[result.command!])
+ ?.call();
+ }
return result.handled ? KeyEventResult.handled : KeyEventResult.ignored;
}
diff --git a/desktop/lib/shortcuts/keymap_settings.dart b/desktop/lib/shortcuts/keymap_settings.dart
new file mode 100644
index 000000000..d63b50533
--- /dev/null
+++ b/desktop/lib/shortcuts/keymap_settings.dart
@@ -0,0 +1,101 @@
+import 'package:flutter/material.dart';
+import 'package:url_launcher/url_launcher.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_select_field.dart';
+import 'app_keymap.dart';
+import 'keymap.dart';
+
+Future<void> openKeyboardConfig(BuildContext context) async {
+ final store = KeymapTheme.of(context, listen: false)?.store;
+ if (store == null) return;
+ try {
+ final file = await store.ensureFile();
+ if (!await launchUrl(file.uri)) {
+ throw StateError(
+ 'No editor is associated with .jsonc files. Open ${file.path} in your editor.',
+ );
+ }
+ } catch (error) {
+ if (context.mounted) {
+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(
+ SnackBar(content: Text('Couldn’t open keyboard config. $error')),
+ );
+ }
+ }
+}
+
+class KeymapSettings extends StatelessWidget {
+ const KeymapSettings({
+ super.key,
+ required this.contextKind,
+ required this.onContextChanged,
+ });
+ final KeymapContext contextKind;
+ final ValueChanged<KeymapContext> onContextChanged;
+
+ @override
+ Widget build(BuildContext context) {
+ final keymap = KeymapTheme.of(context);
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Wrap(
+ spacing: 12,
+ runSpacing: 8,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ AppSelectField<KeymapContext>(
+ value: contextKind,
+ width: 160,
+ options: const [
+ SelectOption(
+ value: KeymapContext.workspace,
+ label: 'Workspace',
+ ),
+ SelectOption(
+ value: KeymapContext.terminal,
+ label: 'Agent input',
+ ),
+ SelectOption(value: KeymapContext.picker, label: 'Search'),
+ ],
+ onChanged: onContextChanged,
+ ),
+ if (keymap?.store != null)
+ TextButton.icon(
+ onPressed: () => openKeyboardConfig(context),
+ icon: const Icon(Icons.edit_outlined, size: 16),
+ label: const Text('Edit keyboard config'),
+ style: TextButton.styleFrom(
+ foregroundColor: grid.AppPalette.textPrimary,
+ ),
+ ),
+ ],
+ ),
+ if (keymap?.path != null) ...[
+ const SizedBox(height: 8),
+ Text(
+ 'Saves apply automatically. Invalid edits keep your last working shortcuts.',
+ style: TextStyle(
+ color: grid.AppPalette.textSecondary,
+ fontSize: 12,
+ ),
+ ),
+ const SizedBox(height: 4),
+ SelectableText(
+ keymap!.path!,
+ style: TextStyle(color: grid.AppPalette.textFaint, fontSize: 11),
+ ),
+ ],
+ if (keymap?.error != null) ...[
+ const SizedBox(height: 8),
+ SelectableText(
+ keymap!.error!,
+ style: const TextStyle(color: Colors.orangeAccent, fontSize: 12),
+ ),
+ ],
+ const SizedBox(height: 16),
+ ],
+ );
+ }
+}
diff --git a/desktop/lib/shortcuts/keymap_store.dart b/desktop/lib/shortcuts/keymap_store.dart
index 37e16029a..baee76bb0 100644
--- a/desktop/lib/shortcuts/keymap_store.dart
+++ b/desktop/lib/shortcuts/keymap_store.dart
@@ -271,14 +271,21 @@ class KeymapStore extends ChangeNotifier {
if (await handle.length() == 0) {
await handle.writeString(
'''// Harness keyboard overrides. Defaults are inherited.
-// Use command names from Keyboard Shortcuts / the command picker.
+// Save this file to apply changes. Invalid edits keep the last working keys.
// A null command unbinds a key or a sequence prefix.
+// "when" can be "workspace" (default), "terminal", or "picker".
+// Workspace bindings are inherited by the other two contexts.
{
"version": 1,
"bindings": [
- // { "keys": "cmd+ctrl+h", "command": "pane.focus_left", "when": "terminal" },
+ // Example: move search from Command-P to Command-O.
+ // { "keys": "cmd+p", "command": null },
+ // { "keys": "cmd+o", "command": "navigation.quick_open" },
],
}
+
+// Available command names:
+${(_commands.toList()..sort()).map((id) => '// $id').join('\n')}
''',
);
await handle.flush();
diff --git a/desktop/lib/shortcuts/shortcuts_list.dart b/desktop/lib/shortcuts/shortcuts_list.dart
index a582211da..a0598204e 100644
--- a/desktop/lib/shortcuts/shortcuts_list.dart
+++ b/desktop/lib/shortcuts/shortcuts_list.dart
@@ -4,6 +4,8 @@ import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart' as grid;
import 'app_shortcuts.dart';
+import 'app_keymap.dart';
+import 'keymap.dart';
import 'key_cap.dart';
/// Every shortcut, grouped and printed — in the two shapes the app needs.
@@ -19,11 +21,12 @@ import 'key_cap.dart';
/// The sheet's body: one column, group headers, no card chrome — it is already
/// inside a dialog, and a card in a card is one surface too many.
class ShortcutsList extends StatelessWidget {
- const ShortcutsList({super.key});
+ const ShortcutsList({super.key, this.contextKind = KeymapContext.workspace});
+ final KeymapContext contextKind;
@override
Widget build(BuildContext context) {
- final rows = shortcutRows();
+ final rows = effectiveShortcutRows(context, contextKind);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@@ -49,7 +52,8 @@ class ShortcutsList extends StatelessWidget {
/// screenful — which is the only reason to open this screen rather than the
/// sheet.
class ShortcutsDeck extends StatelessWidget {
- const ShortcutsDeck({super.key});
+ const ShortcutsDeck({super.key, this.contextKind = KeymapContext.workspace});
+ final KeymapContext contextKind;
/// Narrower than this and a label wraps under its own keycaps. Public so the
/// deck's tests can render a card at exactly the width it is least able to
@@ -69,7 +73,7 @@ class ShortcutsDeck extends StatelessWidget {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- final rows = shortcutRows();
+ final rows = effectiveShortcutRows(context, contextKind);
final cards = <Widget>[
for (final group in ShortcutGroup.values)
_ShortcutCard(
@@ -338,7 +342,15 @@ class _ShortcutRowView extends StatelessWidget {
constraints: BoxConstraints(
maxWidth: math.max(0, constraints.maxWidth - _gutter),
),
- child: KeyChordView(chords: row.chords),
+ child: row.chords.isEmpty
+ ? Text(
+ 'Unassigned',
+ style: TextStyle(
+ color: grid.AppPalette.textFaint,
+ fontSize: 11.5,
+ ),
+ )
+ : KeyChordView(chords: row.chords),
),
],
),
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 746060842..7dbe7a93a 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -95,6 +95,12 @@ class SwarmSearchController extends ChangeNotifier {
notifyListeners();
}
+ void refreshCommands() {
+ if (!isCommandMode) return;
+ _filter();
+ notifyListeners();
+ }
+
void _filter() {
final availableCommands = isCommandMode
? commands?.call() ?? const <SwarmDestination>[]
diff --git a/desktop/lib/widgets/shortcuts_sheet.dart b/desktop/lib/widgets/shortcuts_sheet.dart
index 9fa0750d3..3ea5b1c1f 100644
--- a/desktop/lib/widgets/shortcuts_sheet.dart
+++ b/desktop/lib/widgets/shortcuts_sheet.dart
@@ -3,6 +3,8 @@ import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
import '../shortcuts/shortcuts_list.dart';
+import '../shortcuts/keymap.dart';
+import '../shortcuts/keymap_settings.dart';
/// The ⌘/ sheet — [ShortcutsList] in a dialog.
///
@@ -15,9 +17,16 @@ Future<void> showShortcutsSheet(BuildContext context) {
);
}
-class _ShortcutsSheet extends StatelessWidget {
+class _ShortcutsSheet extends StatefulWidget {
const _ShortcutsSheet();
+ @override
+ State<_ShortcutsSheet> createState() => _ShortcutsSheetState();
+}
+
+class _ShortcutsSheetState extends State<_ShortcutsSheet> {
+ KeymapContext _contextKind = KeymapContext.workspace;
+
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
@@ -46,7 +55,17 @@ class _ShortcutsSheet extends StatelessWidget {
Flexible(
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(18, 8, 18, 16),
- child: const ShortcutsList(),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ KeymapSettings(
+ contextKind: _contextKind,
+ onContextChanged: (value) =>
+ setState(() => _contextKind = value),
+ ),
+ ShortcutsList(contextKind: _contextKind),
+ ],
+ ),
),
),
Container(
@@ -59,6 +78,9 @@ class _ShortcutsSheet extends StatelessWidget {
alignment: Alignment.centerRight,
child: TextButton(
onPressed: () => Navigator.of(context).pop(),
+ style: TextButton.styleFrom(
+ foregroundColor: grid.AppPalette.textSecondary,
+ ),
child: const Text('Close'),
),
),
diff --git a/desktop/lib/widgets/swarm_inline_search.dart b/desktop/lib/widgets/swarm_inline_search.dart
index a99440ffd..dcf5151e1 100644
--- a/desktop/lib/widgets/swarm_inline_search.dart
+++ b/desktop/lib/widgets/swarm_inline_search.dart
@@ -2,6 +2,8 @@ import 'dart:math' as math;
import 'package:flutter/material.dart';
+import '../shortcuts/app_keymap.dart';
+
import '../shared/theme/app_theme.dart' as grid;
import '../state/app_state.dart';
import '../state/swarm_catalog.dart';
@@ -37,6 +39,7 @@ class _SwarmInlineSearchState extends State<SwarmInlineSearch> {
final _overlay = OverlayPortalController();
final _tapGroup = Object();
SwarmSearchController? _search;
+ AppKeymap? _keymap;
@override
void initState() {
@@ -45,9 +48,25 @@ class _SwarmInlineSearchState extends State<SwarmInlineSearch> {
}
void _focusChanged() {
- if (!_focus.hasFocus) _close();
+ if (_focus.hasFocus) {
+ _begin();
+ } else {
+ _close();
+ }
}
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ final next = KeymapTheme.of(context);
+ if (next == _keymap) return;
+ _keymap?.removeListener(_keymapChanged);
+ _keymap = next;
+ _keymap?.addListener(_keymapChanged);
+ }
+
+ void _keymapChanged() => _search?.refreshCommands();
+
void _begin() {
if (_search != null) return;
_search = SwarmSearchController(
@@ -82,6 +101,7 @@ class _SwarmInlineSearchState extends State<SwarmInlineSearch> {
@override
void dispose() {
+ _keymap?.removeListener(_keymapChanged);
_search?.removeListener(_changed);
_search?.dispose();
_focus.removeListener(_focusChanged);
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index 5f8964751..97b6e0f54 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -1,6 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.dart';
+
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
import '../state/app_state.dart';
@@ -130,6 +133,31 @@ class SwarmSearchKeys extends StatelessWidget {
final choice = add ? search?.addHere() : search?.submit();
if (choice != null) onChoose(choice);
});
+ if (KeymapTheme.of(context) != null) {
+ return KeymapRegion(
+ contextKind: KeymapContext.picker,
+ composing: composing,
+ actions: {
+ if (search != null) ...{
+ 'picker.accept': () => choose(false),
+ 'picker.add_here': () => choose(true),
+ 'picker.next': () => search.move(1),
+ 'picker.previous': () => search.move(-1),
+ 'picker.preview': search.togglePreview,
+ 'picker.cancel': onClose,
+ if (search.history == null)
+ 'navigation.commands': () {
+ editing.value = const TextEditingValue(
+ text: '> ',
+ selection: TextSelection.collapsed(offset: 2),
+ );
+ search.setQuery('> ');
+ },
+ },
+ },
+ child: child,
+ );
+ }
return CallbackShortcuts(
bindings: search == null
? {}
@@ -283,6 +311,21 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
@override
Widget build(BuildContext context) {
final scale = MediaQuery.textScalerOf(context);
+ String? hint(String command) => effectiveCommandHint(
+ context,
+ command,
+ contextKind: KeymapContext.picker,
+ );
+ final previewHint = hint('picker.preview');
+ final movementHints = [
+ hint('picker.previous'),
+ hint('picker.next'),
+ ].whereType<String>().join(' ');
+ final cancelHint = hint('picker.cancel');
+ final navigationHint = [
+ if (movementHints.isNotEmpty) '$movementHints choose',
+ if (cancelHint != null) '$cancelHint close',
+ ].join(' · ');
_rowHeight = swarmSearchRowHeight(scale, commands: search.isCommandMode);
final selected = search.selected;
return LayoutBuilder(
@@ -408,7 +451,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
? 'Opens in ${search.targetName}'
: search.query.isEmpty && search.commands != null
? 'Type > for commands'
- : '↑↓ choose · Esc close',
+ : navigationHint,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
@@ -421,9 +464,8 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
if (search.canPreview ||
search.previewEnabled && !search.isCommandMode)
Tooltip(
- message: search.previewEnabled
- ? 'Hide preview (⌘I)'
- : 'Preview recent output (⌘I)',
+ message:
+ '${search.previewEnabled ? 'Hide preview' : 'Preview recent output'}${previewHint == null ? '' : ' ($previewHint)'}',
child: IconButton(
key: const ValueKey('swarm-search-preview-toggle'),
onPressed: () {
@@ -450,7 +492,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
),
child: const _SearchActionLabel(
'Add to this swarm',
- command: true,
+ command: 'picker.add_here',
),
),
TextButton(
@@ -473,20 +515,47 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
}
class _SearchActionLabel extends StatelessWidget {
- const _SearchActionLabel(this.label, {this.command = false});
+ const _SearchActionLabel(this.label, {this.command = 'picker.accept'});
final String label;
- final bool command;
+ final String command;
@override
- Widget build(BuildContext context) => Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(label, style: const TextStyle(fontSize: 11)),
- const SizedBox(width: 8),
- if (command) const Text('⌘', style: TextStyle(fontSize: 11)),
- const Icon(Icons.keyboard_return, size: 14),
- ],
- );
+ Widget build(BuildContext context) {
+ final hint = effectiveCommandHint(
+ context,
+ command,
+ contextKind: KeymapContext.picker,
+ );
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(label, style: const TextStyle(fontSize: 11)),
+ if (hint != null) ...[
+ const SizedBox(width: 8),
+ if (RegExp(r'^[⌃⌥⇧⌘]*↵$').hasMatch(hint)) ...[
+ if (hint.length > 1)
+ Text(
+ hint.substring(0, hint.length - 1),
+ style: const TextStyle(fontSize: 11),
+ ),
+ const Icon(Icons.keyboard_return, size: 14),
+ ] else
+ Tooltip(
+ message: hint,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 96),
+ child: Text(
+ hint.replaceAll('↵', 'Return').replaceAll('⇥', 'Tab'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 11),
+ ),
+ ),
+ ),
+ ],
+ ],
+ );
+ }
}
class _OutputPreview extends StatelessWidget {
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index 276a1412e..8708b527c 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -14,6 +14,8 @@ import '../state/app_state.dart';
import 'agent_drag.dart';
import 'rename_agent_dialog.dart';
import 'terminal_composer.dart';
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.dart';
import 'terminal_find_bar.dart';
import '../terminal/terminal_search.dart';
import '../terminal/terminal_snapshot.dart';
@@ -1016,174 +1018,182 @@ class _TerminalPanelState extends State<TerminalPanel>
final machineState = widget.notifier.stateOf(session.machineId);
final remote = machineState != null && !machineState.isLocalMachine;
final showComposer = _showsComposer;
- return ColoredBox(
- color: grid.AppPalette.windowBg,
- child: Column(
- children: [
- Stack(
- children: [
- Visibility(
- visible: _find == null,
- maintainSize: true,
- maintainAnimation: true,
- maintainState: true,
- child: _buildHeader(context, remote: remote),
- ),
- if (_find != null)
- Positioned.fill(
- child: LayoutBuilder(
- builder: (context, constraints) => Row(
- children: [
- if (constraints.maxWidth > 520)
- Expanded(
+ return KeymapRegion(
+ contextKind: KeymapContext.terminal,
+ composing: () =>
+ _focusNode.hasFocus &&
+ _terminalViewKey.currentState?.isComposing == true,
+ child: ColoredBox(
+ color: grid.AppPalette.windowBg,
+ child: Column(
+ children: [
+ Stack(
+ children: [
+ Visibility(
+ visible: _find == null,
+ maintainSize: true,
+ maintainAnimation: true,
+ maintainState: true,
+ child: _buildHeader(context, remote: remote),
+ ),
+ if (_find != null)
+ Positioned.fill(
+ child: LayoutBuilder(
+ builder: (context, constraints) => Row(
+ children: [
+ if (constraints.maxWidth > 520)
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: _stripPadding,
+ ),
+ child: Text(
+ session.agentName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(
+ fontSize: 13,
+ color: Colors.white70,
+ ),
+ ),
+ ),
+ )
+ else
+ const Spacer(),
+ SizedBox(
+ width: math.min(constraints.maxWidth, 380),
child: Padding(
padding: const EdgeInsets.symmetric(
- horizontal: _stripPadding,
+ horizontal: 6,
+ vertical: 4,
),
- child: Text(
- session.agentName,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: const TextStyle(
- fontSize: 13,
- color: Colors.white70,
- ),
+ child: TerminalFindBar(
+ key: _findBarKey,
+ search: _find!,
+ readOnly:
+ widget.readOnly || !session.acceptsInput,
+ onQuery: _queryFind,
+ onStep: _stepFind,
+ onClose: _closeFind,
+ onFocus: () => widget.onRendererFocus?.call(),
),
),
- )
- else
- const Spacer(),
- SizedBox(
- width: math.min(constraints.maxWidth, 380),
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 6,
- vertical: 4,
- ),
- child: TerminalFindBar(
- key: _findBarKey,
- search: _find!,
- readOnly:
- widget.readOnly || !session.acceptsInput,
- onQuery: _queryFind,
- onStep: _stepFind,
- onClose: _closeFind,
- onFocus: () => widget.onRendererFocus?.call(),
- ),
),
- ),
- ],
+ ],
+ ),
),
),
- ),
- ],
- ),
+ ],
+ ),
- Divider(height: 1, color: AppColors.border),
- Expanded(
- child: Stack(
- children: [
- Positioned.fill(
- child: MouseRegion(
- onEnter: (event) => _hoverLink(event.position),
- onHover: (event) => _hoverLink(event.position),
- onExit: (_) => _hoverLink(null),
- child: Tooltip(
- message: _hoveredLink == null
- ? ''
- : '${defaultTargetPlatform == TargetPlatform.macOS ? '⌘' : 'Ctrl'}-click to open\n$_hoveredLink',
- child: TerminalView(
- session.terminal,
- key: _terminalViewKey,
- controller: _controller,
- autoResize: widget.visible,
- renderingEnabled: widget.visible,
- scrollController: _scrollController,
- focusNode: _focusNode,
- autofocus: widget.focused && !showComposer,
- readOnly: widget.readOnly || !session.acceptsInput,
- theme: terminalThemeFor(grid.AppTheme.palette.value),
- padding: const EdgeInsets.all(10),
- textStyle: terminalFontStore.value,
- // ⚠️ The terminal is NOT app chrome, and the user said so:
- // it carries its own font settings (Settings ▸ Terminal,
- // [terminalFontStore]) precisely because its type is a grid
- // a remote program is drawing into, not a label.
- //
- // Without this, `TerminalView` falls back to
- // `MediaQuery.textScalerOf(context)` (xterm's
- // terminal_view.dart:257), so the app-wide UI size would
- // change the cell size — and a changed cell size is not
- // cosmetic here: it re-derives `rows`, which fires
- // `Terminal.resize` → `session.resize` → a `terminal_resize`
- // frame on the wire and a real SIGWINCH at the far end.
- //
- // Read in `createRenderObject`, not only on update, so this
- // holds from the very first frame — no scaled first paint
- // and no startup resize.
- textScaler: TextScaler.noScaling,
- onKeyEvent: _onTerminalKey,
- onTapDown: _onLinkTapDown,
- onTapUp: _onLinkTapUp,
- mouseCursor:
- _hoveredLink != null && _linkModifierPressed
- ? SystemMouseCursors.click
- : SystemMouseCursors.text,
- onSecondaryTapDown: (_, _) => _copyOrPaste(),
-
- onAltBufferScroll: session.scrollViaTmuxCopyMode
- ? (up) => session.sendScrollCommand(up, 1)
- : null,
+ Divider(height: 1, color: AppColors.border),
+ Expanded(
+ child: Stack(
+ children: [
+ Positioned.fill(
+ child: MouseRegion(
+ onEnter: (event) => _hoverLink(event.position),
+ onHover: (event) => _hoverLink(event.position),
+ onExit: (_) => _hoverLink(null),
+ child: Tooltip(
+ message: _hoveredLink == null
+ ? ''
+ : '${defaultTargetPlatform == TargetPlatform.macOS ? '⌘' : 'Ctrl'}-click to open\n$_hoveredLink',
+ child: TerminalView(
+ session.terminal,
+ key: _terminalViewKey,
+ controller: _controller,
+ autoResize: widget.visible,
+ renderingEnabled: widget.visible,
+ scrollController: _scrollController,
+ focusNode: _focusNode,
+ autofocus: widget.focused && !showComposer,
+ readOnly: widget.readOnly || !session.acceptsInput,
+ theme: terminalThemeFor(grid.AppTheme.palette.value),
+ padding: const EdgeInsets.all(10),
+ textStyle: terminalFontStore.value,
+ // ⚠️ The terminal is NOT app chrome, and the user said so:
+ // it carries its own font settings (Settings ▸ Terminal,
+ // [terminalFontStore]) precisely because its type is a grid
+ // a remote program is drawing into, not a label.
+ //
+ // Without this, `TerminalView` falls back to
+ // `MediaQuery.textScalerOf(context)` (xterm's
+ // terminal_view.dart:257), so the app-wide UI size would
+ // change the cell size — and a changed cell size is not
+ // cosmetic here: it re-derives `rows`, which fires
+ // `Terminal.resize` → `session.resize` → a `terminal_resize`
+ // frame on the wire and a real SIGWINCH at the far end.
+ //
+ // Read in `createRenderObject`, not only on update, so this
+ // holds from the very first frame — no scaled first paint
+ // and no startup resize.
+ textScaler: TextScaler.noScaling,
+ onKeyEvent: _onTerminalKey,
+ onTapDown: _onLinkTapDown,
+ onTapUp: _onLinkTapUp,
+ mouseCursor:
+ _hoveredLink != null && _linkModifierPressed
+ ? SystemMouseCursors.click
+ : SystemMouseCursors.text,
+ onSecondaryTapDown: (_, _) => _copyOrPaste(),
+
+ onAltBufferScroll: session.scrollViaTmuxCopyMode
+ ? (up) => session.sendScrollCommand(up, 1)
+ : null,
+ ),
),
),
),
- ),
- if (session.uploadProgress != null || _previewProgress != null)
- Positioned(
- left: 14,
- right: 14,
- bottom: 12,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- if (session.uploadProgress != null)
- _TransferProgressBadge(
- label: 'Uploading ${session.uploadProgress!.label}',
- fraction: session.uploadProgress!.percent,
- onCancel: () => unawaited(session.cancelUpload()),
- ),
- if (session.uploadProgress != null &&
- _previewProgress != null)
- const SizedBox(height: 8),
- if (_previewProgress != null)
- _TransferProgressBadge(
- label: _previewProgress!.totalBytes == null
- ? 'Preparing preview…'
- : 'Downloading ${_previewProgress!.filename}',
- fraction: _previewProgress!.fraction,
- onCancel: () => _previewCancellation?.cancel(),
- ),
- ],
+ if (session.uploadProgress != null ||
+ _previewProgress != null)
+ Positioned(
+ left: 14,
+ right: 14,
+ bottom: 12,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (session.uploadProgress != null)
+ _TransferProgressBadge(
+ label:
+ 'Uploading ${session.uploadProgress!.label}',
+ fraction: session.uploadProgress!.percent,
+ onCancel: () => unawaited(session.cancelUpload()),
+ ),
+ if (session.uploadProgress != null &&
+ _previewProgress != null)
+ const SizedBox(height: 8),
+ if (_previewProgress != null)
+ _TransferProgressBadge(
+ label: _previewProgress!.totalBytes == null
+ ? 'Preparing preview…'
+ : 'Downloading ${_previewProgress!.filename}',
+ fraction: _previewProgress!.fraction,
+ onCancel: () => _previewCancellation?.cancel(),
+ ),
+ ],
+ ),
),
- ),
- ],
- ),
- ),
- // The grip is shown whether or not the box is: collapsed, it is the only way back.
- if (!widget.compactHeader &&
- remote &&
- widget.onToggleComposer != null)
- ComposerGrip(
- expanded: widget.composerVisible,
- onPressed: widget.onToggleComposer!,
- ),
- if (showComposer)
- TerminalComposer(
- session: session,
- focusNode: _composerFocus,
- inputEnabled: !widget.readOnly,
+ ],
+ ),
),
- ],
+ // The grip is shown whether or not the box is: collapsed, it is the only way back.
+ if (!widget.compactHeader &&
+ remote &&
+ widget.onToggleComposer != null)
+ ComposerGrip(
+ expanded: widget.composerVisible,
+ onPressed: widget.onToggleComposer!,
+ ),
+ if (showComposer)
+ TerminalComposer(
+ session: session,
+ focusNode: _composerFocus,
+ inputEnabled: !widget.readOnly,
+ ),
+ ],
+ ),
),
);
}
diff --git a/desktop/macos/Runner/HarnessKeymap.swift b/desktop/macos/Runner/HarnessKeymap.swift
index 0dba62382..4770fc593 100644
--- a/desktop/macos/Runner/HarnessKeymap.swift
+++ b/desktop/macos/Runner/HarnessKeymap.swift
@@ -41,6 +41,15 @@ struct HarnessKeyStroke: Hashable {
hasher.combine(modifiers.rawValue)
}
+ var canonical: String {
+ var parts: [String] = []
+ if modifiers.contains(.control) { parts.append("ctrl") }
+ if modifiers.contains(.option) { parts.append("alt") }
+ if modifiers.contains(.command) { parts.append("cmd") }
+ if modifiers.contains(.shift) { parts.append("shift") }
+ return (parts + [key]).joined(separator: "+")
+ }
+
private static func validKey(_ key: String) -> Bool {
if named.contains(key) { return true }
if key.count == 1, let value = key.unicodeScalars.first?.value {
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index 8f873b713..f7ad79036 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -28,6 +28,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
private var flutterKeyContext = "workspace"
private var searchKeyDispatch: HarnessNativeKeyDispatch?
private var searchKeyMonitor: Any?
+ private var pendingKeyNames: [String] = []
init(window: NSWindow, messenger: FlutterBinaryMessenger) {
self.window = window
@@ -35,9 +36,10 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
super.init()
strip.emit = { [weak self] method, args in self?.channel.invokeMethod(method, arguments: args) }
strip.editingEnded = { [weak self] in
- self?.searchKeyDispatch?.cancel()
+ self?.cancelKeySequence()
self?.syncMenuKeys()
}
+ strip.editingBegan = { [weak self] in self?.syncMenuKeys() }
channel.setMethodCallHandler { [weak self] call, result in
guard let self else { result(nil); return }
switch call.method {
@@ -47,7 +49,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
case "update":
let state = call.arguments as? [String: Any] ?? [:]
self.actionsEnabled = state["enabled"] as? Bool == true
- if !self.actionsEnabled { self.searchKeyDispatch?.cancel() }
+ if !self.actionsEnabled { self.cancelKeySequence() }
self.canReopen = state["canReopen"] as? Bool == true
self.canFind = state["canFind"] as? Bool == true
self.canClosePane = state["canClosePane"] as? Bool == true
@@ -65,7 +67,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
self.strip.setSearchState(call.arguments as? [String: Any] ?? [:])
result(nil)
case "closeSearch":
- self.searchKeyDispatch?.cancel()
+ self.cancelKeySequence()
self.strip.closeSearch()
self.syncMenuKeys()
result(nil)
@@ -100,7 +102,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
// Keep an in-progress search and its native input owner across app switches.
// Cancelling on window blur would return the next typed key to an agent.
observers.append(NotificationCenter.default.addObserver(forName: NSWindow.didResignKeyNotification,
- object: window, queue: .main) { [weak self] _ in self?.searchKeyDispatch?.suspend() })
+ object: window, queue: .main) { [weak self] _ in self?.cancelKeySequence(suspend: true) })
observers.append(NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification,
object: window, queue: .main) { [weak self] _ in self?.removeKeyMonitor() })
}
@@ -113,13 +115,27 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
private func removeKeyMonitor() {
if let searchKeyMonitor { NSEvent.removeMonitor(searchKeyMonitor) }
searchKeyMonitor = nil
- searchKeyDispatch?.suspend()
+ cancelKeySequence(suspend: true)
+ }
+
+ private func cancelKeySequence(suspend: Bool = false) {
+ if suspend { searchKeyDispatch?.suspend() }
+ else { searchKeyDispatch?.cancel() }
+ syncPendingKeys()
+ }
+
+ private func syncPendingKeys() {
+ let names = searchKeyDispatch?.pending.map(\.canonical) ?? []
+ guard names != pendingKeyNames else { return }
+ pendingKeyNames = names
+ channel.invokeMethod("keymapPending", arguments: ["keys": names])
}
private func setKeymap(_ map: HarnessNativeKeymap) {
keymap = map
if let searchKeyDispatch { searchKeyDispatch.update(map) }
else { searchKeyDispatch = HarnessNativeKeyDispatch(map) }
+ syncPendingKeys()
strip.searchField.usesKeymap = true
strip.searchField.shortcutHint = map.hint(for: "navigation.quick_open", context: "workspace")
if let main = NSApp.mainMenu, let window {
@@ -142,7 +158,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
private func handleSearchKey(_ event: NSEvent) -> NSEvent? {
guard let dispatch = searchKeyDispatch else { return event }
if event.type == .leftMouseDown || event.type == .rightMouseDown {
- dispatch.cancel()
+ cancelKeySequence()
return event
}
guard let window, event.window === window else { return event }
@@ -152,11 +168,12 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
guard actionsEnabled, strip.searchField.searching,
let editor = strip.searchField.currentEditor() as? NSTextView,
window.firstResponder === editor else {
- dispatch.cancel()
+ cancelKeySequence()
return event
}
let result = dispatch.dispatch(HarnessKeyStroke.fromEvent(event), keyCode: event.keyCode,
repeated: event.isARepeat, composing: editor.hasMarkedText(), context: "picker", owner: editor)
+ syncPendingKeys()
if let command = result.command {
if command == "navigation.quick_open" { editor.selectAll(nil) }
else { channel.invokeMethod("keymapCommand", arguments: ["command": command]) }
@@ -807,6 +824,7 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
private(set) var palette = SwarmNativePalette()
var emit: ((String, Any?) -> Void)?
var editingEnded: (() -> Void)?
+ var editingBegan: (() -> Void)?
private let scroll = NSScrollView()
private let document = NSView()
private let newButton = NSButton()
@@ -983,6 +1001,7 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
emit?("searchChanged", ["query": searchField.stringValue])
}
func controlTextDidEndEditing(_ notification: Notification) { editingEnded?() }
+ func controlTextDidBeginEditing(_ notification: Notification) { editingBegan?() }
func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool {
if searchField.usesKeymap { return false }
let event = NSApp.currentEvent
diff --git a/desktop/test/keymap_host_test.dart b/desktop/test/keymap_host_test.dart
index 3caaecc2a..a27b41fa9 100644
--- a/desktop/test/keymap_host_test.dart
+++ b/desktop/test/keymap_host_test.dart
@@ -96,7 +96,16 @@ void main() {
test(
'Mac native editing and window conflicts are rejected before activation',
() {
- for (final keys in ['cmd+q', 'cmd+c', 'cmd+alt+h']) {
+ for (final keys in [
+ 'cmd+q',
+ 'cmd+c',
+ 'cmd+alt+h',
+ 'cmd+equal',
+ 'cmd+shift+equal',
+ 'cmd+0',
+ 'cmd+minus',
+ 'f6 cmd+c',
+ ]) {
final map = ResolvedKeymap(
harnessDefaultBindings,
KeymapConfig.parse(
@@ -113,7 +122,7 @@ void main() {
final map = ResolvedKeymap(
harnessDefaultBindings,
KeymapConfig.parse(
- '{"bindings":[{"keys":"cmd+h","command":"pane.focus_left"},{"keys":"cmd+k","command":null},{"keys":"cmd+k cmd+c","command":"pane.focus_right"}]}',
+ '{"bindings":[{"keys":"cmd+h","command":"pane.focus_left"},{"keys":"cmd+k","command":null},{"keys":"cmd+k c","command":"pane.focus_right"}]}',
commands: harnessCommandById.keys.toSet(),
),
);
diff --git a/desktop/test/keymap_runtime_test.dart b/desktop/test/keymap_runtime_test.dart
new file mode 100644
index 000000000..2f5606701
--- /dev/null
+++ b/desktop/test/keymap_runtime_test.dart
@@ -0,0 +1,326 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/settings/sections/shortcuts_section.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap.dart';
+import 'package:harness/shortcuts/shortcuts_list.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/swarm_catalog.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+import 'package:xterm/xterm.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+const nativeChannel = MethodChannel('harness/swarm_tabs');
+
+Future<void> mount(
+ WidgetTester tester,
+ AppNotifier app,
+ AppKeymap keymap, {
+ bool native = false,
+}) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 800);
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ final projects = SwarmProjectStore();
+ addTearDown(projects.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (_, child) => KeymapProvider(keymap: keymap, child: child!),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: native,
+ projectStore: projects,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+}
+
+Future<void> native(WidgetTester tester, String method, [Object? arguments]) {
+ final done = Completer<void>();
+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(
+ nativeChannel.name,
+ const StandardMethodCodec().encodeMethodCall(MethodCall(method, arguments)),
+ (_) => done.complete(),
+ );
+ return done.future;
+}
+
+void main() {
+ testWidgets(
+ 'remaps, unbinding and sequences control the actual focused agent without leaking input',
+ (tester) async {
+ final map = MemoryKeymap();
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ final firstInput = <TerminalBinaryFrame>[],
+ secondInput = <TerminalBinaryFrame>[];
+ final first = app.adoptSessionForTest(terminal('a0', firstInput));
+ final second = app.adoptSessionForTest(terminal('a1', secondInput));
+ await mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.digit1, cmd: true);
+ expect(app.focusedPaneId, first.id);
+ await key(tester, LogicalKeyboardKey.keyL, cmd: true);
+ expect(app.focusedPaneId, second.id);
+ map.apply('''{"bindings":[
+ {"keys":"cmd+h","command":null,"when":"terminal"},
+ {"keys":"ctrl+g","command":"pane.focus_left","when":"terminal"},
+ {"keys":"cmd+k","command":null},
+ {"keys":"cmd+k n","command":"pane.focus_right"}
+ ]}''');
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyH, cmd: true);
+ expect(app.focusedPaneId, second.id, reason: 'No hardcoded H fallback');
+ await key(tester, LogicalKeyboardKey.keyG, ctrl: true);
+ expect(app.focusedPaneId, first.id);
+ expect(firstInput, isEmpty);
+ expect(secondInput, isEmpty);
+ await key(tester, LogicalKeyboardKey.keyK, cmd: true);
+ expect(find.text('⌘K … Esc to cancel'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(find.text('⌘K … Esc to cancel'), findsNothing);
+ expect(
+ firstInput,
+ isEmpty,
+ reason: 'A failed sequence is never agent input',
+ );
+ await key(tester, LogicalKeyboardKey.keyK, cmd: true);
+ await key(tester, LogicalKeyboardKey.keyN);
+ expect(app.focusedPaneId, second.id);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ expect(secondInput.single.bytes, [27, 91, 68]);
+ expect(firstInput, isEmpty);
+ map.apply(
+ '{"bindings":[{"keys":"ctrl+g","command":null,"when":"terminal"}]}',
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyG, ctrl: true);
+ expect(secondInput.last.bytes, [
+ 7,
+ ], reason: 'Unbinding restores the original agent input route');
+ expect(app.panes, [first, second]);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ },
+ );
+
+ for (final inline in [false, true]) {
+ testWidgets(
+ 'configured picker actions and hints stay in ${inline ? 'New swarm' : 'titlebar'} search',
+ (tester) async {
+ final map = MemoryKeymap()
+ ..apply('''{"bindings":[
+ {"keys":"down","command":null,"when":"picker"},
+ {"keys":"ctrl+j","command":"picker.previous","when":"picker"},
+ {"keys":"enter","command":null,"when":"picker"},
+ {"keys":"alt+enter","command":"picker.accept","when":"picker"},
+ {"keys":"cmd+i","command":null,"when":"picker"},
+ {"keys":"ctrl+i","command":"picker.preview","when":"picker"}
+ ]}''');
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ final frames = <TerminalBinaryFrame>[];
+ final pane = app.adoptSessionForTest(terminal('a0', frames));
+ final original = app.activeSwarmId;
+ app.newSwarm();
+ await mount(tester, app, map);
+ final input = find.byKey(
+ ValueKey(
+ inline ? 'swarm-welcome-search-input' : 'swarm-search-input',
+ ),
+ );
+ if (inline) {
+ await tester.tap(input);
+ } else {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ }
+ await tester.enterText(input, 'Agent');
+ await tester.pump();
+ final search = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ final initial = search.cursor;
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(search.cursor, initial);
+ await key(tester, LogicalKeyboardKey.keyJ, ctrl: true);
+ expect(search.cursor, (initial - 1) % search.rows.length);
+ await tester.enterText(input, 'Agent 0');
+ await tester.pump();
+ expect(find.byTooltip('Preview recent output (⌃I)'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.keyI, cmd: true);
+ expect(search.previewEnabled, isFalse);
+ await key(tester, LogicalKeyboardKey.keyI, ctrl: true);
+ expect(search.previewEnabled, isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(find.byType(SwarmSearchResults), findsOneWidget);
+ expect(frames, isEmpty);
+ await key(tester, LogicalKeyboardKey.enter, alt: true);
+ expect(app.activeSwarmId, original);
+ expect(app.focusedPane, same(pane));
+ expect(find.byType(SwarmSearchResults), findsNothing);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ expect(frames.single.bytes, [27, 91, 68]);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ },
+ );
+ }
+
+ testWidgets(
+ 'terminal IME composition keeps its keys before workspace dispatch',
+ (tester) async {
+ final map = MemoryKeymap();
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ final frames = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', frames));
+ await mount(tester, app, map);
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: '木',
+ selection: TextSelection.collapsed(offset: 1),
+ composing: TextRange(start: 0, end: 1),
+ ),
+ );
+ await tester.pump();
+ expect(
+ tester.state<TerminalViewState>(find.byType(TerminalView)).isComposing,
+ isTrue,
+ );
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ expect(app.swarms, hasLength(1));
+ expect(frames, isEmpty);
+ tester.testTextInput.updateEditingValue(TextEditingValue.empty);
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ expect(app.swarms, hasLength(2));
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ },
+ );
+
+ testWidgets(
+ 'native field commands and snapshots use the same configured workspace actions',
+ (tester) async {
+ final calls = <MethodCall>[];
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ nativeChannel,
+ (call) async {
+ calls.add(call);
+ return null;
+ },
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ nativeChannel,
+ null,
+ ),
+ );
+ final map = MemoryKeymap();
+ final app = createApp();
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app, map, native: true);
+ expect(calls.where((c) => c.method == 'keymapState'), hasLength(1));
+ map.apply(
+ '{"bindings":[{"keys":"cmd+p","command":null},{"keys":"cmd+o","command":"navigation.quick_open"}]}',
+ );
+ await tester.pump();
+ final snapshot =
+ calls.lastWhere((c) => c.method == 'keymapState').arguments as Map;
+ final picker = (snapshot['contexts'] as Map)['picker'] as List;
+ expect(
+ picker.any((row) => (row['keys'] as List).contains('cmd+p')),
+ isFalse,
+ );
+ expect(
+ picker.any(
+ (row) =>
+ row['command'] == 'navigation.quick_open' &&
+ (row['keys'] as List).contains('cmd+o'),
+ ),
+ isTrue,
+ );
+ await native(tester, 'keymapCommand', {
+ 'command': 'navigation.quick_open',
+ });
+ await tester.pump();
+ await native(tester, 'searchChanged', {'query': 'Agent 0'});
+ await tester.pump();
+ await native(tester, 'keymapCommand', {'command': 'picker.preview'});
+ await tester.pump();
+ expect(
+ find.byKey(const ValueKey('swarm-search-preview')),
+ findsOneWidget,
+ );
+ await native(tester, 'keymapCommand', {'command': 'picker.accept'});
+ await tester.pump();
+ expect(find.byType(SwarmSearchResults), findsNothing);
+ expect(app.focusedPane, same(pane));
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ },
+ );
+
+ testWidgets(
+ 'shortcut help reflects current overrides, context and unbound commands',
+ (tester) async {
+ final map = MemoryKeymap();
+ late BuildContext helpContext;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: KeymapProvider(
+ keymap: map,
+ child: Builder(
+ builder: (context) {
+ helpContext = context;
+ return const Scaffold(body: ShortcutsSection());
+ },
+ ),
+ ),
+ ),
+ );
+ var rows = effectiveShortcutRows(helpContext, KeymapContext.workspace);
+ final searchLabel = rows
+ .firstWhere((row) => row.chords.any((keys) => keys.join() == '⌘P'))
+ .label;
+ map.apply('''{"bindings":[
+ {"keys":"cmd+p","command":null},
+ {"keys":"cmd+o","command":"navigation.quick_open"},
+ {"keys":"cmd+s","command":null,"when":"terminal"}
+ ]}''');
+ await tester.pump();
+ rows = effectiveShortcutRows(helpContext, KeymapContext.workspace);
+ expect(rows.firstWhere((r) => r.label == searchLabel).chords, [
+ ['⌘', 'O'],
+ ]);
+ expect(
+ rows.any((r) => r.chords.any((keys) => keys.join() == '⌘P')),
+ isFalse,
+ );
+ final terminalRows = effectiveShortcutRows(
+ helpContext,
+ KeymapContext.terminal,
+ );
+ expect(terminalRows.where((r) => r.chords.isEmpty), isNotEmpty);
+ expect(find.byType(ShortcutsDeck), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ map.dispose();
+ },
+ );
+}
diff --git a/desktop/third_party/xterm/lib/src/terminal_view.dart b/desktop/third_party/xterm/lib/src/terminal_view.dart
index 32c9091d7..cb474af85 100644
--- a/desktop/third_party/xterm/lib/src/terminal_view.dart
+++ b/desktop/third_party/xterm/lib/src/terminal_view.dart
@@ -480,6 +480,15 @@ class TerminalViewState extends State<TerminalView> {
@visibleForTesting
String? get debugComposingText => _composingText;
+ /// Live input-client composition, independent of its visual preview (which
+ /// may already match echoed terminal cells). Workspace shortcuts must let
+ /// the IME finish its marked text before claiming a key.
+ bool get isComposing {
+ final range =
+ _customTextEditKey.currentState?.currentTextEditingValue?.composing;
+ return range != null && range.isValid && !range.isCollapsed;
+ }
+
KeyEventResult _handleKeyEvent(FocusNode focusNode, KeyEvent event) {
final resultOverride = widget.onKeyEvent?.call(focusNode, event);
if (resultOverride != null && resultOverride != KeyEventResult.ignored) {
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index fe70ec82f..9c9023d91 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -275,9 +275,9 @@ private extension SwarmTitlebar {
try checkTitlebar(editor.string == "workshop 木", "Consumed native shortcuts never become query text")
_ = handleSearchKey(event("k", 40, .command))
try checkTitlebar(searchKeyDispatch?.pending.count == 1, "Native field retains a sequence prefix")
- let before = messenger.calls.count
+ let before = messenger.calls.filter { $0.method == "keymapCommand" }.count
_ = handleSearchKey(event("n", 45, .command))
- try checkTitlebar(messenger.calls.count == before + 1 &&
+ try checkTitlebar(messenger.calls.filter { $0.method == "keymapCommand" }.count == before + 1 &&
(messenger.calls.last?.arguments as? [String: Any])?["command"] as? String == "swarm.new",
"The configured sequence dispatches its command once")
_ = handleSearchKey(event("k", 40, .command))
diff --git a/docs/harness-v2-developer-tools-research.md b/docs/harness-v2-developer-tools-research.md
index 376e78315..3edc99ff0 100644
--- a/docs/harness-v2-developer-tools-research.md
+++ b/docs/harness-v2-developer-tools-research.md
@@ -20,7 +20,7 @@ Updated 2026-09-13 after user review. Keep the existing simple Command shortcuts
| In the rebuilt preview; regression verified | Preserve the session, terminal view, Find, viewport, selection and draft context through reconnect/keyframe replacement. Stale output/input/upload completions cannot affect the replacement stream. A real remote interruption remains to be validated. |
| Rebuilt; live search/project review passed | One top-right Cmd-P search for agents, Swarms, machines and projects, with Open and explicit Add here actions. Follow-up in validation: New swarm searches in place, and machine/project results open their swarm directly. Separate Add picker, floating pane + and titlebar bell removed. New swarm uses only the selected mountain/lake wallpaper; rotation and other assets removed. Native typing, Cmd-P select-all and Escape were verified from an existing empty New swarm after the focus correction. |
| Implemented; measured in isolation | Unified search construction and ranking avoid repeated scans/metadata work. Median catalog construction fell 50% in the 2,059-destination debug fixture; native input-to-display measurement remains separate. |
-| In progress | [Audit all shortcuts and implement a coherent agent-workspace key system with file-first remapping](harness-v2-keyboard-system.md). Config parser/resolver and live reload core pass isolated tests. The catalog now derives the live defaults and feeds `>` search commands. Finish runtime remapping, native menus and help while retaining those defaults. Remapping is not yet enabled. |
+| Implemented and regression checked | [A coherent agent-workspace key system with file-first remapping](harness-v2-keyboard-system.md). The optional config loads at startup and reloads on save. Workspace and picker dispatch, native menus, search actions and shortcut help share effective bindings; invalid edits keep the last working map. Existing simple defaults remain unchanged. See the progress log for build status and validation. |
| Calibration in progress; foreground runs paused | Native Release input/navigation fixture with synthetic terminals. No validated latency result yet; resume after the keyboard work stabilizes. Live keyboard/tab/drag and real remote interruption checks remain. |
| Resizing, splits, commands and preview implemented | `>` commands work in both search fields. Controlled resizing uses the existing gaps, saves proportions, protects usable sizes and retains terminal elements. Explicit right/down splits use the normal New agent form and preserve the surrounding rectangles. Cmd-S returns to a preset. Cmd-I or the eye control enables a compact snapshot of already-retained output for the selected agent; preview starts hidden and performs no network or terminal attachment. Match highlighting remains a follow-up. The [progress log](harness-v2-progress.md) records validation and the close-layout fallback. [The six-prototype review](harness-v2-prototype-review.md) records what to borrow and what stays out. |
| Keep deferred | Workflow canvases, autonomous manager layers, a full IDE/Git client and a marketplace. |
diff --git a/docs/harness-v2-keyboard-system.md b/docs/harness-v2-keyboard-system.md
index e8f631d7e..93efdbc66 100644
--- a/docs/harness-v2-keyboard-system.md
+++ b/docs/harness-v2-keyboard-system.md
@@ -50,11 +50,14 @@ Opening Keyboard Config can create a commented template; simply starting the app
Parse and resolve when configuration changes, never on each keystroke. A lookup must perform no disk or network work. Sequences must be cancelable and must not replay a failed prefix as a message to an agent. Default frequent actions need no prefix timeout.
-## Implementation status and next steps
-
-1. **Built and tested in isolation:** parser, resolver, validation, overrides/unbinding, sequences and file reload core. These are not yet connected to production dispatch.
-2. **Corrected and connected to search:** the command catalog derives its workspace keys from the live `app_shortcuts.dart` table. Both search fields accept `>` commands, show their current default shortcut, and invoke the existing workspace callbacks. Enter rechecks availability; command queries never become agent input. The previous draft defaults are gone.
-3. **Native bridge foundation checked:** the Dart adapter exports resolved bindings, contexts, repeat rules, hints and menu-command identities. The native decoder and dispatcher consume that exact exported payload in 51 isolated checks, covering current defaults, context-specific unbinding, remaps, bounded/cancelled sequences, IME, key-up ownership and reload. Logical keys use AppKit's current layout translation; no QWERTY letter table is imposed. The shipped Cmd-I preview action is included in the picker catalog. This foundation is still inactive in the running preview.
-4. **Native ownership implemented, awaiting Dart activation:** native menu labels update from the resolved map, including cleared unbindings and complete sequence tooltips. The main menu defers configured first strokes to the focused input. The titlebar search uses a scoped local event monitor so a plain sequence suffix is handled before text insertion; IME, standard text editing, focus changes and window blur retain their appropriate owner. 319 AppKit checks include actual hidden-field remaps and dispatch through the installed monitor. This follows Apple's [key-event routing](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/HandlingKeyEvents/HandlingKeyEvents.html) and [local event monitor lifecycle](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/MonitoringEvents/MonitoringEvents.html). Next: connect the Dart file loader and host, remove fixed Flutter fallbacks, and update help/tooltips from the same bindings before enabling customization.
-5. **Validation:** exact action and focus destinations, custom remaps, unbinding, repeated movement, sequences, cancellation, modal/IME behavior, and live config reload in isolated agent fixtures. Do not type tests into real agents.
-6. **Delivery:** rebuild and inspect the preview only after integration passes. The broader [working queue](harness-v2-developer-tools-research.md) tracks product proposals separately from authorized fixes.
+## Implementation and validation
+
+Production startup loads the optional file before the workspace opens. Settings and the shortcut sheet show the effective bindings for Workspace, Agent input or Search, including unassigned commands. **Edit keyboard config** creates a commented template only when explicitly invoked, lists the stable command IDs, and opens the associated editor. The startup path, watcher and dispatch never rewrite existing user configuration.
+
+Flutter owns configured workspace/terminal keys before the focused input, with live composition checks. Both search fields use their own picker context. Their Enter/add/preview actions and displayed hints update together; the command result list also refreshes its shortcut labels after a configuration change. Prefixes are temporary and never replay into agent input. The current direct defaults and explicit Cmd-P jump to titlebar search remain unchanged.
+
+Native menu labels come from the same resolved snapshot. The main menu yields configured first strokes to the input owner, rather than independently executing a command before Flutter knows its context. The native search editor uses a scoped local event monitor for ordinary sequence suffixes, with explicit cleanup. This follows Apple's [key-event routing](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/HandlingKeyEvents/HandlingKeyEvents.html) and [local event monitor lifecycle](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/MonitoringEvents/MonitoringEvents.html). Ordinary Mac editing, font and window commands remain native; custom bindings that use those reserved strokes, including sequence suffixes, are rejected instead of being silently unreliable.
+
+The complete Flutter suite passes **1,155 tests with one existing skip**. The native adapter/dispatcher passes **51 checks** against Dart-exported bindings, followed by **319 AppKit titlebar checks**, including remaps in a hidden actual field editor. Integration fixtures cover precise pane destinations and retained sessions, unbinding that returns an input key to its original agent, failed/completed sequences, both search fields, terminal IME, native channel dispatch and effective help. Final visual checks cover the settings deck, narrow layout and sheet; missing Tab/Return glyphs use icons. No real agents receive test input.
+
+See the [progress log](harness-v2-progress.md) for build/artifact status and the [working queue](harness-v2-developer-tools-research.md) for the next product improvements. These fixtures do not establish native input-to-display latency or first-install conversion rates; those remain separate measurements.
diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.md
index 62c3de7cf..52f630fd2 100644
--- a/docs/harness-v2-progress.md
+++ b/docs/harness-v2-progress.md
@@ -2,14 +2,16 @@
Updated 2026-09-13 with coordinated palettes, Models, combined closed-work History and faster unified search. This is a working preview, not a release.
-## Active follow-up: shortcut customization
-
-- Native runtime ownership is now implemented behind the still-inactive `keymapState` bridge. Harness menu rows receive effective keys and tooltips; a main-menu dispatcher yields those events to the focused input. The actual native search field uses its own synchronous configured dispatcher, including plain sequence suffixes, with no fallback that revives unbound keys. Standard Edit/Window/font commands retain AppKit ownership. A scoped local monitor is removed on window close.
-- **51 native decoder checks and 319 AppKit titlebar checks pass**, including the exported Dart remaps in a hidden native search editor, menu unbinding/rebuilds, sequences, IME, paired key-up, blur and reload. `/private/tmp/harness-v2-keymap-native-runtime.log`. The production Dart file loader/host and effective help are the remaining integration work; the running preview still uses its current defaults.
-- The inactive keymap foundation now includes a native decoder/dispatcher and Dart adapter. `bash tool/check_keymap_native.sh /private/tmp/harness-v2-flutter` exports the actual Dart-resolved defaults and custom bindings, then exercises that exact payload in Swift. **51 native checks passed** without opening windows or agents. Input parsing/lookup is synchronous; snapshots are validated as a whole and bounded. The current Cmd-I preview key is now in the picker command catalog.
-- Runtime enablement remains next. Flutter must own workspace keys, including unbound keys, while AppKit's search editor owns its own resolved picker bindings. Menus and help must show the same active configuration. No existing default or running shortcut behavior changes at this foundation checkpoint.
-- The 35 focused Flutter keymap/command checks pass; analyzer has no errors/warnings and the usual 12 vendored infos. The Xcode project file validates. Artifacts: `/private/tmp/harness-v2-keymap-{native-checks,bridge-tests,bridge-analyze}.log`. The running preview remains the previously built search-preview version; do not claim live remapping yet.
-- Push status: `364f1fb` is on `origin/app-v2`. Search preview is committed locally as `f04f6d3`. Automatic approval review rejected its push twice, even after `gh repo view` verified `autonomous-ai/autonomous-harness` as the existing public origin with ADMIN access. Explicit approval naming that public destination has been requested asynchronously; **do not retry pushes until it arrives**. Continue local work and commits. No code from the rejected command was pushed.
+## Keyboard customization checkpoint
+
+- Production startup now loads the optional `~/.config/harness/keybindings.jsonc` file (or its XDG location). Starting with no file creates nothing. Settings and the shortcut sheet offer **Edit keyboard config**, a context selector, the current path, and readable error details. The explicit edit action creates a commented template with command IDs and opens the associated editor. Invalid edits keep the last working bindings; the workspace shows a notice.
+- The existing defaults remain authoritative: Cmd-H/J/K/L and Cmd-arrows move focus, Cmd-S opens layout, Cmd-R refreshes, Cmd-B opens Boss mode, and Cmd-number selects a pane. The workspace uses resolved bindings before agent input. Search in each field uses its configured picker actions; Cmd-P retains the existing explicit jump to titlebar search. Menus, search actions, command hints, tooltips and both help layouts use the effective configuration.
+- Native menus display the resolved shortcut while yielding keyboard dispatch to the focused input. The titlebar editor owns its own configured keys through a scoped local monitor. Unbinding removes fixed fallbacks. Sequences can use ordinary suffixes, show temporary prefix feedback, and cancel on failure, Escape, focus change, reload or blur without replay into query/agent input. Terminal composition is checked through the actual input client's marked range, independently of the painted composition preview.
+- Mac editing, window and font shortcuts retain native ownership; conflicting custom strokes (including sequence suffixes) are rejected with an explanation. Remapping does not require adding modifier-heavy defaults. The provider is injected in tests, so no test reads or edits the user's configuration.
+- Validation: **1,155 Flutter tests passed, one existing skip**; **51 native decoder checks and 319 AppKit titlebar checks passed**. The native checks use the actual Dart-exported configuration in a hidden native field. Final rendering/integration checks also passed after replacing missing Tab/Return glyphs with icons and making the sheet's Close button neutral. Analyzer has zero errors/warnings and the same 12 vendored infos. No real agent received test input.
+- Artifacts: `/private/tmp/harness-v2-keymap-runtime-{full-tests,native,final-checks,analyze,build}.log`, `/private/tmp/harness-v2-keymap-{settings,narrow,sheet}.png`. Visual review covered both help layouts, custom and unassigned keys, and an 880px window. Release build succeeded and the exact development preview reopened after PID 31252 was normally quit and confirmed exited. Computer-use capture still returns `cgWindowNotFound`; visual evidence is from isolated renders, not a live-window capture.
+- Push status: `364f1fb` is on `origin/app-v2`. Subsequent preview/native checkpoints are local (`f04f6d3`, `cd0aa0f`, `fcb8b33`). Automatic approval review rejected pushing to the verified existing public origin `autonomous-ai/autonomous-harness`, despite ADMIN access and the user's earlier push instruction. Explicit approval naming that public destination is pending; **do not retry pushes until it arrives**. Continue local work and commits.
+- Next: search match highlighting and another first-use pass, followed by measured interaction performance. Keep the current defaults, agent drafts, sessions and saved swarm arrangements intact.
## Optional search preview checkpoint