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
fix(web): no repeated agents load or console traces for an unlinked machine (#1709)
Jacob Pham0b5282b67111
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.mdindex 98014cae2..828b99524 100644--- a/desktop/CLAUDE.md+++ b/desktop/CLAUDE.md@@ -279,7 +279,13 @@ The native desktop target uses the CLI for cloud access and SSO tokens:Native link retries wait 5, 10, 20, then 30 seconds between probes, and never close an activeconnection or password-link handshake. Explicit Connect is immediate; repeated clicks join it.The initial unlinked refusal is measured once; later automatic probes are suppressed until the- machine is linked. This changes neither the browser's retry policy nor the daemon.+ machine is linked. A browser's link retry backs off the same way (it redialled every 5 s, each+ refusal reading the device list again). While a machine waits for a link, machine-list reads+ neither dial nor load it, and only a forced load asks it (a person's reload, a status change);+ connecting after a link loads its agents (`test/unlinked_machine_load_test.dart`).+ A released web build prints no `debugPrint` traces (`web/web_console.dart`): framework errors+ and uncaught errors still reach the console, and `?debug=traces` brings the traces back for that+ browser until `?debug=off`.A viewer build settles its own `NO_PEER_LINK`/`E2E_DENIED` first (`_settleTrust`): it joins thedevice log if it is not in it (`ViewerDeviceLog.ensureRegistered`), reads it and dials again,showing the machine as connecting; only a refusal that outlasts two rounds (~15s), or a frozendiff --git a/desktop/lib/desktop_workspace.dart b/desktop/lib/desktop_workspace.dartindex b24bc6964..57edbe9bc 100644--- a/desktop/lib/desktop_workspace.dart+++ b/desktop/lib/desktop_workspace.dart@@ -17,6 +17,9 @@ Widget authenticatedWorkspace(AppNotifier app) => CommunityForkHost(),);+/// A native build's console is stderr, read only by a developer: it keeps every line.+void prepareConsole() {}+/// A native build draws nothing around its screens.Widget appFrame(Widget app) => CommunityLinkHost(child: app);diff --git a/desktop/lib/main.dart b/desktop/lib/main.dartindex 18d2c8cec..3e92e6db6 100644--- a/desktop/lib/main.dart+++ b/desktop/lib/main.dart@@ -17,6 +17,7 @@ import 'desktop_workspace.dart'/// [startHarness] rather than depending on this package.Future<void> main() async {HarnessWidgetsBinding();+ prepareConsole();await startHarness(authenticatedScreen: authenticatedWorkspace,frame: appFrame,diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 3e99cdef5..293867367 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -9457,24 +9457,15 @@ class AppNotifier extends ChangeNotifier {}}+ /// Both builds back off the same way: a browser's retry used to redial every 5 s for good, each+ /// refusal reading the account's device list again — 12 dials and 12 reads a minute for one+ /// unlinked machine.void _startLinkRetry(String machineId) {if (_linkRetryTimers.containsKey(machineId)) return;- if (viewer == null) {- _scheduleNativeLinkRetry(machineId, offlineRetryInterval);- return;- }- _linkRetryTimers[machineId] = Timer.periodic(offlineRetryInterval, (_) {- final state = machineStates[machineId];- if (state == null || !state.needsLink) {- _stopLinkRetry(machineId);- return;- }- unawaited(_pool?.closeMachine(machineId));- _connectMachine(state);- });+ _scheduleLinkRetry(machineId, offlineRetryInterval);}- void _scheduleNativeLinkRetry(String machineId, Duration delay) {+ void _scheduleLinkRetry(String machineId, Duration delay) {final state = machineStates[machineId];if (state == null || !state.needsLink || _disposed) return;final revision = _authRevision;@@ -9503,7 +9494,7 @@ class AppNotifier extends ChangeNotifier {} finally {if (current()) {final next = delay * 2;- _scheduleNativeLinkRetry(+ _scheduleLinkRetry(machineId,next > const Duration(seconds: 30)? const Duration(seconds: 30)@@ -10793,11 +10784,21 @@ class AppNotifier extends ChangeNotifier {return;}for (final machine in machines) {- _connectMachine(machineStates[machine.machineId]!);- unawaited(_loadMachineData(machineStates[machine.machineId]!));+ final state = machineStates[machine.machineId]!;+ if (_awaitingLink(state)) continue;+ _connectMachine(state);+ unawaited(_loadMachineData(state));}}+ /// An unlinked machine whose link retry is waiting: the retry dials it, a device list that pins+ /// its key dials it at once ([_redialPinnedMachines]), and the connection that follows a link+ /// loads its agents. A machine-list read dialling it as well was refused every time — every 4 s+ /// while a browser's connect page shows.+ bool _awaitingLink(MachineState machine) =>+ machine.needsLink &&+ _linkRetryTimers.containsKey(machine.machine.machineId);+/// Viewer builds: a machine this app holds no key for may only be missing from its copy of the/// device log — a computer signed in after this app did — so the log is read first, briefly,/// rather than dialling a refusal. Machines with a key, and ones already asking for a password,@@ -10809,6 +10810,7 @@ class AppNotifier extends ChangeNotifier {final revision = _authRevision;final waiting = <MachineState>[];for (final state in states) {+ if (_awaitingLink(state)) continue;if (state.machine.isShared ||state.needsLink ||await _holdsMachineKey(state.machine.machineId)) {@@ -11664,6 +11666,10 @@ class AppNotifier extends ChangeNotifier {if (machine.machine.isShared) return;if (!_machineWorkCurrent(machine, _authRevision)) return;if (machine.agentLoadStatus == AgentLoadStatus.loaded && !force) return;+ // An unlinked machine refuses every load, and each refusal costs a dial, an error state and a+ // repaint: every machine-list read used to pay that again for nothing. Linking it connects it,+ // and the connection loads with force (`_onMachineConnected`); so does a person's reload.+ if (machine.needsLink && !force) return;if (machine.isLocalMachine &&!machine.usesLocalTransport &&_localLinkLive(machine) &&diff --git a/desktop/lib/web/web_console.dart b/desktop/lib/web/web_console.dartnew file mode 100644index 000000000..5afcb4b6e--- /dev/null+++ b/desktop/lib/web/web_console.dart@@ -0,0 +1,71 @@+import 'package:flutter/foundation.dart';++import '../core/browser_storage.dart';++/// The address switch that brings traces back for one browser: `?debug=traces` turns them on and+/// is remembered there, `?debug=off` forgets it.+const String kWebTracesParameter = 'debug';+const String _tracesPreference = 'debugTraces';++/// The browser console of a released web build carries errors, not traces.+///+/// Shared code traces with `debugPrint` (`agents_list start: …`, `zoo: read failed: …`, a sign-in+/// fallback it recovered from). On Desktop that is stderr, read only by a developer; in a browser+/// it is the console, kept in memory while DevTools is open. A released web build drops those+/// lines, failures included. What the framework reports (a build, layout or paint error) still+/// prints, and an error nothing caught still reaches the console through the browser.+///+/// Called once, before anything prints. Desktop never calls it.+void prepareWebConsole() => quietReleaseConsole(+ release: kReleaseMode,+ traces: webTracesWanted(+ Uri.base.queryParameters[kWebTracesParameter],+ read: () => readBrowserPreference(_tracesPreference),+ write: (value) => writeBrowserPreference(_tracesPreference, value),+ ),+);++/// Whether this browser asked for traces: [parameter] is the address's switch, read once at start,+/// and what it says is kept for the next visit.+@visibleForTesting+bool webTracesWanted(+ String? parameter, {+ required String? Function() read,+ required void Function(String value) write,+}) {+ try {+ switch (parameter) {+ case 'traces':+ write('on');+ return true;+ case 'off':+ write('');+ return false;+ }+ return read() == 'on';+ } catch (_) {+ // Storage a browser refuses (a private window) keeps only what the address says.+ return parameter == 'traces';+ }+}++/// Drops `debugPrint` lines in a [release] build unless [traces] is on, keeping the ones the+/// framework prints while it reports an error.+@visibleForTesting+void quietReleaseConsole({required bool release, required bool traces}) {+ if (!release || traces) return;+ final printLine = debugPrint;+ var reporting = false;+ debugPrint = (message, {wrapWidth}) {+ if (reporting) printLine(message, wrapWidth: wrapWidth);+ };+ final report = FlutterError.onError;+ FlutterError.onError = (details) {+ reporting = true;+ try {+ report?.call(details);+ } finally {+ reporting = false;+ }+ };+}diff --git a/desktop/lib/web/web_entry.dart b/desktop/lib/web/web_entry.dartindex 869360ab7..13f57214b 100644--- a/desktop/lib/web/web_entry.dart+++ b/desktop/lib/web/web_entry.dart@@ -9,6 +9,7 @@ import 'p2p/web_terminal_p2p.dart';import 'shell/web_focus_ring.dart';import 'shell/web_store_banner.dart';import 'shell/web_workspace.dart';+import 'web_console.dart';/// The signed-in screen of a browser build, chosen over/// `desktop_workspace.dart` by the conditional import in `main.dart`: the@@ -18,6 +19,9 @@ Widget authenticatedWorkspace(AppNotifier app) => P2pResumeRetry(child: HubReturn(child: WebWorkspace(app: app)),);+/// A released browser build's console carries errors, not traces (see [prepareWebConsole]).+void prepareConsole() => prepareWebConsole();+/// What a browser build draws around every screen: on a phone, the bar that/// sends it to the Harness app in its store. Above the Navigator, so every/// screen and route under it shows no key hints: the web is mouse-first.diff --git a/desktop/test/unlinked_machine_load_test.dart b/desktop/test/unlinked_machine_load_test.dartnew file mode 100644index 000000000..538cc214c--- /dev/null+++ b/desktop/test/unlinked_machine_load_test.dart@@ -0,0 +1,314 @@+// An unlinked machine (every dial refused NO_PEER_LINK) beside one this app reaches. Idle, it+// costs nothing but a backed-off link retry: no agents load, no console line. Linking it, or a+// person's reload, still loads its agents at once.+//+// Measured with these fakes on main before the fix (five idle minutes, browser): the link retry+// dialled 12 times and read the device list 12 times a minute; with the connect page up, whose+// watch re-reads the machine list every 4 s, the unlinked machine was also loaded 18 times a+// minute — 36 "agents_list start" / "failed: … NO_PEER_LINK" lines.+//+// On the VM: the model under test is the same in both builds, and its Desktop half needs dart:io.+@TestOn('vm')+library;++import 'dart:async';++import 'package:fake_async/fake_async.dart';+import 'package:flutter/foundation.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/api/api_client.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/viewer/device_log.dart';+import 'package:harness/viewer/device_log_sync.dart';+import 'package:harness/viewer/viewer_key_store.dart';+import 'package:harness/viewer/viewer_services.dart';+import 'package:harness/ws/local_cli_discovery.dart';+import 'package:harness/ws/ws_conn.dart';++import 'swarm_state_test.dart' show MemoryStore;++const _reachable = Machine(+ machineId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',+ authMode: MachineAuthMode.remote,+ name: 'Studio',+);+const _unlinked = Machine(+ machineId: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',+ authMode: MachineAuthMode.remote,+ name: 'Box',+);++class _Api extends ApiClient {+ _Api() : super(config: AppConfig.dev, session: AuthSession());++ int logReads = 0;++ @override+ Future<List<Machine>> machines() async => const [_reachable, _unlinked];++ @override+ Future<DeviceLogFetched?> deviceKeys(int since, {String? self}) async {+ logReads++;+ return (acct: 'acct', head: DevLogState.empty('acct').head, entries: []);+ }++ @override+ Future<DeviceLogAppendAnswer?> appendDeviceKey(DevLogEntry entry) async =>+ (head: null, error: null);++ @override+ Future<List<Object?>?> deviceAcks(int since) async => const [];++ @override+ Future<Map<String, int>> deviceKeysSeen() async => const {};+}++class _Discovery extends LocalCliDiscovery {+ _Discovery() : super(config: AppConfig.dev);+ @override+ Future<String?> computerId() async => null;+ @override+ Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>+ null;+}++/// A connection that answers: ready, with [agents] listed.+class _Live extends WsConn {+ _Live(String machineId, this.agents)+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: machineId,+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );++ final List<Map<String, dynamic>> agents;++ @override+ bool get isReady => true;++ @override+ Future<void> waitUntilReady({required Duration timeout}) async {}++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async => type == 'agents_list' ? {'agents': agents} : const {};++ @override+ Future<void> close() async {}+}++/// What a dial to a machine with no link does: refused at once, and closed for good.+class _Refused extends WsConn {+ _Refused()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: _unlinked.machineId,+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );++ @override+ bool get isClosed => true;++ @override+ Future<void> waitUntilReady({required Duration timeout}) =>+ Future.error(StateError('NO_PEER_LINK'));++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) => Future.error(Exception('NO_PEER_LINK'));++ @override+ Future<void> close() async {}+}++/// One app, a browser's or Desktop's, with both machines listed and the unlinked one refused.+class _Rig {+ _Rig(this.clock, {required bool browser}) {+ final keys = ViewerKeyStore(storage: MemoryStore());+ // The reachable machine is one this browser holds a key for.+ unawaited(keys.pin(_reachable.machineId, List.filled(32, 7)));+ clock.flushMicrotasks();+ app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(storage: MemoryStore()),+ configStore: null,+ localCliDiscovery: browser ? null : _Discovery(),+ viewer: browser+ ? ViewerServices(+ config: AppConfig.dev,+ session: AuthSession(storage: MemoryStore()),+ keys: keys,+ )+ : null,+ connectionForTest: _dial,+ );+ app.api = api;+ app.status = AppStatus.authenticated;+ app.adoptPoolConnectionForTest(_reachable.machineId, _studio);+ }++ final FakeAsync clock;+ late final AppNotifier app;+ final api = _Api();+ final _studio = _Live(_reachable.machineId, const []);+ int dials = 0;++ /// Once set, the unlinked machine answers its next dial.+ bool linked = false;++ WsConn _dial(String machineId) {+ if (machineId == _reachable.machineId) return _studio;+ if (linked) {+ return _Live(machineId, const [+ {'id': 'a1', 'name': 'Fix checkout flow tests'},+ ]);+ }+ dials++;+ scheduleMicrotask(() {+ app.localFailureForTest(machineId, 4404, 'NO_PEER_LINK');+ app.connectionStatusForTest(machineId, ConnectionStatus.disconnected);+ });+ return _Refused();+ }++ MachineState get box => app.stateOf(_unlinked.machineId)!;++ /// Started and settled: both listed, the reachable one connected, and the other refused for+ /// long enough that it waits for a link.+ void start() {+ unawaited(app.refreshMachines());+ clock.flushMicrotasks();+ app.onMachineConnectedForTest(_reachable.machineId);+ clock.elapse(const Duration(minutes: 1));+ expect(box.needsLink, isTrue);+ }++ void dispose() {+ app.dispose();+ clock.flushMicrotasks();+ }+}++void main() {+ late List<String> lines;+ final saved = debugPrint;+ setUp(() {+ lines = [];+ debugPrint = (message, {wrapWidth}) => lines.add(message ?? '');+ });+ tearDown(() => debugPrint = saved);++ int loads() => lines+ .where((line) => line == 'agents_list start: ${_unlinked.machineId}')+ .length;++ for (final browser in [true, false]) {+ final host = browser ? 'a browser' : 'Desktop';++ test('$host: four idle minutes load nothing and print nothing', () {+ fakeAsync((clock) {+ final rig = _Rig(clock, browser: browser)..start();+ // The connect page's watch, or any other machine-list reader.+ final watch = Timer.periodic(+ const Duration(seconds: 4),+ (_) => rig.app.rereadMachines(),+ );+ lines.clear();+ final dials = rig.dials;++ clock.elapse(const Duration(minutes: 4));++ expect(loads(), 0);+ expect(lines, isEmpty);+ // The link retry alone, 30 s apart by now.+ expect(rig.dials - dials, 8);+ watch.cancel();+ rig.dispose();+ });+ });++ test('$host: linking loads its agents without a reload', () {+ fakeAsync((clock) {+ final rig = _Rig(clock, browser: browser)..start();+ expect(rig.box.agents, isEmpty);++ rig.linked = true;+ clock.elapse(const Duration(seconds: 30));+ // What the pool reports once the retry's dial has gone through.+ rig.app.connectionStatusForTest(+ _unlinked.machineId,+ ConnectionStatus.connected,+ );+ clock.flushMicrotasks();++ expect(rig.box.needsLink, isFalse);+ expect(rig.box.agentLoadStatus, AgentLoadStatus.loaded);+ expect(rig.box.agents.map((a) => a.name), ['Fix checkout flow tests']);+ rig.dispose();+ });+ });++ test('$host: a person\'s reload still asks the machine', () {+ fakeAsync((clock) {+ final rig = _Rig(clock, browser: browser)..start();+ lines.clear();++ unawaited(rig.app.reloadMachineData(_unlinked.machineId));+ clock.flushMicrotasks();++ expect(loads(), 1);+ expect(rig.box.agentLoadStatus, AgentLoadStatus.needsLink);+ rig.dispose();+ });+ });+ }++ test('a browser\'s link retry backs off to 30 s, as Desktop\'s does', () {+ fakeAsync((clock) {+ final rig = _Rig(clock, browser: true);+ unawaited(rig.app.refreshMachines());+ clock.flushMicrotasks();+ rig.app.onMachineConnectedForTest(_reachable.machineId);+ // Past the two rounds that settle a refusal against the device list.+ clock.elapse(const Duration(seconds: 16));+ expect(rig.box.needsLink, isTrue);+ final reads = rig.api.logReads;++ final at = <int>[];+ var last = rig.dials;+ for (var second = 1; second <= 100; second++) {+ clock.elapse(const Duration(seconds: 1));+ if (rig.dials != last) {+ at.add(second);+ last = rig.dials;+ }+ }++ expect(at.first, lessThanOrEqualTo(5));+ expect(+ [for (var i = 1; i < at.length; i++) at[i] - at[i - 1]],+ [10, 20, 30, 30],+ );+ // Each refusal reads the device list once, so the reads back off with it.+ expect(rig.api.logReads - reads, 5);+ rig.dispose();+ });+ });+}diff --git a/desktop/test/web_console_test.dart b/desktop/test/web_console_test.dartnew file mode 100644index 000000000..4f394e68a--- /dev/null+++ b/desktop/test/web_console_test.dart@@ -0,0 +1,99 @@+// A released web build's console: traces dropped, framework errors kept, and one browser's+// switch that brings the traces back.+import 'package:flutter/foundation.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/web/web_console.dart';++/// Runs [body] with [quietReleaseConsole] installed over a recording console, and puts the+/// framework's handlers back before the test ends.+List<String> _console(+ void Function() body, {+ required bool release,+ required bool traces,+}) {+ final printed = <String>[];+ final savedPrint = debugPrint;+ final savedError = FlutterError.onError;+ debugPrint = (message, {wrapWidth}) => printed.add(message ?? '');+ // What the framework's own handler does: print the error.+ FlutterError.onError = (details) =>+ debugPrint('reported: ${details.exceptionAsString()}');+ try {+ quietReleaseConsole(release: release, traces: traces);+ body();+ } finally {+ debugPrint = savedPrint;+ FlutterError.onError = savedError;+ }+ return printed;+}++void _trace() => debugPrint('agents_list start: box');++void _frameworkError() => FlutterError.reportError(+ FlutterErrorDetails(+ exception: StateError('layout overflowed'),+ library: 'rendering library',+ ),+);++void main() {+ test('a release build drops trace lines', () {+ expect(_console(_trace, release: true, traces: false), isEmpty);+ });++ test('a release build still prints what the framework reports', () {+ final printed = _console(_frameworkError, release: true, traces: false);++ expect(printed, ['reported: Bad state: layout overflowed']);+ });++ test('a debug build prints everything as before', () {+ expect(_console(_trace, release: false, traces: false), [+ 'agents_list start: box',+ ]);+ });++ test('the switch brings traces back in a release build', () {+ expect(_console(_trace, release: true, traces: true), [+ 'agents_list start: box',+ ]);+ });++ group('the switch', () {+ late String? stored;+ bool wanted(String? parameter) => webTracesWanted(+ parameter,+ read: () => stored,+ write: (value) => stored = value,+ );+ setUp(() => stored = null);++ test('is off unless asked for', () {+ expect(wanted(null), isFalse);+ });++ test('?debug=traces turns it on and is remembered', () {+ expect(wanted('traces'), isTrue);+ expect(wanted(null), isTrue);+ });++ test('?debug=off forgets it', () {+ wanted('traces');++ expect(wanted('off'), isFalse);+ expect(wanted(null), isFalse);+ });++ test('a browser that refuses storage keeps what the address says', () {+ bool refused(String? parameter) => webTracesWanted(+ parameter,+ read: () => throw StateError('storage refused'),+ write: (_) => throw StateError('storage refused'),+ );++ expect(refused('traces'), isTrue);+ expect(refused(null), isFalse);+ });+ });+}