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
Keep Desktop connection recovery alive and shorten first arrival (#1337)
Dee6036c67df9fb
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.mdindex f680988b5..1eccef784 100644--- a/desktop/CLAUDE.md+++ b/desktop/CLAUDE.md@@ -237,6 +237,10 @@ The native desktop target uses the CLI for cloud access and SSO tokens:`LocalCliDiscovery`, which runs `harness start` when needed). The CLI terminates E2EE for relayedmachines; the app carries no crypto. Close code `4404`/`NO_PEER_LINK` means the machine needs`harness link import` — surfaced as `MachineState.needsLink` and polled via `_linkRetryTimers`.+ Native link retries wait 5, 10, 20, then 30 seconds between probes, and never close an active+ connection 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.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/measurement/product_connections.dart b/desktop/lib/measurement/product_connections.dartindex f68ed1bf4..5bc8dba1d 100644--- a/desktop/lib/measurement/product_connections.dart+++ b/desktop/lib/measurement/product_connections.dart@@ -56,6 +56,7 @@ class ProductConnections {required bool connecting,required bool connected,ProductHealthMeasure? failure,+ bool suppressStart = false,}) {_choiceChanged();if (!measurement.healthEnabled || !measurement.sharing) {@@ -64,6 +65,10 @@ class ProductConnections {}if (_manual.containsKey(key)) return;if (connecting) {+ // A known unlinked computer's background probes are the same blocked+ // episode. Preserve an already-open observation, but do not start one+ // for every probe. Explicit Connect has its separate manual observation.+ if (suppressStart) return;if (_pending.length >= 64 && !_pending.containsKey(key)) {measurement.health(ProductHealthMeasure.observationOverflow);return;diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex a77724639..2fccf8dd7 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -972,8 +972,10 @@ class AppNotifier extends ChangeNotifier {final Map<String, Timer> _slowReloadTimers = {};// Periodic retry for a machine the relay reported NO_PEER_LINK for — a `harness link connect` run// in a terminal (or another app instance) has no way to notify this one, so this is what makes the- // app pick up a fresh link within a few seconds instead of only on the next manual click/restart.+ // app pick up a fresh link instead of only on the next manual click/restart.+ // Native retries back off and never replace a connection still being established.final Map<String, Timer> _linkRetryTimers = {};+ final Map<String, Future<bool>> _trustedConnections = {};// Safety-net reconciliation for a connected machine's agent list, on top of the push events// (agent_synced/agent_created/agent_renamed/agent_deleted) that normally keep it live — catches the// rare case a push event was dropped. Runs silently: see _syncAgentsIfChanged.@@ -6926,6 +6928,10 @@ class AppNotifier extends ChangeNotifier {final settling =nextStatus == ConnectionStatus.disconnected &&_trustSettling.contains(machineId);+ final retryingLink =+ machine.needsLink &&+ (nextStatus == ConnectionStatus.connecting ||+ nextStatus == ConnectionStatus.reconnecting);productConnections.status(machineId,connecting:@@ -6933,21 +6939,18 @@ class AppNotifier extends ChangeNotifier {nextStatus == ConnectionStatus.connecting ||nextStatus == ConnectionStatus.reconnecting,connected: nextStatus == ConnectionStatus.connected,+ suppressStart: viewer == null && retryingLink,failure: machine.needsLink? ProductHealthMeasure.connectErrorUnlinked: machine.nodeOnline == false? ProductHealthMeasure.connectErrorOffline: null,);- // An unlinked machine is redialled every 5 s by the link retry and refused at once each time+ // An unlinked machine used to be redialled every 5 s and refused at once each time// (4404 NO_PEER_LINK): measured per dial, one such machine read as ~720 failed connects an hour,// and prod's first day showed 1,197 of 1,233 remote connects "failed", nearly all under a second.// The dial that found it unlinked is already open and still ends as one failure; the retry's// dials are not new attempts. A dial after linking (needsLink cleared first) is measured again.- final retryingLink =- machine.needsLink &&- (nextStatus == ConnectionStatus.connecting ||- nextStatus == ConnectionStatus.reconnecting);if (!retryingLink) {_measureConnection(machineId,@@ -7579,7 +7582,8 @@ class AppNotifier extends ChangeNotifier {_offlineRetryTimers.remove(machineId)?.cancel();}- /// Dials [machineId] now instead of at the link retry's next tick. A machine+ /// Dials [machineId] now instead of at the link retry's next tick. Native+ /// callers join an already-running Connect for the same machine. A machine/// that trusts this device through the account's device key log answers with/// no password at all. True once it is connected; false when it still wants/// this device linked (a CLI from before the log, or a log that does not name@@ -7587,16 +7591,42 @@ class AppNotifier extends ChangeNotifier {Future<bool> connectTrusted(String machineId, {Duration timeout = const Duration(seconds: 12),- }) async {+ }) {final state = machineStates[machineId];- if (state == null || state.machine.isShared) return false;+ if (_disposed || state == null || state.machine.isShared) {+ return Future.value(false);+ }+ // Native Connect may be reached from more than one surface. Join its dial+ // instead of closing the socket another click is already waiting on.+ if (viewer == null) {+ final pending = _trustedConnections[machineId];+ if (pending != null) return pending;+ }+ late final Future<bool> work;+ work = _connectTrusted(machineId, state, timeout).whenComplete(() {+ if (identical(_trustedConnections[machineId], work)) {+ _trustedConnections.remove(machineId);+ }+ });+ if (viewer == null) _trustedConnections[machineId] = work;+ return work;+ }++ Future<bool> _connectTrusted(+ String machineId,+ MachineState state,+ Duration timeout,+ ) async {+ final revision = _authRevision;+ bool current() =>+ _authWorkCurrent(revision) && identical(machineStates[machineId], state);final finishConnection = productConnections.manual(machineId);final done = Completer<bool>();var dialed = false;void settle() {final now = machineStates[machineId];if (done.isCompleted) return;- if (now == null) return done.complete(false);+ if (!current() || now == null) return done.complete(false);final status = now.connectionStatus;if (status == ConnectionStatus.connected && !now.needsLink) {return done.complete(true);@@ -7615,10 +7645,11 @@ class AppNotifier extends ChangeNotifier {});try {await _pool?.closeMachine(machineId);- if (machineStates[machineId] case final current?)- _connectMachine(current);+ if (!current()) return false;+ _connectMachine(state);settle();final connected = await done.future;+ if (!current()) return false;if (!connected) {productConnections.refused(machineId,@@ -7638,6 +7669,10 @@ class AppNotifier extends ChangeNotifier {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) {@@ -7649,6 +7684,49 @@ class AppNotifier extends ChangeNotifier {});}+ void _scheduleNativeLinkRetry(String machineId, Duration delay) {+ final state = machineStates[machineId];+ if (state == null || !state.needsLink || _disposed) return;+ final revision = _authRevision;+ late final Timer timer;+ bool current() =>+ _authWorkCurrent(revision) &&+ identical(_linkRetryTimers[machineId], timer) &&+ identical(machineStates[machineId], state) &&+ state.needsLink;+ bool busy() =>+ _trustedConnections.containsKey(machineId) ||+ pendingMachineLink(machineId) != null ||+ state.connectionStatus == ConnectionStatus.connecting ||+ state.connectionStatus == ConnectionStatus.reconnecting ||+ state.connectionStatus == ConnectionStatus.connected;+ timer = Timer(delay, () async {+ try {+ if (!current() || busy()) return;+ // Await removal before redialling; a slow handshake belongs to the+ // existing transport, which has its own timeout/reconnect policy.+ await _pool?.closeMachine(machineId);+ if (!current() || busy()) return;+ _connectMachine(state);+ } catch (_) {+ // A failed close cannot stop recovery; the next bounded retry owns it.+ } finally {+ if (current()) {+ final next = delay * 2;+ _scheduleNativeLinkRetry(+ machineId,+ next > const Duration(seconds: 30)+ ? const Duration(seconds: 30)+ : next,+ );+ } else if (identical(_linkRetryTimers[machineId], timer)) {+ _stopLinkRetry(machineId);+ }+ }+ });+ _linkRetryTimers[machineId] = timer;+ }+void _stopLinkRetry(String machineId) {_linkRetryTimers.remove(machineId)?.cancel();}@@ -7658,6 +7736,7 @@ class AppNotifier extends ChangeNotifier {timer.cancel();}_linkRetryTimers.clear();+ _trustedConnections.clear();}void _stopAllOfflineRetries() {diff --git a/desktop/lib/state/first_arrival.dart b/desktop/lib/state/first_arrival.dartindex 12a1d676d..34e2ac2ca 100644--- a/desktop/lib/state/first_arrival.dart+++ b/desktop/lib/state/first_arrival.dart@@ -204,8 +204,12 @@ class FirstArrival {if (machine == null) return stop('this computer never answered');if (!current()) return stop('the person took over');final machineId = machine.machine.machineId;- final sessions = await recentSessions(app, machineId, budget: indexWait);- await app.probeEngines(machineId);+ // The conversation index and installed engines are independent. A new+ // computer may still be indexing: do not put its engine probe behind it.+ final (sessions, _) = await (+ recentSessions(app, machineId, budget: indexWait),+ app.probeEngines(machineId),+ ).wait;final installed = {for (final engine in const ['claude', 'codex', 'opencode'])if (machine.engines[engine]?.installed == true) engine,diff --git a/desktop/test/connect_trusted_test.dart b/desktop/test/connect_trusted_test.dartindex 84e0e21d7..dcfc2e633 100644--- a/desktop/test/connect_trusted_test.dart+++ b/desktop/test/connect_trusted_test.dart@@ -44,6 +44,29 @@ void main() {expect(await answer, isTrue);});+ test('repeated Connect joins the active dial', () async {+ final first = app.connectTrusted('mac');+ final second = app.connectTrusted('mac');+ expect(second, same(first));+ socket(ConnectionStatus.connecting, needsLink: true);+ socket(ConnectionStatus.connected, needsLink: false);+ expect(await first, isTrue);+ expect(await second, isTrue);++ final next = app.connectTrusted('mac');+ expect(next, isNot(same(first)));+ expect(await next, isTrue);+ });++ test('a replacement machine cannot complete the old Connect', () async {+ final answer = app.connectTrusted('mac');+ socket(ConnectionStatus.connecting, needsLink: true);+ app.machineStates['mac'] = MachineState(mac.machine)+ ..connectionStatus = ConnectionStatus.connected;+ app.notifyListeners();+ expect(await answer, isFalse);+ });+test('one that refuses again still wants its password', () async {final answer = app.connectTrusted('mac');socket(ConnectionStatus.connecting, needsLink: true);diff --git a/desktop/test/first_arrival_test.dart b/desktop/test/first_arrival_test.dartindex 1d306d09c..6434d2432 100644--- a/desktop/test/first_arrival_test.dart+++ b/desktop/test/first_arrival_test.dart@@ -1,7 +1,10 @@+import 'dart:async';+import 'package:flutter_test/flutter_test.dart';import 'package:harness/auth/auth_session.dart';import 'package:harness/core/config.dart';import 'package:harness/core/local_key_value_store.dart';+import 'package:harness/core/models.dart';import 'package:harness/state/app_state.dart';import 'package:harness/state/first_arrival.dart';import 'package:harness/state/session_content_search.dart';@@ -17,6 +20,36 @@ class _MemoryStore implements LocalKeyValueStore {Future<void> delete(String key) async => values.remove(key);}+class _PreparingApp extends AppNotifier {+ _PreparingApp()+ : super(config: AppConfig.dev, authSession: AuthSession(), configStore: null);++ final engineCheck = Completer<void>();+ bool probing = false;+ final local = MachineState(const Machine(machineId: 'local', name: 'Mac', authMode: MachineAuthMode.self));+ @override+ MachineState get localMachineState => local;+ @override+ Iterable<String> get searchableMachineIds => ['local'];+ @override+ Future<void> probeEngines(String machineId, {bool force = false}) {+ probing = true;+ return engineCheck.future;+ }+}++class _PreparingArrival extends FirstArrival {+ _PreparingArrival(super.storage);+ final index = Completer<List<ArrivalSession>>();+ bool searching = false;+ @override+ Future<List<ArrivalSession>> recentSessions(AppNotifier app, String machineId,+ {required Duration budget}) {+ searching = true;+ return index.future;+ }+}+final _base = DateTime(2026, 10, 8, 12);/// A conversation last active [minutesAgo] minutes before noon.@@ -301,6 +334,25 @@ void main() {});group('FirstArrival', () {+ test('the index and engine check start together and both finish before planning', () async {+ final app = _PreparingApp();+ addTearDown(app.dispose);+ final arrival = _PreparingArrival(_MemoryStore())..begin(downloads: false);+ await arrival.restore();+ final opening = arrival.run(app);+ await Future<void>.delayed(Duration.zero);+ expect(arrival.searching, isTrue);+ expect(app.probing, isTrue, reason: 'a slow index must not delay the engine check');+ var finished = false;+ opening.then((_) => finished = true);+ arrival.index.complete([]);+ await Future<void>.delayed(Duration.zero);+ expect(finished, isFalse, reason: 'do not infer no installed engines while the probe is pending');+ app.engineCheck.complete();+ expect(await opening, isFalse); // No installed engines or conversations.+ expect(arrival.pending, isFalse);+ });+// Production order: setup's begin runs before the signed-in restore.test('runs only on a computer setup has just reached, and only once',diff --git a/desktop/test/link_retry_test.dart b/desktop/test/link_retry_test.dartnew file mode 100644index 000000000..c8122770a--- /dev/null+++ b/desktop/test/link_retry_test.dart@@ -0,0 +1,199 @@+import 'dart:async';++import 'package:fake_async/fake_async.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/auth/cli_link.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/ws/ws_conn.dart';++class _Socket extends WsConn {+ _Socket()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'remote',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ int closes = 0;+ Completer<void>? closing;+ @override+ Future<void> close() async {+ closes++;+ await closing?.future;+ }+}++class _Link extends CliLink {+ final result = Completer<CliLinkConnectResult>();+ @override+ Future<CliLinkConnectResult> connect(+ String machineId,+ String password, {+ void Function(String stage)? onProgress,+ String? displayName,+ }) => result.future;+}++void main() {+ const machine = Machine(+ machineId: 'remote',+ name: 'Box',+ authMode: MachineAuthMode.remote,+ );+ late AppNotifier app;+ late _Socket socket;+ late MachineState state;+ late _Link link;+ var dials = 0;+ void setup() {+ dials = 0;+ socket = _Socket();+ link = _Link();+ app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ cliLink: link,+ connectionForTest: (_) {+ dials++;+ app.adoptPoolConnectionForTest('remote', socket);+ return socket;+ },+ );+ state = app.machineStates['remote'] = MachineState(machine)+ ..nodeOnline = true;+ app.machines.add(machine);+ app.adoptPoolConnectionForTest('remote', socket);+ app.localFailureForTest('remote', 4404, 'NO_PEER_LINK');+ }++ test(+ 'native refused retries back off to 30 seconds and stop after linking',+ () {+ fakeAsync((clock) {+ setup();+ for (final seconds in [5, 10, 20, 30, 30]) {+ final before = dials;+ clock.elapse(Duration(seconds: seconds - 1));+ expect(dials, before);+ clock.elapse(const Duration(seconds: 1));+ expect(dials, before + 1);+ }+ expect(socket.closes, 5);+ state.needsLink = false;+ clock.elapse(const Duration(minutes: 1));+ expect(dials, 5);+ app.dispose();+ clock.flushMicrotasks();+ });+ },+ );++ for (final status in [+ ConnectionStatus.connecting,+ ConnectionStatus.reconnecting,+ ]) {+ test('a $status handshake is never closed by the link retry', () {+ fakeAsync((clock) {+ setup();+ state.connectionStatus = status;+ clock.elapse(const Duration(seconds: 35));+ expect(dials, 0);+ expect(socket.closes, 0);+ state.connectionStatus = ConnectionStatus.disconnected;+ clock.elapse(const Duration(seconds: 30));+ expect(dials, 1);+ app.dispose();+ clock.flushMicrotasks();+ });+ });+ }++ test('manual Connect bypasses backoff and is not replaced by a retry', () {+ fakeAsync((clock) {+ setup();+ final manual = app.connectTrusted(+ 'remote',+ timeout: const Duration(seconds: 40),+ );+ final joined = app.connectTrusted('remote');+ expect(joined, same(manual));+ clock.flushMicrotasks();+ expect(dials, 1);+ expect(socket.closes, 1);+ clock.elapse(const Duration(seconds: 35));+ expect(dials, 1);+ expect(socket.closes, 1);+ state+ ..needsLink = false+ ..connectionStatus = ConnectionStatus.connected;+ bool? result;+ manual.then((value) => result = value);+ app.notifyListeners();+ clock.flushMicrotasks();+ expect(result, isTrue);+ app.dispose();+ clock.flushMicrotasks();+ });+ });++ test('a slow socket close is joined and cannot redial a removed machine', () {+ fakeAsync((clock) {+ setup();+ socket.closing = Completer<void>();+ clock.elapse(const Duration(seconds: 35));+ expect(socket.closes, 1);+ expect(dials, 0);+ app.machineStates.remove('remote');+ socket.closing!.complete();+ clock.flushMicrotasks();+ clock.elapse(const Duration(minutes: 1));+ expect(dials, 0);+ app.dispose();+ clock.flushMicrotasks();+ });+ });++ test('password linking owns its handshake until it finishes', () {+ fakeAsync((clock) {+ setup();+ final linking = app.connectWithPassword(+ 'remote',+ 'synthetic fixture password',+ );+ clock.elapse(const Duration(seconds: 35));+ expect(socket.closes, 0);+ expect(dials, 0);+ String? error;+ linking.then((value) => error = value);+ link.result.complete(+ const CliLinkConnectResult(error: 'Fixture refusal'),+ );+ clock.flushMicrotasks();+ expect(error, 'Fixture refusal');+ clock.elapse(const Duration(seconds: 30));+ expect(dials, 1);+ app.dispose();+ clock.flushMicrotasks();+ });+ });++ test('dispose stops retries and fences a pending close', () {+ fakeAsync((clock) {+ setup();+ socket.closing = Completer<void>();+ clock.elapse(const Duration(seconds: 5));+ app.dispose();+ socket.closing!.complete();+ clock.flushMicrotasks();+ clock.elapse(const Duration(minutes: 1));+ expect(dials, 0);+ });+ });+}diff --git a/desktop/test/link_retry_transport_test.dart b/desktop/test/link_retry_transport_test.dartnew file mode 100644index 000000000..199551190--- /dev/null+++ b/desktop/test/link_retry_transport_test.dart@@ -0,0 +1,145 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:flutter_test/flutter_test.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/ws/ws_conn.dart';++void main() {+ test(+ 'a real native link handshake survives the old five-second retry tick',+ () async {+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ final clients = <WebSocket>[];+ final selections = <String>[];+ final refused = Completer<void>();+ final handshake = Completer<void>();+ final timers = <Timer>[];+ var stopped = false;+ server.listen((request) async {+ final ws = await WebSocketTransformer.upgrade(request);+ clients.add(ws);+ var refusedSocket = false;+ ws.listen((data) {+ if (stopped || refusedSocket) return;+ final frame = jsonDecode(data as String) as Map<String, dynamic>;+ final payload = frame['payload'] as Map? ?? {};+ if (frame['type'] == 'machine_select') {+ selections.add(payload['machineId'] as String);+ if (selections.length == 1) {+ refusedSocket = true;+ unawaited(ws.close(4404, 'NO_PEER_LINK'));+ } else {+ if (!handshake.isCompleted) handshake.complete();+ // The old retry closed this socket at five seconds, before the+ // remote computer could finish establishing its trusted link.+ timers.add(+ Timer(const Duration(seconds: 6), () {+ if (!stopped && ws.readyState == WebSocket.open) {+ ws.add(+ jsonEncode({+ 'type': 'connected',+ 'payload': {'machineId': 'remote'},+ }),+ );+ }+ }),+ );+ }+ } else if (payload['requestId'] != null &&+ ws.readyState == WebSocket.open) {+ ws.add(+ jsonEncode({+ 'type': '${frame['type']}_result',+ 'payload': {+ 'requestId': payload['requestId'],+ 'agents': [],+ 'engines': [],+ },+ }),+ );+ }+ });+ });++ late AppNotifier app;+ WsConn? current;+ WsConn connect(String machineId) {+ if (current case final existing? when !existing.isClosed)+ return existing;+ late final WsConn conn;+ conn = WsConn(+ wsBaseUrl: 'ws://127.0.0.1:${server.port}',+ autonomousEnv: 'test',+ machineId: machineId,+ accessTokenProvider: (_, _) async => '',+ transportKind: WsTransportKind.localPlaintext,+ localWsUri: Uri.parse('ws://127.0.0.1:${server.port}'),+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onLocalFailure: (code, reason) =>+ app.localFailureForTest(machineId, code, reason),+ onStatus: (status) {+ if (!identical(current, conn)) return;+ app.connectionStatusForTest(machineId, status);+ if (status == ConnectionStatus.disconnected &&+ app.stateOf(machineId)?.needsLink == true &&+ !refused.isCompleted) {+ refused.complete();+ }+ },+ );+ current = conn;+ app.adoptPoolConnectionForTest(machineId, conn);+ unawaited(conn.connect());+ return conn;+ }++ app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ connectionForTest: connect,+ );+ const machine = Machine(+ machineId: 'remote',+ name: 'Synthetic box',+ authMode: MachineAuthMode.remote,+ );+ app.machines.add(machine);+ app.machineStates['remote'] = MachineState(machine)..nodeOnline = true;+ addTearDown(() async {+ stopped = true;+ for (final timer in timers) {+ timer.cancel();+ }+ final last = current;+ current = null;+ app.dispose();+ await last?.close();+ for (final client in clients) {+ await client.close();+ }+ await server.close(force: true);+ });+ connect('remote');+ await refused.future.timeout(const Duration(seconds: 3));+ final recovery = app.connectTrusted('remote');+ await handshake.future.timeout(const Duration(seconds: 3));+ expect(await recovery, isTrue);+ expect(selections, [+ 'remote',+ 'remote',+ ], reason: 'no background retry replaces the active handshake');+ expect(app.stateOf('remote')!.needsLink, isFalse);+ expect(+ app.stateOf('remote')!.connectionStatus,+ ConnectionStatus.connected,+ );+ },+ );+}diff --git a/desktop/test/product_health_test.dart b/desktop/test/product_health_test.dartindex 5cbdf1159..0b2a0b689 100644--- a/desktop/test/product_health_test.dart+++ b/desktop/test/product_health_test.dart@@ -122,6 +122,36 @@ void main() {expect(reports.first['context'], usage.context!.toJson());});+ test('known unlinked probes preserve the first outcome without counting each retry', () async {+ await usage.flush();+ final connections = ProductConnections(usage);+ addTearDown(connections.dispose);+ connections.status('PRIVATE_MACHINE', connecting: true, connected: false);+ connections.refused('PRIVATE_MACHINE', ProductHealthMeasure.connectErrorUnlinked);+ connections.status('PRIVATE_MACHINE', connecting: true, connected: false, suppressStart: true);+ connections.status('PRIVATE_MACHINE', connecting: false, connected: false);+ for (var retry = 0; retry < 10; retry++) {+ connections.status('PRIVATE_MACHINE', connecting: true, connected: false, suppressStart: true);+ connections.refused('PRIVATE_MACHINE', ProductHealthMeasure.connectErrorUnlinked);+ connections.status('PRIVATE_MACHINE', connecting: false, connected: false,+ failure: ProductHealthMeasure.connectErrorUnlinked);+ }+ final manual = connections.manual('PRIVATE_MACHINE');+ connections.status('PRIVATE_MACHINE', connecting: true, connected: false, suppressStart: true);+ connections.status('PRIVATE_MACHINE', connecting: false, connected: true);+ manual(ProductOutcome.ok);+ // A later ordinary connection remains measurable.+ connections.status('PRIVATE_MACHINE', connecting: true, connected: false);+ connections.status('PRIVATE_MACHINE', connecting: false, connected: true);+ await usage.flush();+ expect(totals()['ui_desktop_connect_auto_started'], 2);+ expect(totals()['ui_desktop_connect_auto_failed'], 1);+ expect(totals()['health_desktop_connect_error_unlinked'], 1);+ expect(totals()['ui_desktop_connect_auto_ok'], 1);+ expect(totals()['ui_desktop_connect_user_ok'], 1);+ expect(jsonEncode(reports), isNot(contains('PRIVATE')));+ });+test('opt-out and account changes fence delayed callbacks, counters, and retries', () async {await usage.flush();final old = usage.begin(ProductFlow.viewerLoad);diff --git a/desktop/test/remote_connect_measurement_test.dart b/desktop/test/remote_connect_measurement_test.dartindex 271814946..9f9bbffe9 100644--- a/desktop/test/remote_connect_measurement_test.dart+++ b/desktop/test/remote_connect_measurement_test.dart@@ -11,6 +11,14 @@ class _Recorder extends ProductMeasurement {_Recorder() : super(surface: 'desktop', automatic: false, sendSetup: (_) async => {});final ended = <String>[];+ final healthCounts = <ProductHealthMeasure>[];++ @override+ bool get healthEnabled => true;+ @override+ bool get sharing => true;+ @override+ void health(ProductHealthMeasure measure) => healthCounts.add(measure);@overridevoid Function(ProductOutcome) begin(ProductFlow flow) =>@@ -68,6 +76,7 @@ void main() {app..status = AppStatus.authenticated..currentUser = const CurrentUserProfile(id: 'u1', email: '[email protected]');+ app.notifyListeners();});tearDown(() => app.dispose());@@ -77,7 +86,7 @@ void main() {// WsConn reports the refusal before the close (WsConn._onDone).app.localFailureForTest(mid, 4404, 'NO_PEER_LINK');app.connectionStatusForTest(mid, ConnectionStatus.disconnected);- expect(usage.ended, ['remoteConnect:failed']);+ expect(usage.ended, ['connectAuto:failed', 'remoteConnect:failed']);// Three link-retry ticks: closeMachine, then a dial refused again.for (var tick = 0; tick < 3; tick++) {@@ -86,13 +95,14 @@ void main() {app.localFailureForTest(mid, 4404, 'NO_PEER_LINK');app.connectionStatusForTest(mid, ConnectionStatus.disconnected);}- expect(usage.ended, ['remoteConnect:failed']);+ expect(usage.ended, ['connectAuto:failed', 'remoteConnect:failed']);+ expect(usage.healthCounts.where((m) => m == ProductHealthMeasure.connectErrorUnlinked), hasLength(1));// Linked: the next dial is measured again, and succeeds.app.stateOf(mid)!.needsLink = false;app.connectionStatusForTest(mid, ConnectionStatus.connecting);app.connectionStatusForTest(mid, ConnectionStatus.connected);- expect(usage.ended, ['remoteConnect:failed', 'remoteConnect:ok']);+ expect(usage.ended, ['connectAuto:failed', 'remoteConnect:failed', 'connectAuto:ok', 'remoteConnect:ok']);});test('an ordinary offline machine still counts each dial that ends', () {@@ -102,6 +112,7 @@ void main() {app.connectionStatusForTest(mid, ConnectionStatus.disconnected);app.connectionStatusForTest(mid, ConnectionStatus.connecting);app.connectionStatusForTest(mid, ConnectionStatus.connected);- expect(usage.ended, ['remoteConnect:failed', 'remoteConnect:ok']);+ expect(usage.ended.where((event) => event.startsWith('remoteConnect:')),+ ['remoteConnect:failed', 'remoteConnect:ok']);});}diff --git a/docs/product-measurement.md b/docs/product-measurement.mdindex e6e8a8b52..313dd6317 100644--- a/docs/product-measurement.md+++ b/docs/product-measurement.md@@ -61,6 +61,11 @@ Weekly bins cover completed weeks from installations that report again, so non-rNative Desktop observes main-frame/first-frame viewer loading, updater apply acknowledgements andthe next observed version, explicit versus automatic connections, and resume-to-observed-work.+Known-unlinked native Desktop retry probes do not start additional automatic connection+observations: the initial refusal remains one outcome, and an explicit Connect is measured+separately. Older releases counted every probe in the health totals. A drop across this+measurement change is not evidence that fewer people encountered linking trouble; these+counters do not count affected people. Retry suppression adds no identifiers or stored history.The startup bucket measures launch to the first consented observation of a connected workspace,including preference/sign-in delay. One in 60 rendered frames supplies a coarse duration bucket;it cannot reliably detect an idle freeze. Error hooks pass only framework/async categories.