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.

Keep tab closes scoped during navigation (#920)

Dee207d10cabccc
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index b56c0c13d..44b5962d8 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -2378,9 +2378,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
case 'select':
if (args['id'] is String) app.selectSwarm(args['id']);
case 'close':
- if (args['id'] is String) await app.requestCloseSwarm(args['id']);
+ // Return native keyboard ownership after this frame, including while
+ // a close confirmation or remote stream cleanup is still pending.
+ if (args['id'] is String) unawaited(app.requestCloseSwarm(args['id']));
case 'closeActive':
- await app.requestCloseSwarm(app.activeSwarmId);
+ unawaited(app.requestCloseSwarm(app.activeSwarmId));
case 'rename':
// Acknowledge after the form opens so the titlebar can hand its native
// keyboard focus to Flutter while the user edits the name.
@@ -2531,6 +2533,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
const {
'select',
'close',
+ 'closeActive',
'new',
'rename',
'renameActive',
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 735a88ffa..abd6bfed4 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -2082,13 +2082,18 @@ class AppNotifier extends ChangeNotifier {
_tabStripHold = null;
}
}
+ selectedMachineId = focusedPane?.machineId;
if (persist) _persistLayout();
notifyListeners();
- selectedMachineId = focusedPane?.machineId;
_announceAppFocus();
for (final machine in machineStates.values) {
- // ⌘W closed a tab; the tiles it revealed are a person's.
- _attachPendingPanes(machine, intent: AttachIntent.person);
+ // Closing is navigation, just like selecting a tab. Attach newly visible
+ // panes without retrying retained error streams in other tabs.
+ _attachPendingPanes(
+ machine,
+ retryExisting: false,
+ intent: AttachIntent.person,
+ );
}
for (final pane in removed.panes) {
if (!allPanes.contains(pane)) await _detachSession(pane, sendClose: true);
diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dart
index c22cb916f..143b8b710 100644
--- a/desktop/lib/widgets/pane_grid.dart
+++ b/desktop/lib/widgets/pane_grid.dart
@@ -1466,8 +1466,12 @@ class _PaneContent extends StatelessWidget {
Widget build(BuildContext context) {
TerminalFontScope.watch(context);
final machine = notifier.stateOf(pane.machineId);
+ final swarmId = notifier.activeSwarmId;
void close() {
- notifier.requestClosePane(pane.id);
+ // A tab switch can precede the frame that replaces this callback. Shared
+ // panes keep their identity, so the pane id alone cannot identify its tab.
+ if (notifier.activeSwarmId != swarmId) return;
+ unawaited(notifier.requestClosePane(pane.id));
}
VoidCallback? split(PaneResizeAxis axis) =>
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index 8aebec0f8..8c7dff2a9 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -2718,6 +2718,7 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
}
}
private var downPoint = NSPoint.zero
+ private var lastSelectionClick: (time: TimeInterval, point: NSPoint)?
private var hovered = false
private var hoverTracking: NSTrackingArea?
override var acceptsFirstResponder: Bool { false }
@@ -2913,8 +2914,20 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
override func mouseDown(with event: NSEvent) {
guard actionsEnabled else { return }
downPoint = event.locationInWindow
- if event.clickCount == 2 { renameSwarm() }
- else { emit?("select", ["id": swarmId]) }
+ let first = lastSelectionClick
+ lastSelectionClick = event.clickCount == 1
+ ? (event.timestamp, event.locationInWindow) : nil
+ // AppKit's click count can span different controls, especially after a
+ // close shifts the next tab under the pointer. Rename only when this tab
+ // owned the first press as well.
+ if event.clickCount == 2, let first,
+ event.timestamp - first.time <= NSEvent.doubleClickInterval,
+ hypot(event.locationInWindow.x - first.point.x,
+ event.locationInWindow.y - first.point.y) <= 4 {
+ renameSwarm()
+ } else {
+ emit?("select", ["id": swarmId])
+ }
}
// The tab owns the full click sequence, including clicks on its padding.
// Forwarding mouseUp lets AppKit also treat a rename as a titlebar zoom.
diff --git a/desktop/test/swarm_close_race_test.dart b/desktop/test/swarm_close_race_test.dart
new file mode 100644
index 000000000..af25ca7c3
--- /dev/null
+++ b/desktop/test/swarm_close_race_test.dart
@@ -0,0 +1,195 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/terminal/terminal_session.dart';
+import 'package:harness/widgets/terminal_panel.dart';
+
+import 'keymap_runtime_test.dart' show native, nativeChannel;
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ for (final closeActive in [false, true]) {
+ test(
+ 'closing a ${closeActive ? 'selected' : 'background'} tab preserves retained error streams',
+ () async {
+ final app = createApp(connected: true);
+ addTearDown(app.dispose);
+ app.stateOf('m')!
+ ..nodeOnline = true
+ ..terminalCapabilityAvailable = true;
+ final session = terminal('a0', []);
+ final retained = app.adoptSessionForTest(session);
+ final first = app.activeSwarm;
+ app.newSwarm(name: 'Closing');
+ final closing = app.activeSwarm;
+ if (!closeActive) app.selectSwarm(first.id);
+ session.transportLost();
+ await app.closeSwarm(closing.id);
+ expect(app.activeSwarm, same(first));
+ expect(app.panes, [retained]);
+ expect(retained.session, same(session));
+ expect(
+ session.status,
+ TerminalSessionStatus.error,
+ reason: 'Closing a tab is navigation, not a retry of other terminals',
+ );
+ },
+ );
+ }
+
+ testWidgets(
+ 'a stale pane close cannot remove a shared pane from another tab',
+ (tester) async {
+ final app = createApp();
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ final first = app.activeSwarm;
+ app.newSwarm(name: 'Second');
+ await app.addAgentToSwarm('m', 'a0');
+ final second = app.activeSwarm;
+ app.selectSwarm(first.id);
+ try {
+ await mount(tester, app);
+ final close = tester
+ .widget<TerminalPanel>(find.byType(TerminalPanel))
+ .onClose!;
+ app.selectSwarm(second.id);
+ // Pointer release can arrive before the next frame replaces callbacks.
+ close();
+ await tester.pump();
+ expect(first.panes, [pane]);
+ expect(second.panes, [pane]);
+ expect(app.closedHistory, isEmpty);
+ tester.widget<TerminalPanel>(find.byType(TerminalPanel)).onClose!();
+ await tester.pump();
+ expect(app.swarms, [first]);
+ expect(first.panes, [pane]);
+ expect(pane.session, isNotNull);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ }
+ },
+ );
+
+ for (final method in ['close', 'closeActive']) {
+ testWidgets(
+ 'native $method acknowledges the new tab while stream cleanup waits',
+ (tester) async {
+ final app = createApp();
+ final closeReply = Completer<bool>();
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ nativeChannel,
+ (_) async => null,
+ );
+ final retained = app.adoptSessionForTest(terminal('a0', []));
+ final first = app.activeSwarm;
+ app.newSwarm(name: 'Closing');
+ final closing = app.activeSwarm;
+ app.adoptSessionForTest(
+ TerminalSession(
+ machineId: 'm',
+ agentId: 'a1',
+ agentName: 'Closing',
+ engineId: 'codex',
+ send: (type, _) => type == 'terminal_close'
+ ? closeReply.future
+ : Future.value(true),
+ sendBinary: (_) async => true,
+ )
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'closing-stream',
+ );
+ try {
+ await mount(tester, app, nativeTabs: true);
+ var acknowledged = false;
+ final reply = native(tester, method, {
+ 'id': closing.id,
+ }).then((_) => acknowledged = true);
+ await tester.pump();
+ await tester.pump();
+ expect(app.activeSwarm, same(first));
+ expect(app.panes, [retained]);
+ expect(
+ acknowledged,
+ isTrue,
+ reason: 'AppKit must return keyboard focus before remote cleanup finishes',
+ );
+ closeReply.complete(true);
+ await reply;
+ } finally {
+ if (!closeReply.isCompleted) closeReply.complete(true);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ nativeChannel,
+ null,
+ );
+ }
+ },
+ );
+ }
+
+ for (final confirmed in [false, true]) {
+ testWidgets(
+ 'native close returns input while a ${confirmed ? 'confirmed' : 'cancelled'} decision is pending',
+ (tester) async {
+ final app = createApp();
+ final review = Completer<bool>();
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ nativeChannel,
+ (_) async => null,
+ );
+ app.adoptSessionForTest(terminal('a0', []));
+ final first = app.activeSwarm;
+ app.newSwarm(name: 'Closing');
+ final closing = app.activeSwarm;
+ final pane = app.adoptSessionForTest(terminal('a1', []));
+ app.stateOf('m')!.agents = [
+ const Agent(
+ id: 'a1',
+ name: 'Closing',
+ engine: 'codex',
+ terminalAvailable: true,
+ closeSupported: true,
+ ),
+ ];
+ try {
+ await mount(tester, app, nativeTabs: true);
+ var reviewed = false;
+ app.reviewSessionClose = (targets, {tabName}) {
+ reviewed = true;
+ return review.future;
+ };
+ var acknowledged = false;
+ final reply = native(tester, 'close', {
+ 'id': closing.id,
+ }).then((_) => acknowledged = true);
+ await tester.pump();
+ await tester.pump();
+ expect(reviewed, isTrue);
+ expect(acknowledged, isTrue);
+ expect(app.activeSwarm, same(closing));
+ expect(app.swarms, [first, closing]);
+ expect(closing.panes, [pane]);
+ expect(app.closedHistory, isEmpty);
+ review.complete(confirmed);
+ await reply;
+ await tester.pump();
+ expect(app.swarms, confirmed ? [first] : [first, closing]);
+ expect(app.closedHistory, hasLength(confirmed ? 1 : 0));
+ } finally {
+ if (!review.isCompleted) review.complete(false);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ nativeChannel,
+ null,
+ );
+ }
+ },
+ );
+ }
+}
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index 17eae5a2e..b01662d5a 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -555,6 +555,28 @@ private extension SwarmTabButton {
NSGraphicsContext.restoreGraphicsState()
}
+ func checkClickOwnership() throws {
+ let originalEmit = emit
+ var actions: [String] = []
+ emit = { method, _ in actions.append(method) }
+ defer { emit = originalEmit }
+ func click(_ count: Int, time: TimeInterval) -> NSEvent {
+ NSEvent.mouseEvent(with: .leftMouseDown, location: NSPoint(x: 60, y: 20),
+ modifierFlags: [], timestamp: time, windowNumber: 0,
+ context: nil, eventNumber: count, clickCount: count, pressure: 1)!
+ }
+ // AppKit can carry its click count across tabs, including a tab that
+ // moved into the pointer's position after its neighbor was closed.
+ selectButton.mouseDown(with: click(2, time: 10))
+ try checkTitlebar(actions == ["select"],
+ "A second click originating on another tab selects this tab instead of renaming it")
+ actions.removeAll()
+ selectButton.mouseDown(with: click(1, time: 20))
+ selectButton.mouseDown(with: click(2, time: 20.1))
+ try checkTitlebar(actions == ["select", "rename"],
+ "A double-click that starts and ends on this tab still renames it")
+ }
+
func checkDoubleClickIsolation() throws {
let parent = nextResponder
let originalEmit = emit
@@ -1650,6 +1672,7 @@ private extension SwarmTabStrip {
update(covered)
try checkTitlebar(contextButton.nextBackground == nil, "A missing PR clears the joined background")
try checkTitlebar(contextButton.fieldButtons.isEmpty, "Leaving a context clears its former link controls")
+ try SwarmTabButton(id: "click-owner").checkClickOwnership()
try tabs[0].checkDoubleClickIsolation()
try checkTitlebar(tabs.count == 24 && newButton.isEnabled, "All overflow tabs and New Tab remain available")
try checkTitlebar(scroll.frame.maxX <= newButton.frame.minX &&