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 routine agent and dial events out of workspace rebuilds

dee99d1ac90922b
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 5b8a75876..b585e6694 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -3496,8 +3496,8 @@ class AppNotifier extends ChangeNotifier {
String _turnActivityKey(String machineId, String agentId) =>
'$machineId\u0000$agentId';
- void _markAgentProcessing(MachineState machine, String agentId) {
- machine.processingAgentIds.add(agentId);
+ bool _markAgentProcessing(MachineState machine, String agentId) {
+ final changed = machine.processingAgentIds.add(agentId);
final key = _turnActivityKey(machine.machine.machineId, agentId);
_turnActivityWatchdogs.remove(key)?.cancel();
_turnActivityWatchdogs[key] = Timer(turnActivityTimeout, () {
@@ -3510,6 +3510,7 @@ class AppNotifier extends ChangeNotifier {
if (!identical(current, machine)) return;
if (machine.processingAgentIds.remove(agentId)) notifyListeners();
});
+ return changed;
}
/// Whether this agent is mid-turn, by the app's own reckoning.
@@ -5174,29 +5175,16 @@ class AppNotifier extends ChangeNotifier {
if (machine == null) return;
final type = event['type'] as String? ?? '';
final payload = (event['payload'] as Map<String, dynamic>?) ?? {};
- // EVERY tile on this machine sees the frame, and each decides for itself.
- //
- // Not a routing choice — a correctness one. `handleFrame` answers "this was
- // a terminal frame", NOT "this was mine": a session that is not the one
- // being addressed still returns true so the app-level switch skips it. With
- // one terminal those two meanings were the same sentence. With four they
- // are not, and stopping at the first `true` would have let whichever tile
- // happened to be first swallow another tile's `terminal_ready` — the reply
- // is matched by requestId AND agentId inside the session, so only the right
- // one acts on it, but only if it is allowed to see it.
- //
- // It also fixes a fault that was invisible at one tile: a
- // `terminal_transport_error` describes the whole connection, and every
- // session must learn the transport died. Stopping early would have told one
- // tile and left the rest showing a terminal that can no longer receive
- // anything.
- var consumedByTerminal = false;
- for (final pane in panesFor(machineId).toList()) {
- final session = pane.session;
- if (session == null) continue;
- if (await session.handleFrame(type, payload)) consumedByTerminal = true;
+ // Only terminal protocol frames visit the session pool. Heartbeats, dial
+ // scroll and discovery events must not await every retained terminal.
+ // Each session still sees terminal frames: ready replies match their own
+ // request/agent, while transport errors must reach the whole machine.
+ if (type.startsWith('terminal_')) {
+ for (final pane in panesFor(machineId).toList()) {
+ await pane.session?.handleFrame(type, payload);
+ }
+ return;
}
- if (consumedByTerminal) return;
switch (type) {
// ── the dial, over the cable, forwarded by the local daemon ──────────────────────────────────
// Local-only frames (backend.sendLocal in the harness CLI): they describe a hand at THIS desk, so
@@ -5205,7 +5193,7 @@ class AppNotifier extends ChangeNotifier {
// The dial came, went, or started taking an update. Its own notifier —
// see [dial] — so nothing else in the window rebuilds for it.
dial.apply(DialStatus.fromJson(payload));
- break;
+ return;
case 'dial_scroll':
// Straight through, including the reports carrying no travel — the ends of a stroke are the point
// of the message. The window does no arithmetic here; the terminal that owns the scrollback does.
@@ -5219,7 +5207,7 @@ class AppNotifier extends ChangeNotifier {
(payload['dy'] as num?)?.round() ?? 0,
(payload['velocity'] as num?)?.round() ?? 0,
);
- break;
+ return;
case 'device_focus':
unawaited(ensureDeviceFocus(payload));
break;
@@ -5397,9 +5385,10 @@ class AppNotifier extends ChangeNotifier {
// turn already under way, which for an agent this app merely reconnected
// to is work nobody here just asked for.
if (type == 'turn_started') _reportFirstMessage();
+ var changed = false;
final agentId = _eventAgentId(machine, event, payload);
if (agentId != null) {
- _markAgentProcessing(machine, agentId);
+ changed = _markAgentProcessing(machine, agentId);
// Only a START opens a stats turn, for the reason above: a heartbeat
// is a turn already under way, and counting one would report an agent
// this app merely reconnected to as work somebody just asked for.
@@ -5411,9 +5400,12 @@ class AppNotifier extends ChangeNotifier {
} else {
final sessionId = _eventSessionId(event, payload);
if (sessionId != null) {
- machine.pendingProcessingSessions.add(sessionId);
+ changed = machine.pendingProcessingSessions.add(sessionId);
}
}
+ // Renew the watchdog on every heartbeat, but redraw only when the
+ // agent first becomes busy. Expiry and turn end publish separately.
+ if (!changed) return;
break;
case 'turn_ended':
final agentId = _eventAgentId(machine, event, payload);
diff --git a/desktop/test/swarm_terminal_routing_test.dart b/desktop/test/swarm_terminal_routing_test.dart
index 23c4c336a..903a02b55 100644
--- a/desktop/test/swarm_terminal_routing_test.dart
+++ b/desktop/test/swarm_terminal_routing_test.dart
@@ -42,6 +42,68 @@ TerminalBinaryFrame _frame(
);
void main() {
+ test(
+ 'JSON replies reach a hidden matching terminal after other sessions',
+ () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final first = _session('a0', _streamA);
+ app.adoptSessionForTest(first);
+ app.newSwarm();
+ Map<String, dynamic>? request;
+ final second = TerminalSession(
+ machineId: 'm',
+ agentId: 'a1',
+ agentName: 'Second',
+ engineId: 'codex',
+ send: (type, payload) async {
+ if (type == 'terminal_open') request = payload;
+ return true;
+ },
+ sendBinary: (_) async => true,
+ );
+ app.adoptSessionForTest(second);
+ await second.open();
+ app.newSwarm();
+ final peer = _session('a1', _streamB, machineId: 'peer');
+ app.adoptSessionForTest(peer);
+
+ await app.handleEventForTest('m', {
+ 'type': 'terminal_ready',
+ 'payload': {
+ 'agentId': 'a1',
+ 'requestId': request!['requestId'],
+ 'protocolVersion': 3,
+ 'streamId': _streamB,
+ },
+ });
+ await app.handleTerminalBinaryForTest(
+ 'm',
+ encodeTerminalLocal(_frame(_streamB, 0, 'Ready', keyframe: true))!,
+ );
+ expect(second.status, TerminalSessionStatus.controlling);
+ expect(second.terminal.buffer.getText(), contains('Ready'));
+ expect(first.terminal.buffer.getText(), isNot(contains('Ready')));
+ expect(peer.terminal.buffer.getText(), isNot(contains('Ready')));
+
+ await app.handleEventForTest('m', {
+ 'type': 'terminal_link_mode',
+ 'payload': {'streamId': _streamB, 'mode': 'p2p'},
+ });
+ expect(second.linkMode, 'p2p');
+ expect(first.linkMode, isNull);
+ expect(peer.linkMode, isNull);
+
+ await app.handleEventForTest('m', {
+ 'type': 'terminal_transport_error',
+ 'payload': {'code': 'TEST_CONNECTION_LOST'},
+ });
+ expect(first.status, TerminalSessionStatus.error);
+ expect(second.status, TerminalSessionStatus.error);
+ expect(peer.status, TerminalSessionStatus.controlling);
+ },
+ );
+
test(
'reordering swarms between incoming frames preserves stream order',
() async {
diff --git a/desktop/test/workspace_event_isolation_test.dart b/desktop/test/workspace_event_isolation_test.dart
new file mode 100644
index 000000000..9e329201d
--- /dev/null
+++ b/desktop/test/workspace_event_isolation_test.dart
@@ -0,0 +1,190 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/terminal/terminal_session.dart';
+import 'package:harness/widgets/terminal_panel.dart';
+import 'package:xterm/xterm.dart';
+
+import 'swarm_screen_test.dart' show mount;
+import 'swarm_state_test.dart' show createApp;
+
+class _ObservedSession extends TerminalSession {
+ _ObservedSession(String id, List<TerminalBinaryFrame> input)
+ : super(
+ machineId: 'm',
+ agentId: id,
+ agentName: 'Session $id',
+ engineId: 'codex',
+ send: (_, _) async => true,
+ sendBinary: (frame) async {
+ if (frame.kind == TerminalBinaryKind.input) input.add(frame);
+ return true;
+ },
+ ) {
+ status = TerminalSessionStatus.controlling;
+ streamId = 'stream-$id';
+ }
+
+ int frameCalls = 0;
+
+ @override
+ Future<bool> handleFrame(String type, Map<String, dynamic> payload) {
+ frameCalls++;
+ return super.handleFrame(type, payload);
+ }
+}
+
+Future<void> _event(
+ AppNotifier app,
+ String type, [
+ Map<String, dynamic> payload = const {},
+]) => app.handleEventForTest('m', {'type': type, 'payload': payload});
+
+void main() {
+ for (final activity in ['heartbeats', 'dial scroll']) {
+ testWidgets('$activity leave the surrounding workspace idle', (
+ tester,
+ ) async {
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ final sessions = <_ObservedSession>[];
+ final inputs = List.generate(16, (_) => <TerminalBinaryFrame>[]);
+ final first = app.activeSwarmId;
+ for (var tab = 0; tab < 4; tab++) {
+ if (tab > 0) app.newSwarm();
+ for (var pane = 0; pane < 4; pane++) {
+ final index = tab * 4 + pane;
+ final session = _ObservedSession('a$index', inputs[index]);
+ session.terminal.write(
+ List.generate(200, (line) => 'History $line\r\n').join(),
+ );
+ sessions.add(session);
+ app.adoptSessionForTest(session);
+ await _event(app, 'turn_started', {'agentId': session.agentId});
+ }
+ }
+ final previousObserver = debugOnRebuildDirtyWidget;
+ try {
+ await mount(tester, app);
+ for (final tab in app.swarms) {
+ app.selectSwarm(tab.id);
+ await tester.pump();
+ }
+ app.selectSwarm(first);
+ app.focusPane(app.panes.first.id);
+ await tester.pump();
+ await tester.pump();
+ expect(
+ find.byType(TerminalPanel, skipOffstage: false),
+ findsNWidgets(16),
+ );
+ final views = tester
+ .widgetList<TerminalView>(
+ find.byType(TerminalView, skipOffstage: false),
+ )
+ .toList();
+ final scrolls = {
+ for (final view in views) view.terminal: view.scrollController!,
+ };
+ final before = {
+ for (final entry in scrolls.entries) entry.key: entry.value.offset,
+ };
+ final focus = FocusManager.instance.primaryFocus;
+ final rebuilds = <String, int>{};
+ var notifications = 0;
+ app.addListener(() => notifications++);
+ for (final session in sessions) {
+ session.frameCalls = 0;
+ }
+ debugOnRebuildDirtyWidget = (element, _) {
+ final type = element.widget.runtimeType.toString();
+ rebuilds.update(type, (count) => count + 1, ifAbsent: () => 1);
+ };
+
+ if (activity == 'heartbeats') {
+ for (final session in sessions) {
+ await _event(app, 'turn_heartbeat', {'agentId': session.agentId});
+ await tester.pump();
+ }
+ expect(app.machineStates['m']!.processingAgentIds, hasLength(16));
+ } else {
+ await _event(app, 'dial_scroll', {'phase': 'down', 'dy': 0});
+ await tester.pump();
+ for (var i = 0; i < 16; i++) {
+ await _event(app, 'dial_scroll', {'dy': 3, 'velocity': 0});
+ await tester.pump();
+ }
+ await _event(app, 'dial_scroll', {'phase': 'up', 'dy': 0});
+ await tester.pump();
+ expect(
+ scrolls[sessions.first.terminal]!.offset,
+ lessThan(before[sessions.first.terminal]!),
+ );
+ }
+ debugOnRebuildDirtyWidget = previousObserver;
+ debugPrint(
+ 'WORKSPACE_EVENTS $activity: notifications=$notifications, '
+ 'terminalDispatches=${sessions.fold(0, (n, s) => n + s.frameCalls)}, '
+ 'workspaceBuilds=${rebuilds['PaneGrid'] ?? 0}',
+ );
+ for (final session in sessions.skip(1)) {
+ expect(scrolls[session.terminal]!.offset, before[session.terminal]);
+ }
+ expect(FocusManager.instance.primaryFocus, same(focus));
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
+ await tester.pump(const Duration(milliseconds: 5));
+ expect(inputs.first, hasLength(1));
+ expect(inputs.skip(1).expand((frames) => frames), isEmpty);
+ expect(notifications, 0);
+ expect(rebuilds['PaneGrid'] ?? 0, 0);
+ expect(sessions.every((session) => session.frameCalls == 0), isTrue);
+ } finally {
+ debugOnRebuildDirtyWidget = previousObserver;
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ }
+ });
+ }
+
+ testWidgets(
+ 'quiet heartbeats renew the watchdog and expiry still publishes',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ var notifications = 0;
+ app.addListener(() => notifications++);
+ await _event(app, 'turn_heartbeat', {'agentId': 'a0'});
+ expect(app.agentIsProcessing('m', 'a0'), isTrue);
+ expect(notifications, 1);
+ await tester.pump(const Duration(seconds: 8));
+ await _event(app, 'turn_heartbeat', {'agentId': 'a0'});
+ await tester.pump(const Duration(seconds: 8));
+ expect(app.agentIsProcessing('m', 'a0'), isTrue);
+ expect(notifications, 1);
+ await tester.pump(const Duration(seconds: 5));
+ expect(app.agentIsProcessing('m', 'a0'), isFalse);
+ expect(notifications, 2);
+ },
+ );
+
+ test(
+ 'device status still reaches its own observers without workspace churn',
+ () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ var workspaceChanges = 0;
+ var deviceChanges = 0;
+ app.addListener(() => workspaceChanges++);
+ app.dial.addListener(() => deviceChanges++);
+ await _event(app, 'dial_status', {'attached': true, 'fw': '1.2.3'});
+ expect(app.dial.status.attached, isTrue);
+ expect(app.dial.status.fw, '1.2.3');
+ await _event(app, 'dial_status', {'attached': false});
+ expect(app.dial.status.attached, isFalse);
+ expect(deviceChanges, 2);
+ expect(workspaceChanges, 0);
+ },
+ );
+}
diff --git a/docs/harness-v2-handoff.md b/docs/harness-v2-handoff.md
index 2e81b7dcf..a006c5507 100644
--- a/docs/harness-v2-handoff.md
+++ b/docs/harness-v2-handoff.md
@@ -1,5 +1,24 @@
# Harness v2: goal, plan, and continuation handoff
+**Workspace event isolation:** Routine heartbeats and dial scroll no longer
+rebuild the surrounding workspace or visit every retained terminal's JSON
+dispatcher. In the current 16-terminal/four-workspace fixture, 16 heartbeats went
+from 16 workspace builds and 256 irrelevant terminal calls to zero; a dial stroke
+went from 18 builds and 288 irrelevant calls to zero. Scroll and next-key routing
+stay with the focused pane. The busy indicator still publishes first activity,
+turn end and watchdog expiry; hidden ready replies and machine-wide transport
+failures remain covered. Device status continues through its own notifier.
+
+All **83 affected checks** pass in `/private/tmp/harness-workspace-events-final-checks.log`.
+The full desktop suite passes **1,431 checks**, with one optional media placeholder
+skipped, in `/private/tmp/harness-workspace-events-full.log`. Analysis has no errors
+or warnings and two existing brace-style infos in unchanged `app_state.dart`
+lines, recorded in `/private/tmp/harness-workspace-events-analyze.log`.
+[Performance evidence](harness-v2-performance.md) records deterministic work
+counts, not native latency. The prepared Release below predates this correction;
+its refresh is pending. The running preview remains unchanged while the console
+is locked, and native benchmarking remains deferred.
+
**Layout keyboard and rendering correction:** `d5756ab` is pushed. The current workspace keymap blocked
a second Layout chord once the dialog opened, and Cmd-number fell through as a
plain layout choice. Layout now owns its configured cycling command while other
diff --git a/docs/harness-v2-performance.md b/docs/harness-v2-performance.md
index c6fca69be..a795901f6 100644
--- a/docs/harness-v2-performance.md
+++ b/docs/harness-v2-performance.md
@@ -12,6 +12,34 @@ It prints `SWARM_BENCH` JSON records. Its filename deliberately does not end in
## Current continuation benchmark (2026-09-14)
+### Routine events leave the surrounding workspace idle
+
+The current New/Open UI was exercised with 16 retained terminals across four
+workspaces. A normal heartbeat from an already-busy agent rebuilt the workspace;
+dial scroll did the same. Both also visited every retained terminal's JSON
+dispatcher before reaching their destination. The dispatcher now sends only
+`terminal_` protocol events through that pool. Dial scroll goes directly to the
+focused viewport, device status updates its own listeners, and heartbeats renew
+the watchdog without publishing an unchanged busy state.
+
+| Isolated event sequence | Workspace builds, before → after | Irrelevant terminal dispatches, before → after |
+| --- | ---: | ---: |
+| 16 routine heartbeats, a frame after each | 16 → 0 | 256 → 0 |
+| Dial down, 16 moves, up, a frame after each | 18 → 0 | 288 → 0 |
+
+These are deterministic work counts from the headless widget runner, not elapsed
+time or native latency measurements. The same checks preserve the other panes'
+scroll positions, focus and next-key routing. First activity and watchdog expiry
+still notify; ready replies and transport failures reach hidden terminals on the
+correct machine. All **83 affected checks** pass in
+`/private/tmp/harness-workspace-events-final-checks.log`; the failing-before
+reproduction is `/private/tmp/harness-workspace-events-before.log`.
+Analysis has no errors or warnings and two existing brace-style infos in unchanged
+lines of `app_state.dart`, recorded in `/private/tmp/harness-workspace-events-analyze.log`.
+Native latency benchmarking remains deferred. The older timing measurements below
+describe their recorded UI revisions; the current entry contract is in
+[the handoff](harness-v2-handoff.md).
+
### Warm picker reopening
Add and Navigate no longer rebuild the unchanged Swarm screen when their