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.

Share resolved keyboard bindings with a tested native dispatcher

deecd0aa0fe8692
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index e81de7a31..a660ae466 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -356,6 +356,13 @@ final harnessCommands = <HarnessCommand>[
extraKeys: ['cmd+enter'],
context: KeymapContext.picker,
),
+ const HarnessCommand(
+ 'picker.preview',
+ 'Toggle agent output preview',
+ ShortcutGroup.navigate,
+ extraKeys: ['cmd+i'],
+ context: KeymapContext.picker,
+ ),
const HarnessCommand(
'picker.cancel',
'Close search',
diff --git a/desktop/lib/shortcuts/keymap_native.dart b/desktop/lib/shortcuts/keymap_native.dart
new file mode 100644
index 000000000..282b56666
--- /dev/null
+++ b/desktop/lib/shortcuts/keymap_native.dart
@@ -0,0 +1,26 @@
+import 'app_keymap.dart';
+import 'keymap.dart';
+import 'keymap_commands.dart';
+
+/// Resolved bindings cross to AppKit only when configuration changes. Native
+/// input never reads the file or waits for a Dart reply to decide ownership.
+Map<String, Object> nativeKeymapSnapshot(AppKeymap keymap) => {
+ 'version': 1,
+ 'contexts': {
+ for (final context in KeymapContext.values)
+ context.name: [
+ for (final binding in keymap.current.bindingsFor(context))
+ if (binding.command != null)
+ {
+ 'keys': binding.keys.map((key) => key.toString()).toList(),
+ 'command': binding.command!,
+ 'hint': describeKeyBinding(binding),
+ 'repeatable':
+ harnessCommandById[binding.command]?.repeatable == true,
+ if (harnessCommandById[binding.command]?.nativeAction
+ case final String action)
+ 'menuAction': action,
+ },
+ ],
+ },
+};
diff --git a/desktop/macos/Runner.xcodeproj/project.pbxproj b/desktop/macos/Runner.xcodeproj/project.pbxproj
index b4e651cd8..022d87445 100644
--- a/desktop/macos/Runner.xcodeproj/project.pbxproj
+++ b/desktop/macos/Runner.xcodeproj/project.pbxproj
@@ -22,6 +22,7 @@
/* Begin PBXBuildFile section */
B20100000000000000000001 /* SwarmTitlebar.swift in Sources */ = {isa = PBXBuildFile; fileRef = B20100000000000000000002 /* SwarmTitlebar.swift */; };
+ B20100000000000000000003 /* HarnessKeymap.swift in Sources */ = {isa = PBXBuildFile; fileRef = B20100000000000000000004 /* HarnessKeymap.swift */; };
331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; };
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; };
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; };
@@ -63,6 +64,7 @@
/* Begin PBXFileReference section */
B20100000000000000000002 /* SwarmTitlebar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwarmTitlebar.swift; sourceTree = "<group>"; };
+ B20100000000000000000004 /* HarnessKeymap.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HarnessKeymap.swift; sourceTree = "<group>"; };
331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = "<group>"; };
333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = "<group>"; };
@@ -171,6 +173,7 @@
33CC10F02044A3C60003C045 /* AppDelegate.swift */,
33CC11122044BFA00003C045 /* MainFlutterWindow.swift */,
B20100000000000000000002 /* SwarmTitlebar.swift */,
+ B20100000000000000000004 /* HarnessKeymap.swift */,
33E51913231747F40026EE4D /* DebugProfile.entitlements */,
33E51914231749380026EE4D /* Release.entitlements */,
33CC11242044D66E0003C045 /* Resources */,
@@ -359,6 +362,7 @@
files = (
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */,
B20100000000000000000001 /* SwarmTitlebar.swift in Sources */,
+ B20100000000000000000003 /* HarnessKeymap.swift in Sources */,
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */,
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */,
);
diff --git a/desktop/macos/Runner/HarnessKeymap.swift b/desktop/macos/Runner/HarnessKeymap.swift
new file mode 100644
index 000000000..663f08362
--- /dev/null
+++ b/desktop/macos/Runner/HarnessKeymap.swift
@@ -0,0 +1,209 @@
+import Cocoa
+
+/// Canonical logical strokes match Dart's KeyStroke. No QWERTY letter table:
+/// AppKit translates the event through the current keyboard layout.
+struct HarnessKeyStroke: Hashable {
+ let key: String
+ let modifiers: NSEvent.ModifierFlags
+ static let modifierMask: NSEvent.ModifierFlags = [.control, .option, .command, .shift]
+ static let named: Set<String> = ["enter", "escape", "left", "right", "up", "down",
+ "pageup", "pagedown", "home", "end", "delete", "backspace", "tab", "space",
+ "comma", "period", "slash", "backslash", "semicolon", "quote", "backquote",
+ "bracketleft", "bracketright", "minus", "equal", "insert"]
+
+ init?(_ canonical: String) {
+ let pieces = canonical.split(separator: "+", omittingEmptySubsequences: false).map(String.init)
+ guard let last = pieces.last, Self.validKey(last), pieces.count <= 5 else { return nil }
+ var flags: NSEvent.ModifierFlags = []
+ for part in pieces.dropLast() {
+ let flag: NSEvent.ModifierFlags
+ switch part {
+ case "ctrl": flag = .control
+ case "alt": flag = .option
+ case "cmd": flag = .command
+ case "shift": flag = .shift
+ default: return nil
+ }
+ guard !flags.contains(flag) else { return nil }
+ flags.insert(flag)
+ }
+ key = last
+ modifiers = flags
+ }
+
+ private init(key: String, modifiers: NSEvent.ModifierFlags) {
+ self.key = key
+ self.modifiers = modifiers.intersection(Self.modifierMask)
+ }
+
+ func hash(into hasher: inout Hasher) {
+ hasher.combine(key)
+ hasher.combine(modifiers.rawValue)
+ }
+
+ private static func validKey(_ key: String) -> Bool {
+ if named.contains(key) { return true }
+ if key.count == 1, let value = key.unicodeScalars.first?.value {
+ return (97...122).contains(value) || (48...57).contains(value)
+ }
+ guard key.first == "f", let number = Int(key.dropFirst()) else { return false }
+ return (1...24).contains(number) && key == "f\(number)"
+ }
+
+ private static let characterNames: [String: String] = [
+ "\r": "enter", "\u{3}": "enter", "\u{1b}": "escape", "\u{7f}": "backspace",
+ "\u{8}": "backspace", "\t": "tab", "\u{19}": "tab", " ": "space",
+ ",": "comma", ".": "period", "/": "slash", "\\": "backslash",
+ ";": "semicolon", "'": "quote", "`": "backquote", "[": "bracketleft",
+ "]": "bracketright", "-": "minus", "=": "equal",
+ "\u{f700}": "up", "\u{f701}": "down", "\u{f702}": "left", "\u{f703}": "right",
+ "\u{f727}": "insert", "\u{f728}": "delete", "\u{f729}": "home",
+ "\u{f72b}": "end", "\u{f72c}": "pageup", "\u{f72d}": "pagedown",
+ ]
+
+ static func fromCharacters(_ characters: String, modifiers: NSEvent.ModifierFlags) -> Self? {
+ let lowered = characters.lowercased()
+ let key: String
+ if let scalar = characters.unicodeScalars.first, characters.unicodeScalars.count == 1,
+ (0xf704...0xf71b).contains(scalar.value) {
+ key = "f\(scalar.value - 0xf704 + 1)"
+ } else {
+ key = characterNames[characters] ?? lowered
+ }
+ guard validKey(key) else { return nil }
+ return Self(key: key, modifiers: modifiers)
+ }
+
+ static func fromEvent(_ event: NSEvent) -> Self? {
+ guard event.type == .keyDown || event.type == .keyUp else { return nil }
+ // Remove Shift/Option from translation, but keep them in the stroke. This
+ // resolves Shift-1 through the user's layout without treating '!' as a key.
+ guard let text = event.characters(byApplyingModifiers: event.modifierFlags.intersection(.command))
+ ?? event.charactersIgnoringModifiers else { return nil }
+ return fromCharacters(text, modifiers: event.modifierFlags)
+ }
+
+ var menuEquivalent: String {
+ let special: [String: String] = [
+ "enter": "\r", "escape": "\u{1b}", "backspace": "\u{8}", "tab": "\t", "space": " ",
+ "comma": ",", "period": ".", "slash": "/", "backslash": "\\", "semicolon": ";",
+ "quote": "'", "backquote": "`", "bracketleft": "[", "bracketright": "]", "minus": "-", "equal": "=",
+ "up": "\u{f700}", "down": "\u{f701}", "left": "\u{f702}", "right": "\u{f703}",
+ "insert": "\u{f727}", "delete": "\u{f728}", "home": "\u{f729}", "end": "\u{f72b}",
+ "pageup": "\u{f72c}", "pagedown": "\u{f72d}",
+ ]
+ if let value = special[key] { return value }
+ if key.first == "f", let number = Int(key.dropFirst()), (1...24).contains(number) {
+ return String(UnicodeScalar(0xf704 + number - 1)!)
+ }
+ return key
+ }
+}
+
+struct HarnessNativeBinding {
+ let keys: [HarnessKeyStroke]
+ let command: String
+ let hint: String
+ let repeatable: Bool
+ let menuAction: String?
+}
+
+private final class HarnessKeyNode {
+ var binding: HarnessNativeBinding?
+ var children: [HarnessKeyStroke: HarnessKeyNode] = [:]
+}
+
+/// Reject a malformed snapshot as a whole, leaving the caller's last good map.
+/// Defaults and overrides are already resolved in Dart, including unbinding.
+final class HarnessNativeKeymap {
+ private var roots: [String: HarnessKeyNode] = [:]
+ private(set) var bindings: [String: [HarnessNativeBinding]] = [:]
+
+ init?(_ payload: [String: Any]) {
+ guard payload["version"] as? Int == 1,
+ let contexts = payload["contexts"] as? [String: Any],
+ Set(contexts.keys) == Set(["workspace", "terminal", "picker"]) else { return nil }
+ for (context, raw) in contexts {
+ guard let rows = raw as? [[String: Any]], rows.count <= 640 else { return nil }
+ let root = HarnessKeyNode()
+ var parsed: [HarnessNativeBinding] = []
+ for row in rows {
+ guard let keys = row["keys"] as? [String], (1...4).contains(keys.count),
+ let command = row["command"] as? String, !command.isEmpty, command.utf8.count <= 120,
+ let hint = row["hint"] as? String, hint.utf8.count <= 160,
+ let repeatable = row["repeatable"] as? Bool else { return nil }
+ let strokes = keys.compactMap(HarnessKeyStroke.init)
+ guard strokes.count == keys.count else { return nil }
+ let binding = HarnessNativeBinding(keys: strokes, command: command, hint: hint,
+ repeatable: repeatable, menuAction: row["menuAction"] as? String)
+ var node = root
+ for stroke in strokes {
+ guard node.binding == nil else { return nil }
+ if node.children[stroke] == nil { node.children[stroke] = HarnessKeyNode() }
+ node = node.children[stroke]!
+ }
+ guard node.children.isEmpty && node.binding == nil else { return nil }
+ node.binding = binding
+ parsed.append(binding)
+ }
+ roots[context] = root
+ bindings[context] = parsed
+ }
+ }
+
+ func match(_ keys: [HarnessKeyStroke], context: String) -> (binding: HarnessNativeBinding?, prefix: Bool) {
+ guard var node = roots[context] else { return (nil, false) }
+ for key in keys {
+ guard let child = node.children[key] else { return (nil, false) }
+ node = child
+ }
+ return (node.binding, !node.children.isEmpty)
+ }
+}
+
+/// Synchronous native-field dispatcher. Mirrors KeymapDispatch: cancelled or
+/// failed prefixes are consumed, never replayed into the query or an agent.
+final class HarnessNativeKeyDispatch {
+ private var map: HarnessNativeKeymap
+ private(set) var pending: [HarnessKeyStroke] = []
+ private var pressed: Set<UInt16> = []
+ private var owner: ObjectIdentifier?
+ private var context: String?
+
+ init(_ map: HarnessNativeKeymap) { self.map = map }
+ func update(_ next: HarnessNativeKeymap) { map = next; cancel() }
+ func cancel() { pending.removeAll(keepingCapacity: true); owner = nil; context = nil }
+ func suspend() { cancel(); pressed.removeAll(keepingCapacity: true) }
+ func release(_ keyCode: UInt16) -> Bool { pressed.remove(keyCode) != nil }
+
+ func dispatch(_ stroke: HarnessKeyStroke?, keyCode: UInt16, repeated: Bool = false,
+ modifier: Bool = false, composing: Bool = false, context: String,
+ owner: AnyObject, canExecute: (String) -> Bool = { _ in true }) -> (handled: Bool, command: String?) {
+ if composing { cancel(); return (false, nil) }
+ let ownerID = ObjectIdentifier(owner)
+ if !pending.isEmpty && (self.owner != ownerID || self.context != context) { cancel() }
+ guard let stroke else {
+ if !modifier && !pending.isEmpty { cancel(); pressed.insert(keyCode); return (true, nil) }
+ return (false, nil)
+ }
+ if repeated && !pending.isEmpty { return (pressed.contains(keyCode), nil) }
+ let wasPending = !pending.isEmpty
+ if wasPending && stroke == HarnessKeyStroke("escape")! {
+ cancel(); pressed.insert(keyCode); return (true, nil)
+ }
+ let sequence = pending + [stroke]
+ let match = map.match(sequence, context: context)
+ if match.prefix {
+ pending = sequence; self.owner = ownerID; self.context = context
+ pressed.insert(keyCode)
+ return (true, nil)
+ }
+ cancel()
+ if let binding = match.binding {
+ pressed.insert(keyCode)
+ return (true, canExecute(binding.command) && (!repeated || binding.repeatable) ? binding.command : nil)
+ }
+ if wasPending { pressed.insert(keyCode) }
+ return (wasPending, nil)
+ }
+}
diff --git a/desktop/test/keymap_native_test.dart b/desktop/test/keymap_native_test.dart
new file mode 100644
index 000000000..2f1743e53
--- /dev/null
+++ b/desktop/test/keymap_native_test.dart
@@ -0,0 +1,73 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shortcuts/keymap_native.dart';
+import 'package:harness/shortcuts/keymap.dart';
+import 'package:harness/shortcuts/keymap_commands.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap;
+
+void main() {
+ test(
+ 'native payload carries resolved contexts, unbinding and actual hints',
+ () async {
+ final keymap = MemoryKeymap();
+ addTearDown(keymap.dispose);
+ final defaults = nativeKeymapSnapshot(keymap);
+ keymap.apply('''{"bindings":[
+ {"keys":"cmd+p","command":null},
+ {"keys":"cmd+o","command":"navigation.quick_open"},
+ {"keys":"cmd+k","command":null},
+ {"keys":"cmd+k cmd+n","command":"swarm.new"},
+ {"keys":"cmd+h","command":null,"when":"terminal"},
+ {"keys":"down","command":null,"when":"picker"},
+ {"keys":"ctrl+j","command":"picker.previous","when":"picker"}
+ ]}''');
+ final changed = nativeKeymapSnapshot(keymap);
+ final contexts = changed['contexts']! as Map;
+ for (final context in KeymapContext.values) {
+ final rows = (contexts[context.name] as List).cast<Map>();
+ final bindings = keymap.current.bindingsFor(context);
+ expect(rows.length, bindings.length);
+ for (final binding in bindings) {
+ final row = rows.singleWhere(
+ (row) => (row['keys'] as List).join(' ') == binding.sequence,
+ );
+ expect(row['command'], binding.command);
+ expect(row['hint'], describeKeyBinding(binding));
+ expect(
+ row['repeatable'],
+ harnessCommandById[binding.command]!.repeatable,
+ );
+ expect(
+ row['menuAction'],
+ harnessCommandById[binding.command]!.nativeAction,
+ );
+ }
+ expect(
+ rows.any((row) => (row['keys'] as List).join(' ') == 'cmd+p'),
+ isFalse,
+ );
+ }
+ expect(
+ (contexts['terminal'] as List).any(
+ (row) => (row['keys'] as List).join(' ') == 'cmd+h',
+ ),
+ isFalse,
+ );
+ expect(
+ (contexts['workspace'] as List).any(
+ (row) => (row['keys'] as List).join(' ') == 'cmd+h',
+ ),
+ isTrue,
+ );
+ final fixture = Platform.environment['HARNESS_KEYMAP_FIXTURE_PATH'];
+ if (fixture != null) {
+ await File(
+ fixture,
+ ).writeAsString(jsonEncode({'defaults': defaults, 'changed': changed}));
+ }
+ },
+ );
+}
diff --git a/desktop/tool/check_keymap_native.sh b/desktop/tool/check_keymap_native.sh
new file mode 100644
index 000000000..0310b590e
--- /dev/null
+++ b/desktop/tool/check_keymap_native.sh
@@ -0,0 +1,16 @@
+#!/bin/bash
+set -euo pipefail
+
+desktop_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
+flutter_sdk="${1:?Pass the Flutter SDK path}"
+check_dir="$(mktemp -d "${TMPDIR:-/tmp}/harness-keymap.XXXXXX")"
+trap 'rm -rf "$check_dir"' EXIT
+cd "$desktop_dir"
+# Export the production Dart adapter's resolved payload, then exercise that
+# exact payload in Swift. No user config, real windows or agent connections.
+HARNESS_KEYMAP_FIXTURE_PATH="$check_dir/bindings.json" \
+ "$flutter_sdk/bin/flutter" test --no-pub test/keymap_native_test.dart
+cat macos/Runner/HarnessKeymap.swift tool/keymap_native_checks.swift > "$check_dir/main.swift"
+xcrun swiftc -swift-version 5 -module-cache-path "$check_dir/module-cache" \
+ "$check_dir/main.swift" -o "$check_dir/check-keymap"
+"$check_dir/check-keymap" "$check_dir/bindings.json"
diff --git a/desktop/tool/keymap_native_checks.swift b/desktop/tool/keymap_native_checks.swift
new file mode 100644
index 000000000..befbcc2a9
--- /dev/null
+++ b/desktop/tool/keymap_native_checks.swift
@@ -0,0 +1,104 @@
+// Compiled after HarnessKeymap.swift by check_keymap_native.sh.
+struct KeymapCheckFailure: Error { let message: String }
+var keymapChecks = 0
+func checkKeymap(_ condition: @autoclosure () -> Bool, _ message: String) throws {
+ guard condition() else { throw KeymapCheckFailure(message: message) }
+ keymapChecks += 1
+}
+func stroke(_ key: String) -> HarnessKeyStroke { HarnessKeyStroke(key)! }
+
+let source = try Data(contentsOf: URL(fileURLWithPath: CommandLine.arguments[1]))
+let fixture = try JSONSerialization.jsonObject(with: source) as! [String: [String: Any]]
+let defaults = HarnessNativeKeymap(fixture["defaults"]!)!
+let changed = HarnessNativeKeymap(fixture["changed"]!)!
+for (key, command) in [
+ ("cmd+h", "pane.focus_left"), ("cmd+j", "pane.focus_below"),
+ ("cmd+k", "pane.focus_above"), ("cmd+l", "pane.focus_right"),
+ ("cmd+s", "pane.layout"), ("cmd+r", "machines.refresh"),
+ ("cmd+b", "task.route"), ("cmd+p", "navigation.quick_open"),
+] {
+ try checkKeymap(defaults.match([stroke(key)], context: "workspace").binding?.command == command,
+ "Preserve the current default for \(key)")
+}
+for context in ["workspace", "terminal", "picker"] {
+ try checkKeymap(changed.match([stroke("cmd+p")], context: context).binding == nil,
+ "Native context honors inherited unbinding")
+ let search = changed.match([stroke("cmd+o")], context: context).binding
+ try checkKeymap(search?.command == "navigation.quick_open" && search?.hint == "⌘O" && search?.menuAction == "jump",
+ "The new key, menu owner and displayed hint agree")
+ try checkKeymap(changed.match([stroke("cmd+k")], context: context).prefix,
+ "User sequence prefix replaces the shorter command")
+}
+try checkKeymap(changed.match([stroke("cmd+h")], context: "terminal").binding == nil,
+ "Terminal-only unbinding does not leak its workspace binding")
+try checkKeymap(changed.match([stroke("cmd+h")], context: "workspace").binding != nil,
+ "Workspace keeps its own context")
+try checkKeymap(changed.match([stroke("down")], context: "picker").binding == nil,
+ "Picker unbinding removes the original arrow action")
+try checkKeymap(changed.match([stroke("ctrl+j")], context: "picker").binding?.command == "picker.previous",
+ "Picker remapping wins")
+try checkKeymap(defaults.match([stroke("cmd+i")], context: "picker").binding?.command == "picker.preview",
+ "The shipped optional-preview shortcut joins the catalog")
+
+let dispatcher = HarnessNativeKeyDispatch(changed)
+let field = NSObject(), otherField = NSObject()
+func send(_ key: String?, _ code: UInt16 = 1, repeated: Bool = false, composing: Bool = false,
+ owner: NSObject = field, context: String = "picker", modifier: Bool = false,
+ executable: Bool = true) -> (handled: Bool, command: String?) {
+ dispatcher.dispatch(key.map(stroke), keyCode: code, repeated: repeated, modifier: modifier,
+ composing: composing, context: context, owner: owner, canExecute: { _ in executable })
+}
+try checkKeymap(send("cmd+k").handled && dispatcher.pending.count == 1, "Prefix is claimed synchronously")
+try checkKeymap(send("cmd+k", repeated: true).command == nil && dispatcher.pending.count == 1,
+ "A held prefix does not advance a sequence")
+try checkKeymap(!send(nil, 2, modifier: true).handled && dispatcher.pending.count == 1,
+ "Modifiers retain normal delivery during a prefix")
+try checkKeymap(send("cmd+n", 3).command == "swarm.new" && dispatcher.pending.isEmpty,
+ "Completing a sequence dispatches exactly one named command")
+try checkKeymap(dispatcher.release(3) && !dispatcher.release(3), "Consumed key-up is paired once")
+_ = send("cmd+k")
+try checkKeymap(send("x", 4).handled && dispatcher.pending.isEmpty,
+ "A failed sequence is consumed rather than typed into an agent")
+try checkKeymap(!send("x", 4).handled, "The next ordinary character is not swallowed")
+_ = send("cmd+k")
+try checkKeymap(send("escape", 5).handled && dispatcher.pending.isEmpty, "Escape cancels a prefix")
+_ = send("cmd+k")
+try checkKeymap(!send("x", 4, owner: otherField).handled && dispatcher.pending.isEmpty,
+ "A different input owner cannot complete the previous field's sequence")
+_ = send("cmd+k")
+try checkKeymap(!send("enter", 6, composing: true).handled && dispatcher.pending.isEmpty,
+ "IME composition keeps input and cancels the prefix")
+try checkKeymap(send("cmd+o", executable: false).handled && send("cmd+o", executable: false).command == nil,
+ "An unavailable mapped action cannot fall through as input")
+try checkKeymap(send("cmd+o", repeated: true).command == nil, "Search does not repeat")
+try checkKeymap(send("ctrl+j", repeated: true).command == "picker.previous", "Result movement repeats")
+_ = send("cmd+k")
+dispatcher.suspend()
+try checkKeymap(dispatcher.pending.isEmpty && !dispatcher.release(1), "Window blur clears pending and held keys")
+dispatcher.update(defaults)
+try checkKeymap(send("cmd+p").command == "navigation.quick_open", "Reload installs the new resolved map")
+
+try checkKeymap(HarnessKeyStroke.fromCharacters("P", modifiers: [.command, .capsLock]) == stroke("cmd+p"),
+ "Caps Lock does not change a Command binding")
+try checkKeymap(HarnessKeyStroke.fromCharacters("1", modifiers: [.command, .shift]) == stroke("cmd+shift+1"),
+ "Shift stays in modifiers after layout translation")
+try checkKeymap(HarnessKeyStroke.fromCharacters("\u{f702}", modifiers: .command) == stroke("cmd+left"),
+ "AppKit arrow characters map to the same logical keys")
+try checkKeymap(HarnessKeyStroke.fromCharacters("木", modifiers: []) == nil,
+ "Unsupported composed text is not guessed as a QWERTY key")
+try checkKeymap(stroke("cmd+shift+left").menuEquivalent == "\u{f702}" && stroke("f24").menuEquivalent == "\u{f71b}",
+ "Native menu equivalents preserve function keys")
+
+func payload(_ rows: [[String: Any]]) -> [String: Any] {
+ ["version": 1, "contexts": ["workspace": rows, "terminal": rows, "picker": rows]]
+}
+let prefix: [String: Any] = ["keys": ["cmd+k"], "command": "example", "hint": "⌘K", "repeatable": false]
+let sequence: [String: Any] = ["keys": ["cmd+k", "cmd+n"], "command": "example", "hint": "⌘K ⌘N", "repeatable": false]
+try checkKeymap(HarnessNativeKeymap(payload([prefix, sequence])) == nil, "Reject ambiguous prefixes atomically")
+try checkKeymap(HarnessNativeKeymap(payload([prefix, prefix])) == nil, "Reject duplicate strokes atomically")
+try checkKeymap(HarnessNativeKeymap(payload(Array(repeating: prefix, count: 641))) == nil, "Bound incoming binding counts")
+try checkKeymap(HarnessNativeKeymap(["version": 2, "contexts": [:]]) == nil, "Reject unsupported snapshots")
+for value in ["cmd+cmd+p", "cmd+", "cmd+not-a-key", "ctrl+alt+shift+cmd+fn+p", "f01"] {
+ try checkKeymap(HarnessKeyStroke(value) == nil, "Reject malformed native stroke \(value)")
+}
+print("Native keyboard bridge: \(keymapChecks) checks passed against Dart's exported bindings; no windows or agents opened.")
diff --git a/docs/harness-v2-keyboard-system.md b/docs/harness-v2-keyboard-system.md
index 885518ad4..24f6ce937 100644
--- a/docs/harness-v2-keyboard-system.md
+++ b/docs/harness-v2-keyboard-system.md
@@ -54,6 +54,7 @@ Parse and resolve when configuration changes, never on each keystroke. A lookup
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. **Next implementation:** finish one runtime binding system for the agent workspace, search, native menus, help and tooltips, retaining the agreed defaults above. Audit native owners for conflicts with those defaults instead of assuming system conventions win.
-4. **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.
-5. **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.
+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. **Next implementation:** connect runtime configuration to the workspace and search, remove competing native shortcut owners when Flutter owns input, and update menu/help/tooltips from the same bindings. Preserve the agreed defaults. A shortcut's native menu label must not cause the old binding to survive unbinding in Flutter.
+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.
diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.md
index 41145be6f..79d7d1bfc 100644
--- a/docs/harness-v2-progress.md
+++ b/docs/harness-v2-progress.md
@@ -2,7 +2,14 @@
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: optional search preview
+## Active follow-up: shortcut customization
+
+- 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.
+
+## Optional search preview checkpoint
- The eye control in open search, or **Cmd-I** while editing its query, toggles a short output preview. It starts hidden for each search session. Both the titlebar and New swarm field keep their own query, caret, selected result and Enter action. Commands, groups and closed History entries do not show an agent-output preview.
- The preview snapshots only an already-retained matching machine/agent session. It scans at most 160 rows and 192 cells per row, keeps at most 12 nonblank lines, and retains only the current excerpt. Repeated query edits on the same selection reuse that excerpt; changing selection or toggling off/on captures again. Missing output gets an honest empty state. No network request, terminal attachment, input, resize or viewport mutation occurs.