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.

Reduce idle USB scanning and redundant desktop invalidation (#506)

Dee3c5b3aa5fa87
diff --git a/cli/src/cable/cableFleet.spec.ts b/cli/src/cable/cableFleet.spec.ts
index f218c9f3f..a94c4c4e8 100644
--- a/cli/src/cable/cableFleet.spec.ts
+++ b/cli/src/cable/cableFleet.spec.ts
@@ -218,6 +218,29 @@ describe('USB dial fleet', () => {
})
describe('macOS USB inventory', () => {
+ it('reads multiple USB-rooted subtrees without leaking IDs into their siblings', () => {
+ const dump = `+-o Tim <class IOUSBHostDevice>
+ "idVendor" = 12346
+ "idProduct" = 4097
+ "USB Serial Number" = "AA:01"
+ +-o CDC
+ +-o serial
+ "IOCalloutDevice" = "/dev/tim"
++-o unrelated <class IOUSBHostDevice>
+ "idVendor" = 12346
+ "idProduct" = 12
+ +-o serial
+ "IOCalloutDevice" = "/dev/unrelated"
++-o Tux <class IOUSBHostDevice>
+ "USB Serial Number" = "BB:02"
+ "idProduct" = 4097
+ "idVendor" = 12346
+ +-o serial
+ "IOCalloutDevice" = "/dev/tux"`
+ expect(parseDarwinDialPorts(dump)).toEqual([device('/dev/tim', 'AA:01'), device('/dev/tux', 'BB:02')])
+ expect(parseDarwinDialPorts('')).toEqual([])
+ })
+
it('associates each tty with its own matching USB parent and serial in either property order', () => {
const dump = `+-o root
+-o Tim
diff --git a/cli/src/cable/serial.ts b/cli/src/cable/serial.ts
index 1527e3f93..e422b0817 100644
--- a/cli/src/cable/serial.ts
+++ b/cli/src/cable/serial.ts
@@ -61,7 +61,9 @@ function depthOf(line: string): number {
async function findDarwin(): Promise<DialPort[]> {
let dump: string
try {
- const { stdout } = await runFile('ioreg', ['-p', 'IOService', '-w0', '-l'], { maxBuffer: 64 * 1024 * 1024 })
+ // Keep each USB device's children (the tty lives below its vendor/product IDs), but do not
+ // serialize the whole IOService plane every two seconds just to detect a hot-plugged dial.
+ const { stdout } = await runFile('ioreg', ['-r', '-c', 'IOUSBHostDevice', '-w0', '-l'], { maxBuffer: 64 * 1024 * 1024 })
dump = stdout
} catch {
throw new Error('Could not enumerate USB dials')
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index b10264d10..e5ee9bcf5 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -1,7 +1,7 @@
/// Data models mirroring the backend/web types.
library;
-import 'package:flutter/foundation.dart' show immutable;
+import 'package:flutter/foundation.dart' show immutable, listEquals;
import 'runtime_model_name.dart';
import 'agent_git_context.dart';
@@ -771,6 +771,17 @@ class AgentPhase {
final AgentPhaseState state;
final String? artifact;
+ @override
+ bool operator ==(Object other) =>
+ other is AgentPhase &&
+ id == other.id &&
+ name == other.name &&
+ state == other.state &&
+ artifact == other.artifact;
+
+ @override
+ int get hashCode => Object.hash(id, name, state, artifact);
+
static AgentPhase? fromJson(Object? raw) {
if (raw is! Map) return null;
final name = AgentVerdict._safeText(raw['name'], 40);
@@ -876,11 +887,19 @@ class AgentVerdict {
other.errors == errors &&
other.warnings == warnings &&
other.artifact == artifact &&
+ listEquals(other.phases, phases) &&
other.updatedAt == updatedAt;
@override
- int get hashCode =>
- Object.hash(ready, summary, errors, warnings, artifact, updatedAt);
+ int get hashCode => Object.hash(
+ ready,
+ summary,
+ errors,
+ warnings,
+ artifact,
+ Object.hashAll(phases),
+ updatedAt,
+ );
}
/// What the daemon answered when asked where a typed task belongs (⌘B).
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index ee67ee287..cf1e4ba66 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -5454,6 +5454,7 @@ class AppNotifier extends ChangeNotifier {
final prev = byId[agent.id];
if (prev == null ||
prev.name != agent.name ||
+ prev.title != agent.title ||
prev.sessionId != agent.sessionId ||
prev.engine != agent.engine ||
prev.engineDisplayName != agent.engineDisplayName ||
@@ -5461,6 +5462,11 @@ class AppNotifier extends ChangeNotifier {
prev.codexHome != agent.codexHome ||
prev.modelName != agent.modelName ||
prev.modelEffort != agent.modelEffort ||
+ prev.gridModel != agent.gridModel ||
+ prev.gridWebSearch != agent.gridWebSearch ||
+ prev.gridBaseUrl != agent.gridBaseUrl ||
+ prev.gridState != agent.gridState ||
+ _gridNoteValue(prev.gridNote) != _gridNoteValue(agent.gridNote) ||
prev.parentAgentId != agent.parentAgentId ||
prev.project != agent.project ||
prev.gitContext != agent.gitContext ||
@@ -5480,13 +5486,29 @@ class AppNotifier extends ChangeNotifier {
prev.viewerUrl != agent.viewerUrl ||
prev.viewerError != agent.viewerError ||
prev.viewerName != agent.viewerName ||
- prev.verdict != agent.verdict) {
+ prev.verdict != agent.verdict ||
+ prev.forkedFrom?.agentId != agent.forkedFrom?.agentId ||
+ prev.forkedFrom?.name != agent.forkedFrom?.name ||
+ prev.forkable != agent.forkable ||
+ prev.resumeMode != agent.resumeMode ||
+ prev.permissionMode != agent.permissionMode ||
+ prev.bypassPermission != agent.bypassPermission ||
+ prev.namedAgent != agent.namedAgent) {
return false;
}
}
return true;
}
+ static (Type?, String?, String?) _gridNoteValue(GridNote? note) => (
+ note?.runtimeType,
+ note?.model,
+ switch (note) {
+ GridNoteOffline(:final machine) => machine,
+ _ => null,
+ },
+ );
+
/// Public retry hook used by the offline join guide's "Retry now" action.
Future<void> retryOfflineMachine(String machineId) =>
_pollOfflineMachine(machineId);
@@ -7259,10 +7281,22 @@ class AppNotifier extends ChangeNotifier {
}
}
- void _upsertAgent(MachineState machine, Agent agent) {
+ bool _upsertAgent(MachineState machine, Agent agent) {
final index = machine.agents.indexWhere((item) => item.id == agent.id);
final previous = index == -1 ? null : machine.agents[index];
agent = retainNewerGitContext(agent, previous);
+ // Discovery repeatedly sends the same snapshot. Preserve the existing
+ // object (pane presentation keys include it), and do not refetch previews
+ // or invalidate the workspace for a snapshot with no new information.
+ if (previous != null &&
+ agentsEqual([previous], [agent]) &&
+ machine.agentLoadStatus == AgentLoadStatus.loaded &&
+ machine.agentsLoadError == null &&
+ !machine.pendingProcessingSessions.contains(agent.sessionId)) {
+ // The layout can change independently of the agent snapshot: a newly
+ // opened terminal still needs its viewer, and an orphaned viewer must go.
+ return _syncViewerPane(machine, previous);
+ }
if (index == -1) {
machine.agents = [...machine.agents, agent];
} else {
@@ -7314,16 +7348,19 @@ class AppNotifier extends ChangeNotifier {
_lastErrorRetryable = false;
}
}
+ return true;
}
- void _renameAgent(MachineState machine, String agentId, String name) {
+ bool _renameAgent(MachineState machine, String agentId, String name) {
final index = machine.agents.indexWhere((agent) => agent.id == agentId);
- if (index == -1 || name.trim().isEmpty) return;
+ if (index == -1 || name.trim().isEmpty) return false;
final cleanName = name.trim();
+ if (machine.agents[index].name == cleanName) return false;
machine.agents = [...machine.agents]
..[index] = machine.agents[index].copyWith(name: cleanName);
_recordAgentName(machine, machine.agents[index]);
_syncAgentName(machine, machine.agents[index]);
+ return true;
}
// Creation can be in flight while a Stop reply removes the old final pane.
@@ -7430,7 +7467,7 @@ class AppNotifier extends ChangeNotifier {
/// changes, and takes the tile down when the viewer or the terminal goes.
/// It never steals focus: the person is typing in the terminal the viewer
/// belongs to. Nothing is persisted — see [PaneKind.web].
- void _syncViewerPane(MachineState machine, Agent agent) {
+ bool _syncViewerPane(MachineState machine, Agent agent) {
final machineId = machine.machine.machineId;
final url = agent.viewerUrl;
final viewerState = url ?? agent.viewerError;
@@ -7466,6 +7503,8 @@ class AppNotifier extends ChangeNotifier {
// The same page again is nothing new; a different one navigates in
// place rather than reopening a tile.
for (final pane in viewers) {
+ changed =
+ changed || pane.url != url || pane.viewerError != agent.viewerError;
pane.url = url;
pane.viewerError = agent.viewerError;
}
@@ -7501,6 +7540,7 @@ class AppNotifier extends ChangeNotifier {
changed = true;
}
if (changed) _persistLayout();
+ return changed;
}
/// Whether the active tab shows this agent's viewer beside its terminal.
@@ -13203,8 +13243,8 @@ class AppNotifier extends ChangeNotifier {
if (raw is Map) {
try {
final agent = Agent.fromJson(Map<String, dynamic>.from(raw));
+ var changed = _upsertAgent(machine, agent);
if (agent.terminalAvailable) {
- _upsertAgent(machine, agent);
// A pane created before this agent's terminal was verified is still sitting on
// "Attaching…" with no session — nothing else re-checks it once agentLoadStatus is
// already `loaded`, so this push is the only signal that it can attach now.
@@ -13217,13 +13257,13 @@ class AppNotifier extends ChangeNotifier {
// agent are still alive. Keep the pane/layout intent and let a
// later available sync reattach it. A confirmed `agent_deleted`
// event remains the sole path that removes a person's panes.
- _upsertAgent(machine, agent);
for (final pane in panesFor(machine.machine.machineId)) {
- if (pane.agentId != agent.id) continue;
+ if (pane.agentId != agent.id || pane.session == null) continue;
await _detachSession(pane, sendClose: false);
+ changed = true;
}
- notifyListeners();
}
+ if (!changed) return;
} catch (_) {
unawaited(_loadMachineData(machine, force: true));
}
@@ -13251,7 +13291,7 @@ class AppNotifier extends ChangeNotifier {
final agentId = _eventAgentId(machine, event, payload);
final name = payload['name'];
if (agentId != null && name is String) {
- _renameAgent(machine, agentId, name);
+ if (!_renameAgent(machine, agentId, name)) return;
} else {
unawaited(_loadMachineData(machine, force: true));
}
@@ -13451,6 +13491,10 @@ class AppNotifier extends ChangeNotifier {
}
}
break;
+ default:
+ // RPC replies and frames owned by other controllers carry no app
+ // state changes. They must not trigger a full workspace rebuild.
+ return;
}
notifyListeners();
}
diff --git a/desktop/test/agent_event_invalidation_test.dart b/desktop/test/agent_event_invalidation_test.dart
new file mode 100644
index 000000000..b27cb9c61
--- /dev/null
+++ b/desktop/test/agent_event_invalidation_test.dart
@@ -0,0 +1,181 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+
+import 'swarm_state_test.dart' show createApp;
+
+const _snapshot = <String, dynamic>{
+ 'id': 'a0',
+ 'name': 'Work',
+ 'engine': 'codex',
+ 'sessionId': 'conversation',
+ 'terminal': {'available': true},
+};
+
+Future<void> _sync(AppNotifier app, Map<String, dynamic> raw) =>
+ app.handleMachineEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {'agent': raw},
+ });
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ test('repeated discovery snapshots keep pane presentation stable', () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ await _sync(app, _snapshot);
+ final roster = app.stateOf('m')!.agents;
+ final agent = roster.first;
+ var rebuilds = 0;
+ app.addListener(() => rebuilds++);
+
+ for (var i = 0; i < 100; i++) {
+ await _sync(app, {..._snapshot});
+ }
+ await app.handleMachineEventForTest('m', {
+ 'type': 'agent_renamed',
+ 'agentId': 'a0',
+ 'payload': {'name': 'Work'},
+ });
+ expect(app.stateOf('m')!.agents, same(roster));
+ expect(app.stateOf('m')!.agents.first, same(agent));
+ expect(rebuilds, 0);
+
+ await _sync(app, {..._snapshot, 'title': 'Reviewing changes'});
+ expect(rebuilds, 1);
+ expect(app.stateOf('m')!.agents.first.title, 'Reviewing changes');
+ });
+
+ test(
+ 'RPC and device inventory frames do not invalidate the workspace',
+ () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ var rebuilds = 0;
+ app.addListener(() => rebuilds++);
+ for (final type in [
+ 'agent_recent',
+ 'devices_status',
+ 'future_extension',
+ ]) {
+ await app.handleMachineEventForTest('m', {
+ 'type': type,
+ 'payload': <String, dynamic>{},
+ });
+ }
+ expect(rebuilds, 0);
+ },
+ );
+
+ test('an unchanged snapshot still clears discovery errors and resolves a pending turn', () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ await _sync(app, _snapshot);
+ final machine = app.stateOf('m')!;
+ machine.agentsLoadError = 'Temporary failure';
+ machine.pendingProcessingSessions.add('conversation');
+ var rebuilds = 0;
+ app.addListener(() => rebuilds++);
+ await _sync(app, _snapshot);
+ expect(machine.agentsLoadError, isNull);
+ expect(machine.pendingProcessingSessions, isEmpty);
+ expect(machine.processingAgentIds, contains('a0'));
+ expect(rebuilds, greaterThan(0));
+ });
+
+ test(
+ 'a verdict phase can advance without changing its summary or timestamp',
+ () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ Map<String, dynamic> snapshot(String state) => {
+ ..._snapshot,
+ 'verdict': {
+ 'ready': false,
+ 'phases': [
+ {'id': 'review', 'name': 'Review', 'state': state},
+ ],
+ },
+ };
+ await _sync(app, snapshot('pending'));
+ var rebuilds = 0;
+ app.addListener(() => rebuilds++);
+ await _sync(app, snapshot('active'));
+ expect(rebuilds, 1);
+ expect(
+ app.stateOf('m')!.agents.first.verdict!.currentPhase!.state,
+ AgentPhaseState.active,
+ );
+ await _sync(app, snapshot('active'));
+ expect(rebuilds, 1);
+ },
+ );
+
+ // Every field below affects a visible label, action, model, or work phase.
+ // Suppressing duplicate pushes must never suppress a change to one of them.
+ final changes = <String, Map<String, dynamic>>{
+ 'title': {'title': 'New title'},
+ 'grid model': {
+ 'grid': {'model': 'Qwen3.5-4B'},
+ },
+ 'grid search': {
+ 'grid': {'webSearch': 'on'},
+ },
+ 'grid endpoint': {
+ 'grid': {'baseUrl': 'http://localhost:8080'},
+ },
+ 'grid state': {
+ 'grid': {'state': 'asleep'},
+ },
+ 'grid note': {
+ 'grid': {
+ 'note': {'reason': 'offline', 'model': 'Qwen3.5-4B', 'machine': 'M2'},
+ },
+ },
+ 'fork source': {
+ 'forkedFrom': {'agentId': 'source', 'name': 'Source'},
+ },
+ 'fork capability': {'forkable': false},
+ 'resume mode': {'resumeMode': 'conversation'},
+ 'permission': {'permissionMode': 'readOnly'},
+ 'bypass': {'bypassPermission': false},
+ 'named agent': {'namedAgent': 'reviewer'},
+ 'terminal': {
+ 'terminal': {'available': false},
+ },
+ 'verdict phase': {
+ 'verdict': {
+ 'ready': false,
+ 'phases': [
+ {'id': 'review', 'name': 'Review', 'state': 'active'},
+ ],
+ },
+ },
+ };
+ for (final change in changes.entries) {
+ test(
+ '${change.key} updates once, while identical parsed values stay quiet',
+ () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ await _sync(app, _snapshot);
+ var rebuilds = 0;
+ app.addListener(() => rebuilds++);
+ final changed = {..._snapshot, ...change.value};
+ await _sync(app, changed);
+ final agent = app.stateOf('m')!.agents.first;
+ expect(rebuilds, 1);
+ expect(
+ AppNotifier.agentsEqual([agent], [Agent.fromJson(changed)]),
+ isTrue,
+ );
+ await _sync(app, changed);
+ expect(app.stateOf('m')!.agents.first, same(agent));
+ expect(rebuilds, 1);
+ await _sync(app, _snapshot);
+ expect(rebuilds, 2, reason: 'removing a value must also reach the UI');
+ },
+ );
+ }
+}
diff --git a/desktop/test/web_pane_test.dart b/desktop/test/web_pane_test.dart
index dcd81a166..93f2fffa0 100644
--- a/desktop/test/web_pane_test.dart
+++ b/desktop/test/web_pane_test.dart
@@ -162,8 +162,11 @@ void main() {
);
// The same URL again is nothing new; a different one navigates in place.
+ var updates = 0;
+ app.addListener(() => updates++);
await _synced(app, 'a0', viewerUrl: 'http://127.0.0.1:4179/');
expect(_viewers(app).single.id, viewer.id);
+ expect(updates, 0, reason: 'an unchanged viewer must not repaint the workspace');
await _synced(app, 'a0', viewerUrl: 'http://127.0.0.1:4179/?file=a.step');
expect(_viewers(app).single.id, viewer.id);
expect(_viewers(app).single.url, 'http://127.0.0.1:4179/?file=a.step');
@@ -247,8 +250,11 @@ void main() {
expect(app.panes, isEmpty);
// Not a dismissal: the next open of the agent brings the viewer back.
app.adoptSessionForTest(terminal('a0', input));
+ var updates = 0;
+ app.addListener(() => updates++);
await _synced(app, 'a0', viewerUrl: 'http://127.0.0.1:4179/');
expect(_viewers(app), hasLength(1));
+ expect(updates, greaterThan(0), reason: 'restoring a viewer is a visible change');
});
test('the header control hides the viewer and brings it back', () async {