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.

Preserve native tab scroll and keyboard ownership

dee09e722997be5
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 89c0af307..271786762 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -416,7 +416,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
case 'closeActive':
await app.closeSwarm(app.activeSwarmId);
case 'rename':
- if (args['id'] is String) await _rename(args['id']);
+ // Acknowledge after the form opens so the titlebar can hand its native
+ // keyboard focus to Flutter while the user edits the name.
+ if (args['id'] is String) unawaited(_rename(args['id']));
case 'renameActive':
await _rename(app.activeSwarmId);
case 'next':
@@ -463,6 +465,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
case 'settings':
await _settings();
}
+ if (mounted &&
+ const {'select', 'close', 'new', 'rename'}.contains(call.method)) {
+ // Native tab controls wait for this reply before releasing keyboard
+ // ownership. The destination's actual focus tree must be ready first.
+ await WidgetsBinding.instance.endOfFrame;
+ if (mounted) FocusManager.instance.applyFocusChangesIfNeeded();
+ }
}
Future<void> _dialog(Future<void> Function() action) async {
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index f7ad79036..cf5ee22a9 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -29,12 +29,16 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
private var searchKeyDispatch: HarnessNativeKeyDispatch?
private var searchKeyMonitor: Any?
private var pendingKeyNames: [String] = []
+ private var tabActionGeneration = 0
init(window: NSWindow, messenger: FlutterBinaryMessenger) {
self.window = window
channel = FlutterMethodChannel(name: "harness/swarm_tabs", binaryMessenger: messenger)
super.init()
- strip.emit = { [weak self] method, args in self?.channel.invokeMethod(method, arguments: args) }
+ strip.emit = { [weak self] method, args in
+ guard let self else { return }
+ self.sendTabAction(method, arguments: args)
+ }
strip.editingEnded = { [weak self] in
self?.cancelKeySequence()
self?.syncMenuKeys()
@@ -112,6 +116,23 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
observers.forEach(NotificationCenter.default.removeObserver)
}
+ private func sendTabAction(_ method: String, arguments: Any?) {
+ guard ["select", "close", "new", "rename"].contains(method) else {
+ channel.invokeMethod(method, arguments: arguments)
+ return
+ }
+ tabActionGeneration += 1
+ let generation = tabActionGeneration
+ // Keyboard/VoiceOver activation can leave a button as responder. Wait for
+ // Flutter to apply the action before giving the next key to its content.
+ channel.invokeMethod(method, arguments: arguments) { [weak self, weak responder = window?.firstResponder] result in
+ guard let self, let window = self.window, generation == self.tabActionGeneration,
+ !(result is FlutterError), result as? NSObject !== FlutterMethodNotImplemented,
+ window.firstResponder === responder || window.firstResponder === window else { return }
+ window.makeFirstResponder(window.contentViewController)
+ }
+ }
+
private func removeKeyMonitor() {
if let searchKeyMonitor { NSEvent.removeMonitor(searchKeyMonitor) }
searchKeyMonitor = nil
@@ -832,6 +853,8 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
private var lastSearchWidth: CGFloat = 0
private var tabs: [SwarmTabButton] = []
private var activeId = ""
+ private var revealActiveAfterLayout = false
+ private var tabOrderChanged = false
private var actionsEnabled = false
override var mouseDownCanMoveWindow: Bool { true }
@@ -876,9 +899,12 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
}
actionsEnabled = state["enabled"] as? Bool == true
let rows = state["tabs"] as? [[String: Any]] ?? []
- activeId = state["activeId"] as? String ?? ""
+ let nextActiveId = state["activeId"] as? String ?? ""
+ revealActiveAfterLayout = revealActiveAfterLayout || nextActiveId != activeId
+ activeId = nextActiveId
let ids = rows.compactMap { $0["id"] as? String }
let previousOrder = tabs.map(\.swarmId)
+ tabOrderChanged = tabOrderChanged || ids != previousOrder
for tab in tabs where !ids.contains(tab.swarmId) { tab.removeFromSuperview() }
let previous = Dictionary(uniqueKeysWithValues: tabs.map { ($0.swarmId, $0) })
tabs = rows.compactMap { row in
@@ -889,7 +915,11 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
tab.selected = id == activeId
tab.actionsEnabled = actionsEnabled
tab.attention = (row["attention"] as? Int ?? 0) > 0
- tab.emit = { [weak self] method, args in self?.emit?(method, args) }
+ tab.emit = { [weak self, weak tab] method, args in
+ guard let self, let tab, self.actionsEnabled,
+ self.tabs.contains(where: { $0 === tab }) else { return }
+ self.emit?(method, args)
+ }
tab.hoverChanged = { [weak self] in self?.updateDividers() }
if tab.superview == nil { document.addSubview(tab) }
tab.needsDisplay = true
@@ -918,6 +948,10 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
override func layout() {
super.layout()
+ let active = tabs.first(where: { $0.swarmId == activeId })
+ let activeWasVisible = active.map { scroll.documentVisibleRect.intersects($0.frame) } ?? false
+ let previousScrollSize = scroll.frame.size
+ let previousDocumentSize = document.frame.size
let searchWidth: CGFloat = searchField.searching
? min(600, max(128, bounds.width - 184))
: bounds.width < 480 ? 128 : bounds.width < 720 ? 156 : 200
@@ -937,9 +971,12 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
lastSearchWidth = searchWidth
emit?("searchGeometry", ["width": searchWidth])
}
- if let active = tabs.first(where: { $0.swarmId == activeId }) {
+ let geometryChanged = scroll.frame.size != previousScrollSize || document.frame.size != previousDocumentSize
+ if let active, revealActiveAfterLayout || (activeWasVisible && (geometryChanged || tabOrderChanged)) {
document.scrollToVisible(active.frame)
}
+ revealActiveAfterLayout = false
+ tabOrderChanged = false
}
override func draw(_ dirtyRect: NSRect) {
// The selected tab meets this edge; its bottom corners are shoulders,
@@ -956,7 +993,9 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
if event.clickCount == 2 { window?.performZoom(nil) }
else { window?.performDrag(with: event) }
}
- @objc private func newSwarm() { emit?("new", nil) }
+ @objc private func newSwarm() {
+ if actionsEnabled && newButton.isEnabled { emit?("new", nil) }
+ }
private func beginSearch() {
guard actionsEnabled, !searchField.searching else { return }
searchField.searching = true
@@ -1012,15 +1051,22 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
}
return true
}
- override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { actionsEnabled ? .move : [] }
- override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation { actionsEnabled ? .move : [] }
+ private func draggedTab(_ sender: NSDraggingInfo) -> SwarmTabButton? {
+ guard actionsEnabled, sender.draggingSourceOperationMask.contains(.move),
+ let source = sender.draggingSource as? SwarmTabButton,
+ tabs.contains(where: { $0 === source }),
+ sender.draggingPasteboard.string(forType: swarmPasteboardType) == source.swarmId,
+ scroll.frame.contains(convert(sender.draggingLocation, from: nil)) else { return nil }
+ return source
+ }
+ override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { draggedTab(sender) == nil ? [] : .move }
+ override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation { draggedTab(sender) == nil ? [] : .move }
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
- guard actionsEnabled, let id = sender.draggingPasteboard.string(forType: swarmPasteboardType),
- tabs.contains(where: { $0.swarmId == id }) else { return false }
+ guard let source = draggedTab(sender), let old = tabs.firstIndex(where: { $0 === source }) else { return false }
let point = document.convert(sender.draggingLocation, from: nil)
let index = tabs.firstIndex(where: { point.x < $0.frame.midX }) ?? tabs.count
- let old = tabs.firstIndex(where: { $0.swarmId == id })!
- emit?("reorder", ["id": id, "index": max(0, index > old ? index - 1 : index)])
+ let destination = max(0, index > old ? index - 1 : index)
+ if destination != old { emit?("reorder", ["id": source.swarmId, "index": destination]) }
return true
}
}
@@ -1032,13 +1078,13 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
let swarmId: String
var name = "New swarm" { didSet { if name != oldValue { invalidateLabel(); updateAccessibility() } } }
var selected = false { didSet { if selected != oldValue { invalidateLabel(); updateAccessibility() } } }
- var attention = false
+ var attention = false { didSet { if attention != oldValue { needsDisplay = true; updateAccessibility() } } }
var showsDivider = false { didSet { if showsDivider != oldValue { needsDisplay = true } } }
var contentCenterY: CGFloat = 20
var emit: ((String, Any?) -> Void)?
var hoverChanged: (() -> Void)?
var isHovered: Bool { hovered && actionsEnabled }
- private let closeButton = NSButton()
+ private let closeButton = SwarmTabActionButton()
private let selectButton = SwarmSelectButton()
private var cachedLabel: NSAttributedString?
var actionsEnabled = true {
@@ -1059,6 +1105,7 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
setAccessibilityElement(true)
setAccessibilityRole(.group)
selectButton.owner = self
+ closeButton.owner = self
selectButton.title = ""
selectButton.isBordered = false
selectButton.target = self
@@ -1157,6 +1204,7 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
setAccessibilityLabel(name)
selectButton.setAccessibilityLabel("Select \(name)")
selectButton.setAccessibilityValue(selected ? "Selected" : "")
+ selectButton.setAccessibilityHelp(attention ? "Contains agents needing input" : nil)
toolTip = "\(name) — double-click to rename"
closeButton.setAccessibilityLabel("Close \(name)")
}
@@ -1189,8 +1237,16 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
/// Selection and closing are sibling accessibility buttons, so VoiceOver and
/// UI automation can reach the close action without treating the tab as a leaf.
-private final class SwarmSelectButton: NSButton {
+private class SwarmTabActionButton: NSButton {
weak var owner: SwarmTabButton?
+ override func becomeFirstResponder() -> Bool {
+ guard super.becomeFirstResponder() else { return false }
+ if let owner { owner.scrollToVisible(owner.bounds) }
+ return true
+ }
+}
+
+private final class SwarmSelectButton: SwarmTabActionButton {
override func mouseDown(with event: NSEvent) {
guard isEnabled else { return }
owner?.mouseDown(with: event)
diff --git a/desktop/test/swarm_interactions_test.dart b/desktop/test/swarm_interactions_test.dart
index 3b643adee..2a1ab34eb 100644
--- a/desktop/test/swarm_interactions_test.dart
+++ b/desktop/test/swarm_interactions_test.dart
@@ -13,6 +13,7 @@ import 'package:harness/settings/settings_screen.dart';
import 'package:harness/shared/widgets/app_select_field.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/codex_profile_field.dart';
import 'package:harness/widgets/new_agent_dialog.dart';
import 'package:harness/widgets/swarm_dialogs.dart';
@@ -138,6 +139,100 @@ void main() {
app.dispose();
});
+ testWidgets(
+ 'native tab replies wait for destination focus and allow rename input',
+ (tester) async {
+ const channel = MethodChannel('harness/swarm_tabs');
+ const codec = StandardMethodCodec();
+ final messenger = tester.binding.defaultBinaryMessenger;
+ messenger.setMockMethodCallHandler(channel, (_) async => true);
+ addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
+ final app = createApp();
+ final input = <TerminalBinaryFrame>[];
+ app.machineStates['m']!.nodeOnline = true;
+ app.adoptSessionForTest(terminal('a0', input));
+ final first = app.activeSwarmId;
+ app.newSwarm();
+ app.adoptSessionForTest(terminal('a1', input));
+ final second = app.activeSwarmId;
+ app.selectSwarm(first);
+ final projects = SwarmProjectStore();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ ),
+ ),
+ );
+ await tester.pump();
+
+ Future<void> activate(String method, [Object? args]) async {
+ final reply = Completer<void>();
+ messenger.handlePlatformMessage(
+ channel.name,
+ codec.encodeMethodCall(MethodCall(method, args)),
+ (bytes) {
+ try {
+ codec.decodeEnvelope(bytes!);
+ reply.complete();
+ } catch (error, stack) {
+ reply.completeError(error, stack);
+ }
+ },
+ );
+ for (var frame = 0; frame < 5 && !reply.isCompleted; frame++) {
+ await tester.pump();
+ }
+ expect(
+ reply.isCompleted,
+ isTrue,
+ reason: '$method must acknowledge its visible result',
+ );
+ await reply.future;
+ }
+
+ await activate('select', {'id': second});
+ expect(app.activeSwarmId, second);
+ // No extra frame between the native acknowledgement and the first key.
+ expect(tester.testTextInput.hasAnyClients, isTrue);
+ tester.testTextInput.enterText('x');
+ await tester.idle();
+ expect(input.single.streamId, 'stream-a1');
+ expect(String.fromCharCodes(input.single.bytes), 'x');
+ await activate('rename', {'id': second});
+ expect(find.text('Rename swarm'), findsOneWidget);
+ final name = tester.widget<TextField>(find.byType(TextField));
+ expect(name.focusNode!.hasPrimaryFocus, isTrue);
+ tester.testTextInput.enterText('Keyboard work');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pump();
+ expect(app.activeSwarm.name, 'Keyboard work');
+ expect(input, hasLength(1));
+
+ await activate('close', {'id': second});
+ expect(app.activeSwarmId, first);
+ expect(tester.testTextInput.hasAnyClients, isTrue);
+ tester.testTextInput.enterText('y');
+ await tester.idle();
+ expect(input.last.streamId, 'stream-a0');
+ expect(String.fromCharCodes(input.last.bytes), 'y');
+ await activate('close', {'id': first});
+ expect(app.swarms, hasLength(1));
+ expect(app.panes, isEmpty);
+ expect(app.activeSwarmId, isNot(anyOf(first, second)));
+ expect(find.text('Start a swarm'), findsOneWidget);
+ await activate('new');
+ expect(app.swarms, hasLength(2));
+ expect(input, hasLength(2));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ projects.dispose();
+ },
+ );
+
testWidgets('native Swarm commands cannot mutate the view behind Settings', (
tester,
) async {
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index 9c9023d91..52dbd6a6d 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -81,6 +81,22 @@ private extension SwarmTabStrip {
try tab.checkAccessibility(expectedName: "Swarm \(index)", active: index == 11)
}
try checkActiveVisible()
+ scroll.contentView.scroll(to: .zero)
+ scroll.reflectScrolledClipView(scroll.contentView)
+ let browsingOrigin = scroll.documentVisibleRect.origin
+ var refreshed = state(rows, active: "swarm-11")
+ var renamedRows = rows
+ renamedRows[0]["name"] = "Background task renamed"
+ refreshed["tabs"] = renamedRows
+ update(refreshed)
+ try checkTitlebar(scroll.documentVisibleRect.origin == browsingOrigin,
+ "A background title update preserves the tabs the user scrolled to")
+ refreshed["palette"] = ["workspace": Int64(0xff252d43)]
+ update(refreshed)
+ try checkTitlebar(scroll.documentVisibleRect.origin == browsingOrigin,
+ "A palette update does not undo manual tab scrolling")
+ update(state(rows, active: "swarm-23"))
+ try checkActiveVisible()
setFrameSize(NSSize(width: 320, height: 40))
needsLayout = true
layoutSubtreeIfNeeded()
@@ -155,6 +171,7 @@ private extension SwarmTabStrip {
newButton.performClick(nil)
focusSearch()
try checkTitlebar(events.isEmpty, "Disabled controls emit no actions")
+ try checkDragOperations()
}
}
@@ -186,17 +203,153 @@ private extension SwarmTabStrip {
try checkTitlebar(window.firstResponder === window.contentViewController,
"Closing native search returns keyboard events to the content controller")
}
+
+ func checkTabKeyboardFocus(_ window: NSWindow, messenger: TitlebarCheckMessenger) throws {
+ update(["enabled": true, "activeId": "keyboard-23",
+ "tabs": (0..<24).map { ["id": "keyboard-\($0)", "name": "Keyboard \($0)"] }])
+ let tab = tabs[0]
+ let buttons = tab.accessibilityChildren()!.compactMap { $0 as? NSButton }
+ for button in buttons {
+ try checkTitlebar(window.makeFirstResponder(button), "An enabled tab action accepts keyboard focus")
+ try checkTitlebar(scroll.documentVisibleRect.contains(tab.frame),
+ "Keyboard focus reveals the entire overflowed tab and close control")
+ try checkTitlebar(activeId == "keyboard-23", "Focusing a tab control does not activate its swarm")
+ let before = messenger.calls.count
+ messenger.holdReplies = true
+ button.performClick(nil)
+ try checkTitlebar(window.firstResponder === button,
+ "Typing stays out of the old workspace until the tab action is acknowledged")
+ messenger.finishNextReply()
+ try checkTitlebar(window.firstResponder === window.contentViewController,
+ "Activating a tab action returns the next key to Flutter content")
+ try checkTitlebar(messenger.calls.count == before + 1, "Each native tab activation sends one action")
+ }
+ tab.attention = true
+ try checkTitlebar(buttons[0].accessibilityHelp()?.contains("needing input") == true,
+ "The attention dot has an accessible description")
+ tab.attention = false
+ try checkTitlebar(buttons[0].accessibilityHelp() == nil, "Resolved attention clears its accessible description")
+ try checkTitlebar(window.makeFirstResponder(buttons[0]), "Rename starts from an actual focused control")
+ let rename = tab.menu!.items.first!
+ NSApp.sendAction(rename.action!, to: rename.target, from: rename)
+ messenger.finishNextReply()
+ try checkTitlebar(window.firstResponder === window.contentViewController && messenger.calls.last?.method == "rename",
+ "Renaming gives the Flutter form native keyboard ownership")
+ let stale = tab
+ update(["enabled": true, "activeId": "survivor", "tabs": [["id": "survivor", "name": "Survivor"]]])
+ let beforeStale = messenger.calls.count
+ stale.clickBothActions()
+ try checkTitlebar(messenger.calls.count == beforeStale, "A removed tab's retained controls cannot dispatch actions")
+ try checkTitlebar(window.makeFirstResponder(newButton), "New swarm accepts keyboard focus")
+ newButton.performClick(nil)
+ messenger.finishNextReply()
+ try checkTitlebar(window.firstResponder === window.contentViewController && messenger.calls.last?.method == "new",
+ "New swarm returns keyboard ownership to the workspace")
+ let current = tabs[0].accessibilityChildren()!.first as! NSButton
+ window.makeFirstResponder(current)
+ current.performClick(nil)
+ focusSearch()
+ let editor = window.firstResponder
+ messenger.finishNextReply()
+ try checkTitlebar(window.firstResponder === editor && editor is NSTextView,
+ "A delayed tab reply cannot steal focus from a newer search")
+ closeSearch()
+ window.makeFirstResponder(current)
+ current.performClick(nil)
+ current.performClick(nil)
+ messenger.finishNextReply()
+ try checkTitlebar(window.firstResponder === current, "An older tab action cannot release a newer action's focus")
+ messenger.finishNextReply()
+ try checkTitlebar(window.firstResponder === window.contentViewController,
+ "The latest acknowledged tab action restores content focus")
+ messenger.holdReplies = false
+ }
+}
+
+private final class TitlebarCheckDrag: NSObject, NSDraggingInfo {
+ var draggingDestinationWindow: NSWindow?
+ var draggingSourceOperationMask: NSDragOperation = .move
+ var draggingLocation = NSPoint.zero
+ var draggedImageLocation = NSPoint.zero
+ var draggedImage: NSImage? { nil }
+ let draggingPasteboard = NSPasteboard.withUniqueName()
+ var draggingSource: Any?
+ var draggingSequenceNumber: Int { 1 }
+ var draggingFormation: NSDraggingFormation = .none
+ var animatesToDestination = false
+ var numberOfValidItemsForDrop = 1
+ var springLoadingHighlight: NSSpringLoadingHighlight { .none }
+ func slideDraggedImage(to screenPoint: NSPoint) {}
+ override func namesOfPromisedFilesDropped(atDestination dropDestination: URL) -> [String]? { nil }
+ func resetSpringLoading() {}
+ func enumerateDraggingItems(options: NSDraggingItemEnumerationOptions, for view: NSView?, classes: [AnyClass],
+ searchOptions: [NSPasteboard.ReadingOptionKey: Any], using block: (NSDraggingItem, Int, UnsafeMutablePointer<ObjCBool>) -> Void) {}
+ deinit { draggingPasteboard.releaseGlobally() }
+}
+
+private extension SwarmTabStrip {
+ func checkDragOperations() throws {
+ setFrameSize(NSSize(width: 900, height: 40))
+ let rows = (0..<4).map { ["id": "drag-\($0)", "name": "Drag \($0)"] }
+ update(["tabs": rows, "activeId": "drag-0", "enabled": true])
+ var moves: [[String: Any]] = []
+ emit = { method, args in if method == "reorder", let args = args as? [String: Any] { moves.append(args) } }
+ let info = TitlebarCheckDrag()
+ info.draggingSource = tabs[0]
+ info.draggingPasteboard.setString("drag-0", forType: swarmPasteboardType)
+ info.draggingLocation = document.convert(NSPoint(x: tabs[2].frame.midX + 1, y: 20), to: nil)
+ try checkTitlebar(draggingEntered(info) == .move && draggingUpdated(info) == .move,
+ "An owned tab can move within the visible tab area")
+ try checkTitlebar(performDragOperation(info) && moves.last?["index"] as? Int == 2,
+ "Moving right accounts for removing the source tab first")
+ moves.removeAll()
+ info.draggingLocation = document.convert(NSPoint(x: tabs[0].frame.midX - 1, y: 20), to: nil)
+ try checkTitlebar(performDragOperation(info) && moves.isEmpty, "Dropping in place performs no redundant reorder")
+ info.draggingSource = tabs[3]
+ info.draggingPasteboard.setString("drag-3", forType: swarmPasteboardType)
+ try checkTitlebar(performDragOperation(info) && moves.last?["index"] as? Int == 0,
+ "Moving left preserves the requested first position")
+ moves.removeAll()
+ func rejected(_ reason: String) throws {
+ try checkTitlebar(draggingEntered(info).isEmpty && draggingUpdated(info).isEmpty && !performDragOperation(info), reason)
+ try checkTitlebar(moves.isEmpty, "Rejected drag emits no reorder")
+ }
+ info.draggingLocation = convert(NSPoint(x: searchField.frame.midX, y: 20), to: nil)
+ try rejected("Search is not a tab drop target")
+ info.draggingLocation = document.convert(NSPoint(x: tabs[0].frame.midX, y: 20), to: nil)
+ info.draggingSource = SwarmTabButton(id: "drag-3")
+ try rejected("A foreign tab with a matching ID cannot reorder this strip")
+ info.draggingSource = tabs[3]
+ info.draggingSourceOperationMask = .copy
+ try rejected("A copy-only source is not advertised as movable")
+ info.draggingSourceOperationMask = .move
+ info.draggingPasteboard.setString("drag-0", forType: swarmPasteboardType)
+ try rejected("The pasteboard identity must match the actual dragged tab")
+ info.draggingPasteboard.setString("drag-3", forType: swarmPasteboardType)
+ update(["tabs": rows, "activeId": "drag-0", "enabled": false])
+ try rejected("A modal rejects a pending tab drop")
+ update(["tabs": Array(rows.prefix(3)), "activeId": "drag-0", "enabled": true])
+ try rejected("A removed source cannot finish its pending drag")
+ }
}
// No engine, account, terminal or transport is involved in native layout.
private final class TitlebarCheckMessenger: NSObject, FlutterBinaryMessenger {
var calls: [FlutterMethodCall] = []
+ var holdReplies = false
+ var replies: [FlutterBinaryReply] = []
+ func finishNextReply() {
+ replies.removeFirst()(FlutterStandardMethodCodec.sharedInstance().encodeSuccessEnvelope(nil))
+ }
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)
+ if let callback {
+ if holdReplies { replies.append(callback) }
+ else { callback(FlutterStandardMethodCodec.sharedInstance().encodeSuccessEnvelope(nil)) }
+ }
}
func setMessageHandlerOnChannel(_ channel: String, binaryMessageHandler handler: FlutterBinaryMessageHandler?) -> FlutterBinaryMessengerConnection { 1 }
func cleanUpConnection(_ connection: FlutterBinaryMessengerConnection) {}
@@ -302,7 +455,7 @@ private extension SwarmTitlebar {
try checkTitlebar(searchKeyMonitor == nil, "The scoped event monitor is removed explicitly")
}
- func checkNativeContainer() throws {
+ func checkNativeContainer(messenger: TitlebarCheckMessenger) throws {
guard let window else { throw TitlebarCheckFailure(message: "Native test window exists") }
let main = NSMenu()
let appItem = NSMenuItem(title: "Harness V2", action: nil, keyEquivalent: "")
@@ -482,6 +635,7 @@ private extension SwarmTitlebar {
try strip.checkWindowGeometry(window)
}
try strip.checkSearchEditing(window)
+ try strip.checkTabKeyboardFocus(window, messenger: messenger)
try checkTitlebar(!window.isVisible, "Native layout check never displays its window")
}
}
@@ -545,7 +699,7 @@ do {
window.contentViewController = content
let messenger = TitlebarCheckMessenger()
let titlebar = SwarmTitlebar(window: window, messenger: messenger)
- try titlebar.checkNativeContainer()
+ try titlebar.checkNativeContainer(messenger: messenger)
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)
diff --git a/docs/harness-v2-developer-tools-research.md b/docs/harness-v2-developer-tools-research.md
index 0ed6a8b4b..d065a6e72 100644
--- a/docs/harness-v2-developer-tools-research.md
+++ b/docs/harness-v2-developer-tools-research.md
@@ -13,6 +13,7 @@ Updated 2026-09-13 after user review. Keep the existing simple Command shortcuts
| Status | Work |
| --- | --- |
| In the preview | Real machine/project data; native Swarm tabs; wallpaper only in New swarm; Cmd+P jump, Needs input and terminal Find. |
+| Native tab behavior implemented and regression checked | Background updates preserve manually scrolled overflow. Keyboard/accessible controls reveal their tab and hand input back after Flutter's visible destination is ready; late replies preserve newer focus. Drops are restricted to owned tabs in the visible tab area. Hidden-window and synthetic-session checks cover these policies; live pointer/VoiceOver use remains unverified. |
| Fixed and rebuilt | Cmd+P stale focus/offscreen targets; retained offline output and composer drafts; blocking frozen overlays removed. |
| In the rebuilt preview | Settings gear removed on macOS; native File/History menus and Cmd+P routing. Menus and picker typing verified live; focus/input regression tests pass. |
| Rebuilt; native menu reviewed live | Models replaces Swarm; Subscription shows existing account limits, while API, Local and Add Model are disabled placeholders. History uses provider icons and restores both closed agents and closed Swarms. Recovery is covered with isolated sessions; live agents were not closed to test it. |
@@ -106,6 +107,12 @@ Apple's [native menu documentation](https://developer.apple.com/documentation/sw
Chrome is the user's primary interaction reference. Chromium's [menu definition](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/chrome/browser/ui/cocoa/main_menu_builder.mm) and [History bridge](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/chrome/browser/ui/cocoa/history_menu_bridge.mm) inform Back/Forward, direct Recently Closed/Recently Visited sections, and Show Full History. Harness shows up to 10 closed agents or Swarms and 15 recent destinations there. Navigation retains at most 64 recent identities, a 128-entry exact-pane Back/Forward trail, and a combined 24-close recovery list. Show Full History searches those recoverable destinations and explicitly says **This session**. History does not persist across app exit or collect terminal commands, prompts or output. These bounded session records are not a durable all-time browser history.
+## Tab navigation and attention
+
+Chromium's [tab design notes](https://www.chromium.org/user-experience/tabs/) treat each tab and its content as an independent unit and describe spatial keyboard switching. Its overflow section describes shrinking tabs; it does not establish a policy for preserving manual horizontal scrolling. Harness's minimum-width overflow policy is our adaptation: background agent activity should not move the strip the developer is currently exploring. A deliberate selection reveals its destination, while background metadata updates keep the chosen scroll position. AppKit's [scroll-to-visible API](https://developer.apple.com/documentation/appkit/nsview/scrolltovisible%28_%3A%29) also lets a keyboard-focused tab reveal its own complete control area without selecting another swarm.
+
+The September 13 native audit found and reproduced automatic scroll reset during background title updates. It also addressed native button focus after activation and rejects tab drops over Search or from stale/foreign controls. Passing isolated tests establish these local policies and input routing; they do not establish live pointer/VoiceOver usability or input-to-display latency. The next validation remains an isolated real-window pass once foreground access works.
+
## Reductions and prototype follow-up
[The prototype review](harness-v2-prototype-review.md) covers all six variants in `harness-new-ui` at `19ced37`. Keep the terminal canvas and chosen Swarms; borrow optional contextual preview, explicit splits and exact return selectively. Leave out V3's primary/supporting hierarchy, persistent shelf, extra status/footer/context rows, model dashboard, and V4's default replacement of the active pane. Use the current easy Command prefix instead of copying Ctrl+B.
diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.md
index 1a5efdb43..33d46b9d1 100644
--- a/docs/harness-v2-progress.md
+++ b/docs/harness-v2-progress.md
@@ -2,6 +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.
+## Native tab interaction checkpoint
+
+- A reproduced overflow regression let background name/status/palette updates snap the strip back to the active tab. The strip now preserves manual scrolling during those updates, reveals a newly selected tab, and keeps a previously visible active tab in view when the strip's geometry or order changes.
+- Keyboard focus reveals the complete tab and its close control. Select, close, new and rename return native keyboard ownership after Flutter acknowledges the destination's rendered focus tree. Rename acknowledges its open form instead of waiting for it to close. Late replies cannot steal a newer Search field or release a newer tab action's focus. The attention dot has an accessible description that clears when resolved.
+- Reordering accepts only an actual tab owned by this strip, with a matching private pasteboard identity and a move operation inside the visible tab area. Search, foreign/stale controls, disabled actions and removed sources cannot reorder the swarm. Dropping in place sends no redundant reorder.
+- Validation: **21 focused Flutter checks passed**, including first text immediately after native select/close acknowledgements, immediate rename input, and closing the last swarm. **51 native decoder checks and 361 AppKit checks passed**, using actual Dart-exported bindings and a hidden window. Analyzer has zero errors/warnings and the existing 12 vendored infos. Artifacts: `/private/tmp/harness-v2-native-tab-{routing-tests,keymap-final,analyze}.log`; the pre-fix overflow failure is `/private/tmp/harness-v2-native-overflow-before.log`.
+- These are isolated keyboard/focus, drop-policy and layout checks, not a live VoiceOver session, pointer-drag audit or native latency measurement. Real agents received no test input. Release rebuild follows this checkpoint; public-origin push approval remains pending.
+
## Git context recovery checkpoint
- Three regressions reproduced stale branch context after a worktree pointer changed or a directory watch ended/errored. The local compatibility reader now watches the working tree's `.git` connection, follows changed Git/common directories, and rebinds subscriptions after same-path directory replacement. Removed working folders clear their cached context instead of borrowing the parent repository.
@@ -428,7 +436,7 @@ Earlier logs contain superseded failures. Temporary logs and toolchains are loca
## Remaining work
1. Measure native terminal input and tab-switch responsiveness under output load, including p50/p95/p99 and cold/warm paths. Calibration is paused until there is new evidence that the isolated window can become active/key; do not bypass its focus guard. Earlier live Cmd+P destination focus/quick return, branch headers, project associations, New swarm cleanup and native History were verified. Keep typing/transport measurements in disposable fixtures; the user's real agent terminals are not test inputs.
-2. Audit native drag/reorder, overflow, close-last-tab, renaming and accessibility without changing the user's saved agent memberships. Keep any integration runner separate and out of the foreground review app.
+2. Native overflow, drop ownership/bounds, close-last-tab, rename and keyboard/accessibility control focus are now covered by isolated AppKit/Flutter regressions. Live pointer dragging and VoiceOver still need a foreground-capable disposable window. Keep any integration runner separate and out of the foreground review app; preserve saved agent memberships.
3. Verify real remote reconnect, agent input, paste, selection and IME against disposable local/remote processes. The AppNotifier/keyframe and stale completion regressions now pass; they do not prove every network or native editing condition. Preserve immediate first-input flush and shared retained renderers.
4. Visually confirm app-menu modal behavior and overflow accessibility in AppKit; route/shortcut behavior is covered by passing Flutter tests.
5. Build/review Linux and Windows when their toolchains are available. Remote full project/branch metadata requires daemons running the new wire format; do not upgrade them automatically.