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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Coordinate native menu and search shortcut ownership
deefcb8b33af967
diff --git a/desktop/macos/Runner/HarnessKeymap.swift b/desktop/macos/Runner/HarnessKeymap.swiftindex 663f08362..0dba62382 100644--- a/desktop/macos/Runner/HarnessKeymap.swift+++ b/desktop/macos/Runner/HarnessKeymap.swift@@ -159,6 +159,69 @@ final class HarnessNativeKeymap {}return (node.binding, !node.children.isEmpty)}++ func hint(for command: String, context: String) -> String? {+ bindings[context]?.first(where: { $0.command == command })?.hint+ }++ /// Only explicitly identified Harness rows change. AppKit's Edit, Window,+ /// Services and font-size commands retain their native ownership.+ func applyMenuKeys(to menu: NSMenu, context: String) {+ let resolved = bindings[context] ?? []+ for item in menu.items {+ if let identifier = item.identifier?.rawValue,+ identifier.hasPrefix(HarnessKeymapMenu.actionPrefix) {+ let action = String(identifier.dropFirst(HarnessKeymapMenu.actionPrefix.count))+ let binding = resolved.first(where: { $0.menuAction == action })+ let key = binding?.keys.count == 1 ? binding?.keys.first : nil+ item.keyEquivalent = key?.menuEquivalent ?? ""+ item.keyEquivalentModifierMask = key?.modifiers ?? []+ // AppKit has no multi-stroke key-equivalent column. Show its complete+ // binding in the tooltip; never advertise just a sequence's first key.+ item.toolTip = binding.map { "\(item.title) — \($0.hint)" }+ }+ if let submenu = item.submenu { applyMenuKeys(to: submenu, context: context) }+ }+ }+}++/// Display the effective native shortcuts without dispatching them ahead of+/// the focused Flutter input. The union of first strokes is deliberate: the+/// synchronous Dart focus context, not an asynchronous menu snapshot, decides+/// whether a terminal-only override or unbinding applies to this event.+final class HarnessKeymapMenu: NSMenu {+ static let actionPrefix = "harness.keymap."+ weak var ownerWindow: NSWindow?+ private var inputStrokes: Set<HarnessKeyStroke> = []++ static func replacing(_ previous: NSMenu) -> HarnessKeymapMenu {+ let menu = HarnessKeymapMenu(title: previous.title)+ menu.autoenablesItems = previous.autoenablesItems+ menu.delegate = previous.delegate+ // Retain the actual submenu objects: NSApp's Services/Windows references+ // and AppKit's first-responder targets must continue to point at them.+ for item in previous.items {+ previous.removeItem(item)+ menu.addItem(item)+ }+ return menu+ }++ func update(_ map: HarnessNativeKeymap, window: NSWindow) {+ ownerWindow = window+ inputStrokes = Set(map.bindings.values.flatMap { $0.compactMap { $0.keys.first } })+ }++ func defersToInput(_ event: NSEvent) -> Bool {+ guard let ownerWindow, (event.window ?? NSApp.keyWindow) === ownerWindow,+ let stroke = HarnessKeyStroke.fromEvent(event) else { return false }+ return inputStrokes.contains(stroke)+ }++ override func performKeyEquivalent(with event: NSEvent) -> Bool {+ if defersToInput(event) { return false }+ return super.performKeyEquivalent(with: event)+ }}/// Synchronous native-field dispatcher. Mirrors KeymapDispatch: cancelled ordiff --git a/desktop/macos/Runner/MainFlutterWindow.swift b/desktop/macos/Runner/MainFlutterWindow.swiftindex c7d3e029d..75d818f4c 100644--- a/desktop/macos/Runner/MainFlutterWindow.swift+++ b/desktop/macos/Runner/MainFlutterWindow.swift@@ -231,6 +231,10 @@ class MainFlutterWindow: NSWindow {)item.target = selfitem.tag = tag+ if tag == shortcutsMenuItemTag || tag == layoutMenuItemTag {+ let command = tag == shortcutsMenuItemTag ? "showShortcuts" : "layout"+ item.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + command)+ }// Every other row in this menu carries a glyph, so one without reads as// unfinished — the gutter stays but nothing sits in it.item.image = NSImage(systemSymbolName: symbol, accessibilityDescription: title)diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex 7bf31c6b2..8f873b713 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -24,12 +24,20 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {private let historyIcons = SwarmHistoryIcons()private let modelsMenu = NSMenu(title: "Models")private var subscriptions: [SwarmSubscriptionEntry] = []+ private var keymap: HarnessNativeKeymap?+ private var flutterKeyContext = "workspace"+ private var searchKeyDispatch: HarnessNativeKeyDispatch?+ private var searchKeyMonitor: Any?init(window: NSWindow, messenger: FlutterBinaryMessenger) {self.window = windowchannel = FlutterMethodChannel(name: "harness/swarm_tabs", binaryMessenger: messenger)super.init()strip.emit = { [weak self] method, args in self?.channel.invokeMethod(method, arguments: args) }+ strip.editingEnded = { [weak self] in+ self?.searchKeyDispatch?.cancel()+ self?.syncMenuKeys()+ }channel.setMethodCallHandler { [weak self] call, result inguard let self else { result(nil); return }switch call.method {@@ -39,6 +47,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() }self.canReopen = state["canReopen"] as? Bool == trueself.canFind = state["canFind"] as? Bool == trueself.canClosePane = state["canClosePane"] as? Bool == true@@ -56,12 +65,29 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {self.strip.setSearchState(call.arguments as? [String: Any] ?? [:])result(nil)case "closeSearch":+ self.searchKeyDispatch?.cancel()self.strip.closeSearch()+ self.syncMenuKeys()result(nil)case "modelsState":let state = call.arguments as? [String: Any] ?? [:]self.updateModels(state["subscriptions"] as? [[String: Any]] ?? [])result(nil)+ case "keymapState":+ guard let payload = call.arguments as? [String: Any],+ let map = HarnessNativeKeymap(payload) else {+ result(FlutterError(code: "INVALID_KEYMAP", message: "Invalid keyboard configuration", details: nil))+ return+ }+ self.setKeymap(map)+ result(nil)+ case "keymapContext":+ if let context = (call.arguments as? [String: Any])?["context"] as? String,+ ["workspace", "terminal", "picker"].contains(context) {+ self.flutterKeyContext = context+ self.syncMenuKeys()+ }+ result(nil)default: result(FlutterMethodNotImplemented)}}@@ -73,9 +99,76 @@ 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() })+ observers.append(NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification,+ object: window, queue: .main) { [weak self] _ in self?.removeKeyMonitor() })}- deinit { observers.forEach(NotificationCenter.default.removeObserver) }+ deinit {+ removeKeyMonitor()+ observers.forEach(NotificationCenter.default.removeObserver)+ }++ private func removeKeyMonitor() {+ if let searchKeyMonitor { NSEvent.removeMonitor(searchKeyMonitor) }+ searchKeyMonitor = nil+ searchKeyDispatch?.suspend()+ }++ private func setKeymap(_ map: HarnessNativeKeymap) {+ keymap = map+ if let searchKeyDispatch { searchKeyDispatch.update(map) }+ else { searchKeyDispatch = HarnessNativeKeyDispatch(map) }+ strip.searchField.usesKeymap = true+ strip.searchField.shortcutHint = map.hint(for: "navigation.quick_open", context: "workspace")+ if let main = NSApp.mainMenu, let window {+ let menu = main as? HarnessKeymapMenu ?? HarnessKeymapMenu.replacing(main)+ if NSApp.mainMenu !== menu { NSApp.mainMenu = menu }+ menu.update(map, window: window)+ }+ syncMenuKeys()+ guard searchKeyMonitor == nil else { return }+ // A local monitor is needed for ordinary letters that follow a custom+ // prefix. NSTextView's command delegate only receives editing commands;+ // it cannot stop a plain sequence suffix before it becomes query text.+ searchKeyMonitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .keyUp, .leftMouseDown, .rightMouseDown]) {+ [weak self] event in+ guard let self else { return event }+ return self.handleSearchKey(event)+ }+ }++ private func handleSearchKey(_ event: NSEvent) -> NSEvent? {+ guard let dispatch = searchKeyDispatch else { return event }+ if event.type == .leftMouseDown || event.type == .rightMouseDown {+ dispatch.cancel()+ return event+ }+ guard let window, event.window === window else { return event }+ // Consume the paired release even when a command just moved focus. It+ // must not leak half a keystroke into the newly selected agent.+ if event.type == .keyUp { return dispatch.release(event.keyCode) ? nil : event }+ guard actionsEnabled, strip.searchField.searching,+ let editor = strip.searchField.currentEditor() as? NSTextView,+ window.firstResponder === editor else {+ dispatch.cancel()+ return event+ }+ let result = dispatch.dispatch(HarnessKeyStroke.fromEvent(event), keyCode: event.keyCode,+ repeated: event.isARepeat, composing: editor.hasMarkedText(), context: "picker", owner: editor)+ if let command = result.command {+ if command == "navigation.quick_open" { editor.selectAll(nil) }+ else { channel.invokeMethod("keymapCommand", arguments: ["command": command]) }+ }+ return result.handled ? nil : event+ }++ private func syncMenuKeys() {+ guard let keymap, let main = NSApp.mainMenu else { return }+ let context = strip.searchField.currentEditor() == nil ? flutterKeyContext : "picker"+ keymap.applyMenuKeys(to: main, context: context)+ }private func configure() {guard let window, !configured else { return }@@ -101,6 +194,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {window.addTitlebarAccessoryViewController(accessory)resize()installWorkspaceMenus()+ if let keymap { setKeymap(keymap) }// An editable accessory must not become the window's initial input owner.window.makeFirstResponder(window.contentViewController)}@@ -123,6 +217,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {settings.target = selfsettings.action = #selector(menuAction(_:))settings.representedObject = "settings"+ settings.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "settings")settings.keyEquivalentModifierMask = [.command]if settings.menu == nil { appMenu.insertItem(settings, at: min(2, appMenu.numberOfItems)) }}@@ -131,6 +226,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {item.keyEquivalentModifierMask = modifiersitem.target = selfitem.representedObject = action+ item.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + action)menu.addItem(item)}func install(_ menu: NSMenu, at index: Int) {@@ -173,6 +269,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {}func menuWillOpen(_ menu: NSMenu) {+ syncMenuKeys()guard menu === modelsMenu, actionsEnabled else { return }// The native menu opens from its cache. Network/credential reads happen// asynchronously in Dart and never hold up AppKit's menu tracking.@@ -241,6 +338,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {let item = NSMenuItem(title: title, action: #selector(menuAction(_:)), keyEquivalent: key)item.target = selfitem.representedObject = action+ item.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + action)item.keyEquivalentModifierMask = [.command]historyMenu.addItem(item)}@@ -252,6 +350,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {appendHistorySection("Recently Visited", entries: Array(history.prefix(15)), closed: false)historyMenu.addItem(.separator())command("Show Full History", "y", "showHistory")+ if let keymap { keymap.applyMenuKeys(to: historyMenu, context: flutterKeyContext) }}private func appendHistorySection(_ title: String, entries: [SwarmHistoryEntry], closed: Bool) {@@ -295,6 +394,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {item.keyEquivalentModifierMask = modifiersitem.target = selfitem.representedObject = action+ item.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + action)menu.addItem(item)}// The template's find/replace actions target an unused text-editor handler.@@ -599,6 +699,8 @@ private final class SwarmSearchField: NSSearchField {var begin: (() -> Void)?var command: ((String) -> Void)?var searching = false { didSet { needsDisplay = true } }+ var usesKeymap = false+ var shortcutHint: String? = "⌘P" { didSet { needsDisplay = true } }override init(frame: NSRect) {super.init(frame: frame)cell = SwarmSearchCell(textCell: "")@@ -634,6 +736,7 @@ private final class SwarmSearchField: NSSearchField {super.mouseDown(with: event)}override func performKeyEquivalent(with event: NSEvent) -> Bool {+ if usesKeymap { return super.performKeyEquivalent(with: event) }if let editor = currentEditor() as? NSTextView,event.modifierFlags.intersection([.command, .option, .control, .shift]) == .command {if event.charactersIgnoringModifiers == "p" && !editor.hasMarkedText() {@@ -687,11 +790,13 @@ private final class SwarmSearchField: NSSearchField {rim.stroke()}super.draw(dirtyRect)- if !searching && stringValue.isEmpty && bounds.width >= 140 {- let shortcut = "⌘P" as NSString+ if !searching && stringValue.isEmpty && bounds.width >= 140, let shortcutHint,+ !shortcutHint.isEmpty {+ let shortcut = shortcutHint as NSStringlet attrs: [NSAttributedString.Key: Any] = [.font: NSFont.systemFont(ofSize: 11),.foregroundColor: NSColor.secondaryLabelColor]let size = shortcut.size(withAttributes: attrs)+ guard size.width <= bounds.width * 0.4 else { return }shortcut.draw(at: NSPoint(x: bounds.width - size.width - 12,y: (bounds.height - size.height) / 2), withAttributes: attrs)}@@ -701,10 +806,11 @@ private final class SwarmSearchField: NSSearchField {private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {private(set) var palette = SwarmNativePalette()var emit: ((String, Any?) -> Void)?+ var editingEnded: (() -> Void)?private let scroll = NSScrollView()private let document = NSView()private let newButton = NSButton()- private let searchField = SwarmSearchField()+ fileprivate let searchField = SwarmSearchField()private var lastSearchWidth: CGFloat = 0private var tabs: [SwarmTabButton] = []private var activeId = ""@@ -876,7 +982,9 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {guard searchField.searching else { return }emit?("searchChanged", ["query": searchField.stringValue])}+ func controlTextDidEndEditing(_ notification: Notification) { editingEnded?() }func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool {+ if searchField.usesKeymap { return false }let event = NSApp.currentEventguard let action = SwarmSearchField.resultCommand(NSStringFromSelector(selector), event: event,composing: textView.hasMarkedText()) else { return false }diff --git a/desktop/tool/check_keymap_native.sh b/desktop/tool/check_keymap_native.shindex 0310b590e..83b4fac4c 100644--- a/desktop/tool/check_keymap_native.sh+++ b/desktop/tool/check_keymap_native.sh@@ -14,3 +14,5 @@ cat macos/Runner/HarnessKeymap.swift tool/keymap_native_checks.swift > "$check_dxcrun 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"+HARNESS_TITLEBAR_KEYMAP_FIXTURE="$check_dir/bindings.json" \+ bash tool/check_swarm_titlebar.sh "$flutter_sdk" --window-layoutdiff --git a/desktop/tool/check_swarm_titlebar.sh b/desktop/tool/check_swarm_titlebar.shindex 8d1c046a2..2e202b4c4 100644--- a/desktop/tool/check_swarm_titlebar.sh+++ b/desktop/tool/check_swarm_titlebar.sh@@ -16,7 +16,8 @@ if [[ ! -d "$framework_dir/FlutterMacOS.framework/Modules" ]]; thenficheck_dir="$(mktemp -d "${TMPDIR:-/tmp}/harness-v2-titlebar.XXXXXX")"trap 'rm -rf "$check_dir"' EXIT-cat "$desktop_dir/macos/Runner/SwarmTitlebar.swift" \+cat "$desktop_dir/macos/Runner/HarnessKeymap.swift" \+ "$desktop_dir/macos/Runner/SwarmTitlebar.swift" \"$desktop_dir/tool/swarm_titlebar_checks.swift" > "$check_dir/main.swift"xcrun swiftc -swift-version 5 -module-cache-path "$check_dir/module-cache" \-F "$framework_dir" -framework FlutterMacOS \diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swiftindex ca9b24a64..fe70ec82f 100644--- a/desktop/tool/swarm_titlebar_checks.swift+++ b/desktop/tool/swarm_titlebar_checks.swift@@ -190,13 +190,118 @@ private extension SwarmTabStrip {// No engine, account, terminal or transport is involved in native layout.private final class TitlebarCheckMessenger: NSObject, FlutterBinaryMessenger {- func send(onChannel channel: String, message: Data?) {}- func send(onChannel channel: String, message: Data?, binaryReply callback: FlutterBinaryReply?) { callback?(nil) }+ var calls: [FlutterMethodCall] = []+ func send(onChannel channel: String, message: Data?) {+ if let message { calls.append(FlutterStandardMethodCodec.sharedInstance().decodeMethodCall(message)) }+ }+ func send(onChannel channel: String, message: Data?, binaryReply callback: FlutterBinaryReply?) {+ send(onChannel: channel, message: message)+ callback?(nil)+ }func setMessageHandlerOnChannel(_ channel: String, binaryMessageHandler handler: FlutterBinaryMessageHandler?) -> FlutterBinaryMessengerConnection { 1 }func cleanUpConnection(_ connection: FlutterBinaryMessengerConnection) {}}private extension SwarmTitlebar {+ func checkKeymapRuntime(_ fixture: [String: [String: Any]], messenger: TitlebarCheckMessenger) throws {+ guard let window, let defaults = HarnessNativeKeymap(fixture["defaults"]!),+ let changed = HarnessNativeKeymap(fixture["changed"]!) else {+ throw TitlebarCheckFailure(message: "Exported runtime keymaps exist")+ }+ let original = NSApp.mainMenu!+ let edit = original.item(withTitle: "Edit")!.submenu!+ let jump = edit.items.first(where: { $0.representedObject as? String == "jump" })!+ let file = original.item(withTitle: "File")!.submenu!+ let newSwarm = file.items.first(where: { $0.representedObject as? String == "new" })!+ let nativeCopy = NSMenuItem(title: "Copy", action: #selector(NSText.copy(_:)), keyEquivalent: "c")+ edit.addItem(nativeCopy)+ setKeymap(defaults)+ let main = NSApp.mainMenu as! HarnessKeymapMenu+ try checkTitlebar(main !== original && main.item(withTitle: "Edit")?.submenu === edit,+ "The main-menu dispatcher retains the actual Edit submenu and its targets")+ try checkTitlebar(jump.keyEquivalent == "p" && jump.toolTip?.contains("⌘P") == true,+ "Native shortcut display comes from the effective Dart binding")+ setKeymap(changed)+ try checkTitlebar(NSApp.mainMenu === main && jump.keyEquivalent == "o",+ "Hot reload updates the existing menu to the remapped key")+ try checkTitlebar(nativeCopy.keyEquivalent == "c" && nativeCopy.action == #selector(NSText.copy(_:)),+ "Standard native editing remains intact")+ // The inherited default is still first; a sequence is not falsely shown+ // as a second one-stroke accelerator in AppKit's shortcut column.+ let onlySequence = HarnessNativeKeymap(["version": 1, "contexts": Dictionary(uniqueKeysWithValues:+ ["workspace", "terminal", "picker"].map { ($0, [["keys": ["cmd+k", "n"], "command": "swarm.new",+ "hint": "⌘K N", "repeatable": false, "menuAction": "new"]]) })])!+ setKeymap(onlySequence)+ try checkTitlebar(newSwarm.keyEquivalent.isEmpty && newSwarm.toolTip?.contains("⌘K N") == true,+ "A sequence has a complete tooltip without a misleading first-key menu shortcut")+ try checkTitlebar(jump.keyEquivalent.isEmpty && jump.toolTip == nil,+ "Unbinding clears the old native shortcut and hint")+ rebuildHistoryMenu()+ try checkTitlebar(historyMenu.items.allSatisfy { $0.keyEquivalent.isEmpty },+ "Rebuilt History rows retain effective unbindings")+ setKeymap(changed)+ actionsEnabled = true+ strip.focusSearch()+ guard let editor = strip.searchField.currentEditor() as? NSTextView else {+ throw TitlebarCheckFailure(message: "Native search owns an editor for shortcut checks")+ }+ strip.setSearchState(["query": "workshop 木"])+ func event(_ text: String, _ code: UInt16, _ flags: NSEvent.ModifierFlags = [],+ up: Bool = false, repeated: Bool = false) -> NSEvent {+ NSEvent.keyEvent(with: up ? .keyUp : .keyDown, location: .zero, modifierFlags: flags,+ timestamp: 0, windowNumber: window.windowNumber, context: nil, characters: text,+ charactersIgnoringModifiers: text, isARepeat: repeated, keyCode: code)!+ }+ let open = event("o", 31, .command)+ let oldOpen = event("p", 35, .command)+ try checkTitlebar(main.defersToInput(open) && !main.defersToInput(oldOpen),+ "The menu yields the new key while the unbound old key has no native owner")+ try checkTitlebar(!main.performKeyEquivalent(with: open), "Menu key equivalents defer before dispatch")+ try checkTitlebar(handleSearchKey(oldOpen) === oldOpen, "Unbound search key is not claimed by a fallback")+ try checkTitlebar(handleSearchKey(open) == nil && editor.selectedRange().length == editor.string.utf16.count,+ "Remapped search shortcut selects the existing native query")+ try checkTitlebar(handleSearchKey(event("o", 31, .command, up: true)) == nil,+ "A claimed key-up cannot escape to another input")+ let down = event("\u{f701}", 125)+ try checkTitlebar(handleSearchKey(down) === down &&+ !strip.control(strip.searchField, textView: editor, doCommandBy: #selector(NSResponder.moveDown(_:))),+ "Unbound result navigation is not revived by NSTextView's delegate")+ messenger.calls.removeAll()+ let previous = event("j", 38, .control)+ NSApp.sendEvent(previous)+ try checkTitlebar(messenger.calls.filter { $0.method == "keymapCommand" }.count == 1 &&+ (messenger.calls.last?.arguments as? [String: Any])?["command"] as? String == "picker.previous",+ "The installed local monitor routes one remapped result action")+ 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+ _ = handleSearchKey(event("n", 45, .command))+ try checkTitlebar(messenger.calls.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))+ editor.setMarkedText("木", selectedRange: NSRange(location: 1, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0))+ let enter = event("\r", 36)+ try checkTitlebar(handleSearchKey(enter) === enter && searchKeyDispatch?.pending.isEmpty == true,+ "IME owns Return and cancels any partial shortcut")+ editor.unmarkText()+ _ = handleSearchKey(event("k", 40, .command))+ NotificationCenter.default.post(name: NSWindow.didResignKeyNotification, object: window)+ try checkTitlebar(searchKeyDispatch?.pending.isEmpty == true && window.firstResponder === editor,+ "Blur cancels a partial shortcut while preserving search input ownership")+ _ = handleSearchKey(event("k", 40, .command))+ setKeymap(defaults)+ try checkTitlebar(searchKeyDispatch?.pending.isEmpty == true && strip.searchField.shortcutHint == "⌘P",+ "Reload cancels a pending sequence and refreshes the native search hint")+ strip.closeSearch()+ let ordinary = event("x", 7)+ try checkTitlebar(handleSearchKey(ordinary) === ordinary,+ "The native monitor does not intercept Flutter or agent input")+ removeKeyMonitor()+ try checkTitlebar(searchKeyMonitor == nil, "The scoped event monitor is removed explicitly")+ }+func checkNativeContainer() throws {guard let window else { throw TitlebarCheckFailure(message: "Native test window exists") }let main = NSMenu()@@ -438,8 +543,13 @@ do {let content = TitlebarCheckContentController()content.view = NSView(frame: NSRect(x: 0, y: 0, width: 1280, height: 700))window.contentViewController = content- let titlebar = SwarmTitlebar(window: window, messenger: TitlebarCheckMessenger())+ let messenger = TitlebarCheckMessenger()+ let titlebar = SwarmTitlebar(window: window, messenger: messenger)try titlebar.checkNativeContainer()+ if let path = ProcessInfo.processInfo.environment["HARNESS_TITLEBAR_KEYMAP_FIXTURE"] {+ let fixture = try JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path))) as! [String: [String: Any]]+ try titlebar.checkKeymapRuntime(fixture, messenger: messenger)+ }window.close()print("AppKit Swarm titlebar: \(titlebarCheckCount) checks passed, including native window layout; no windows displayed.")} else {diff --git a/docs/harness-v2-keyboard-system.md b/docs/harness-v2-keyboard-system.mdindex 24f6ce937..e8f631d7e 100644--- a/docs/harness-v2-keyboard-system.md+++ b/docs/harness-v2-keyboard-system.md@@ -55,6 +55,6 @@ Parse and resolve when configuration changes, never on each keystroke. A lookup1. **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. **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.+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.diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.mdindex 79d7d1bfc..62c3de7cf 100644--- a/docs/harness-v2-progress.md+++ b/docs/harness-v2-progress.md@@ -4,6 +4,8 @@ Updated 2026-09-13 with coordinated palettes, Models, combined closed-work Histo## 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.