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(mobile): back off parked machine rechecks, pause them in background
tony2f244736a14a
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 6ca3a7b9c..d82b2e131 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -10467,6 +10467,12 @@ class AppNotifier extends ChangeNotifier {_pausedAt ??= DateTime.now();_desk.pause();_stopDeafPoll();+ // A socket waiting on a machine that is off stops dialling it while nobody is looking;+ // [handleAppResumed]'s reconnectAll asks again the moment the phone is back+ // ([WsConn.pauseParkedRecheck]).+ for (final machine in machines) {+ _heldConnection(machine.machineId)?.pauseParkedRecheck();+ }// The agents this run learned between lists, for the next launch — see [_keepMachineCache]._keepMachineCache();}diff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dartindex 29e133464..1e1b43b40 100644--- a/mobile/lib/ws/ws_conn.dart+++ b/mobile/lib/ws/ws_conn.dart@@ -135,9 +135,31 @@ class WsConn {bool _parked = false;bool get isParked => _parked;- /// How long a parked connection waits before it dials again of its own accord, with nothing having- /// said the machine is back — the fallback under [wake], not the way back.+ /// How long a parked connection first waits before it dials again of its own accord, with nothing+ /// having said the machine is back — the fallback under [wake], not the way back.+ ///+ /// ⚠️ **Each such recheck waits twice as long as the one before, up to [_parkedRecheckCeiling]+ /// (2026-10-20).** At a flat minute, an app left open beside a machine that is switched off+ /// dialled it sixty times an hour for as long as it stayed open — a simulator left running did+ /// exactly that through 2026-10-19/20, while the relay counted 15,104 phone sockets against 344+ /// the day before and the people using the phone stayed level. Each dial is a token, a key mint+ /// on this thread and a TLS handshake here, and an auth, a lookup and a write at the relay.+ /// Nothing is slower to come back for it: the relay's push, `/api/machines`, a tap and the app's+ /// return all [wake] it at once and start the waits over.static const _parkedRecheck = Duration(seconds: 60);+ static const _parkedRecheckCeiling = Duration(minutes: 15);++ /// The rechecks this connection has dialled in a row on its own ([wake] with `recheck`), each+ /// one parked again: what [parkedRecheckAfter] doubles the next wait by.+ int _parkedRechecks = 0;++ /// The wait before a parked connection's next recheck after [rechecks] of them in a row:+ /// a minute, then 2, 4, 8, and 15 at most.+ @visibleForTesting+ static Duration parkedRecheckAfter(int rechecks) {+ final wait = _parkedRecheck * (1 << min(max(rechecks, 0), 4));+ return wait > _parkedRecheckCeiling ? _parkedRecheckCeiling : wait;+ }/// This socket's `e2e_hello` went out right behind its `machine_select`, so the select's ack must/// not send another — see [connect]. Reset on every dial.@@ -633,7 +655,7 @@ class WsConn {/// status changes down every socket (`machines_status`), so the app hears this machine come back/// through it — or through any other machine's socket, or `/api/machines` — and calls [wake]. A/// welcome that arrives anyway (the relay was wrong) still makes it ready ([_markReady]). With- /// nothing heard at all, it dials again after [_parkedRecheck].+ /// nothing heard at all, it dials again after [parkedRecheckAfter] — longer each time.////// Only a connection that never became ready: a live session's machine going away is the/// `node_status` the app already handles, on a socket that is still up.@@ -643,19 +665,36 @@ class WsConn {_selectWatchdog?.cancel();_selectWatchdog = null;_reconnectTimer?.cancel();- _reconnectTimer = Timer(_parkedRecheck, () => wake('recheck'));+ final wait = parkedRecheckAfter(_parkedRechecks);+ _reconnectTimer = Timer(wait, () => wake(_recheck));appLog.info('ws','parked $machineId · the relay says it is offline; '- 'waiting for it (recheck ${_parkedRecheck.inSeconds}s)',+ 'waiting for it (recheck ${wait.inSeconds}s)',);}+ /// [wake]'s reason when nothing said the machine is back: the parked connection's own timer.+ static const _recheck = 'recheck';++ /// The app has gone to the background: a parked connection stops dialling again on its own. A+ /// phone that runs no code would not have dialled anyway, but one that still does (Android for a+ /// while, a simulator) was dialling for nobody. Nothing else changes: it stays parked, a push still+ /// [wake]s it, and coming back to the front asks again at once ([reconnectNow]).+ void pauseParkedRecheck() {+ if (!_parked) return;+ _reconnectTimer?.cancel();+ _reconnectTimer = null;+ }+/// Dial a parked connection now — its machine was reported back ([reason] goes to the log)./// Nothing for a connection that is not parked.void wake(String reason) {if (!_parked) return;_parked = false;+ // Its own recheck makes the next wait longer; anything else — the machine reported back,+ // somebody asking for it — starts the waits over.+ _parkedRechecks = reason == _recheck ? _parkedRechecks + 1 : 0;_reconnectTimer?.cancel();_reconnectTimer = null;if (_closing || _ready) return;@@ -680,6 +719,7 @@ class WsConn {_reconnectTimer?.cancel();_reconnectTimer = null;}+ _parkedRechecks = 0;_ready = true;_attempt = 0;onStatus(ConnectionStatus.connected);@@ -1268,6 +1308,7 @@ class WsConn {_closing = true;_ready = false;_parked = false;+ _parkedRechecks = 0;_codec = null;_disposePlugin();_reconnectTimer?.cancel();diff --git a/mobile/test/state/stale_socket_redial_test.dart b/mobile/test/state/stale_socket_redial_test.dartindex 3f92f2475..8e6cee8d9 100644--- a/mobile/test/state/stale_socket_redial_test.dart+++ b/mobile/test/state/stale_socket_redial_test.dart@@ -12,10 +12,14 @@ class _HeldConn extends EdgeConn {bool redials = true;DateTime? heard;int redialled = 0;+ int parkedRechecksPaused = 0;@overridebool get isReady => ready;+ @override+ void pauseParkedRecheck() => parkedRechecksPaused++;+@overridebool get canForceReconnect => redials;@@ -199,6 +203,16 @@ void main() {expect(session.status, TerminalSessionStatus.takenOver);expect(app.stateOf('m')!.pendingOfflineAgentId, isNull);});++ test('going to the background stops a socket waiting on a machine that is '+ 'off from dialling it on its own', () {+ app.handleAppPaused();+ expect(conn.parkedRechecksPaused, 1);+ // The OS repeating itself pauses again: harmless, nothing is dialled.+ app.handleAppPaused();+ expect(conn.parkedRechecksPaused, 2);+ expect(conn.redialled, 0);+ });});group('a terminal stream and its socket gone quiet', () {diff --git a/mobile/test/ws/ws_conn_park_test.dart b/mobile/test/ws/ws_conn_park_test.dartnew file mode 100644index 000000000..1d73f65ba--- /dev/null+++ b/mobile/test/ws/ws_conn_park_test.dart@@ -0,0 +1,201 @@+import 'dart:async';+import 'dart:convert';++import 'package:fake_async/fake_async.dart';+import 'package:flutter_test/flutter_test.dart';++import 'package:harness_mobile/ws/ws_conn.dart';++import 'memory_web_socket.dart';++/// A connection whose machine the relay calls offline waits for it ([WsConn.parkUntilOnline]) and+/// dials again on its own only now and then: after a minute, then twice as long each time, to+/// fifteen minutes. Anything that says the machine is back, and anybody asking for it, dials at+/// once and starts the waits over. At a flat minute, an app left open beside a machine that was+/// off dialled it sixty times an hour, for as long as it stayed open.+void main() {+ test('the waits double from a minute to fifteen at most', () {+ expect(+ [for (var n = 0; n < 7; n++) WsConn.parkedRecheckAfter(n).inSeconds],+ [60, 120, 240, 480, 900, 900, 900],+ );+ });++ /// One connection on a fake clock, dialled through an in-memory relay ([relay] holds the relay's+ /// end of every dial, so its length is the number of dials). The first dial is parked, as the+ /// app parks it when the relay answers the select with "offline".+ void parked(+ void Function(FakeAsync clock, WsConn conn, List<MemoryWebSocket> relay)+ body,+ ) {+ fakeAsync((clock) {+ final relay = <MemoryWebSocket>[];+ final conn = WsConn(+ wsBaseUrl: 'ws://fixture.invalid',+ connectChannel: (_, {protocols}) {+ final (client, server) = MemoryWebSocket.pair();+ server.stream.listen((_) {});+ relay.add(server);+ client.accept();+ return client;+ },+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => 'token',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );+ unawaited(conn.connect());+ clock.flushMicrotasks();+ conn.parkUntilOnline();+ expect(relay, hasLength(1));+ expect(conn.isParked, isTrue);+ body(clock, conn, relay);+ unawaited(conn.close());+ clock.flushMicrotasks();+ });+ }++ /// The dial just made hears "offline" again, and the app parks it once more.+ void stillOff(FakeAsync clock, WsConn conn) {+ clock.flushMicrotasks();+ conn.parkUntilOnline();+ expect(conn.isParked, isTrue);+ }++ test('dials again after 1, 2, 4, 8 and then every 15 minutes', () {+ parked((clock, conn, relay) {+ for (final (minutes, dials) in [+ (1, 2),+ (2, 3),+ (4, 4),+ (8, 5),+ (15, 6),+ (15, 7),+ ]) {+ clock.elapse(Duration(minutes: minutes) - const Duration(seconds: 1));+ expect(relay, hasLength(dials - 1), reason: 'before $minutes min');+ clock.elapse(const Duration(seconds: 1));+ expect(relay, hasLength(dials), reason: 'at $minutes min');+ stillOff(clock, conn);+ }+ });+ });++ test('word that the machine is back dials at once and starts the waits over', () {+ parked((clock, conn, relay) {+ // Three rechecks of its own: the next one is eight minutes away.+ for (final minutes in [1, 2, 4]) {+ clock.elapse(Duration(minutes: minutes));+ stillOff(clock, conn);+ }+ expect(relay, hasLength(4));++ // The relay's push says it is back, and the dial finds it off after all.+ conn.wake('the relay says it is online');+ stillOff(clock, conn);+ expect(relay, hasLength(5));++ // A minute again, not eight.+ clock.elapse(const Duration(minutes: 1));+ expect(relay, hasLength(6));+ });+ });++ test('somebody asking for it (the app back in front, a tap) dials at once and starts over', () {+ parked((clock, conn, relay) {+ for (final minutes in [1, 2]) {+ clock.elapse(Duration(minutes: minutes));+ stillOff(clock, conn);+ }+ conn.reconnectNow();+ stillOff(clock, conn);+ expect(relay, hasLength(4));++ clock.elapse(const Duration(minutes: 1));+ expect(relay, hasLength(5));+ });+ });++ test('a connection that came up, then lost its machine, starts from a minute again', () {+ parked((clock, conn, relay) {+ for (final minutes in [1, 2, 4]) {+ clock.elapse(Duration(minutes: minutes));+ stillOff(clock, conn);+ }++ // The eight-minute recheck finds the machine up: the select is answered.+ clock.elapse(const Duration(minutes: 8));+ clock.flushMicrotasks();+ relay.last.sink.add(+ jsonEncode({+ 'type': 'connected',+ 'payload': {'machineId': 'm'},+ }),+ );+ clock.flushMicrotasks();+ expect(conn.isReady, isTrue);+ expect(conn.isParked, isFalse);++ // Later the socket drops and the machine is off: the ordinary backoff dials, and the park+ // after it waits a minute, not fifteen.+ unawaited(relay.last.sink.close());+ clock.elapse(const Duration(seconds: 1));+ expect(relay, hasLength(6));+ stillOff(clock, conn);++ clock.elapse(const Duration(minutes: 1));+ expect(relay, hasLength(7));+ });+ });++ test(+ 'in the background it stops dialling on its own; coming back asks at once',+ () {+ parked((clock, conn, relay) {+ conn.pauseParkedRecheck();+ clock.elapse(const Duration(hours: 2));+ expect(relay, hasLength(1));+ // Still waiting for the machine: a push would still wake it.+ expect(conn.isParked, isTrue);++ conn.reconnectNow();+ stillOff(clock, conn);+ expect(relay, hasLength(2));++ clock.elapse(const Duration(minutes: 1));+ expect(relay, hasLength(3));+ });+ },+ );++ test('a push still wakes a connection paused in the background', () {+ parked((clock, conn, relay) {+ conn.pauseParkedRecheck();+ conn.wake('the relay says it is online');+ clock.flushMicrotasks();+ expect(relay, hasLength(2));+ });+ });++ test('pausing leaves a connection that is not parked to its own backoff', () {+ parked((clock, conn, relay) {+ // The machine answers, then the socket drops: an ordinary reconnect, not a park.+ relay.last.sink.add(+ jsonEncode({+ 'type': 'connected',+ 'payload': {'machineId': 'm'},+ }),+ );+ clock.flushMicrotasks();+ expect(conn.isReady, isTrue);+ unawaited(relay.last.sink.close());+ clock.flushMicrotasks();++ conn.pauseParkedRecheck();+ clock.elapse(const Duration(seconds: 1));+ expect(relay, hasLength(2));+ });+ });+}