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): dial every machine again the moment the app comes back
bubu-dudu706054c1e121
diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dartindex 05e43abd5..f5c7e193c 100644--- a/mobile/lib/phone/phone_shell.dart+++ b/mobile/lib/phone/phone_shell.dart@@ -55,12 +55,19 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {super.dispose();}- /// Back in the foreground: a p2p retry waiting out its delay fires now. Going to- /// the background needs nothing — the OS suspends the socket, and its redial- /// tears the old wire down and negotiates a fresh one.+ /// Back in the foreground: a p2p retry waiting out its delay fires now, and so does every machine+ /// socket the phone lost while it was away. Going to the background needs nothing — the OS+ /// suspends the socket, and the redial tears the old wire down and negotiates a fresh one.+ ///+ /// ⚠️ The two used to be one line, and the missing half showed. P2P was kicked here from the+ /// start; the WebSocket underneath it was not, so a phone coming back sat through a backoff that+ /// had already climbed to its 30s ceiling — the machine list saying "Connecting…" at somebody+ /// who was looking straight at it, with a network that would have answered at once.@overridevoid didChangeAppLifecycleState(AppLifecycleState state) {- if (state == AppLifecycleState.resumed) phoneTerminalP2p.kickRetry();+ if (state != AppLifecycleState.resumed) return;+ phoneTerminalP2p.kickRetry();+ widget.notifier.handleAppResumed();}NavigatorState? get _currentNavigator => _navigators[_tab]?.currentState;diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 32a04545b..25ee1af56 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -5578,6 +5578,18 @@ class AppNotifier extends ChangeNotifier {Map<String, dynamic> event,) => _handleEvent(machineId, event);+ /// The app is back in front of somebody: every machine socket the phone lost while it was away+ /// dials again now instead of waiting out a backoff nobody is watching.+ ///+ /// ⚠️ The phone loses these sockets by being BACKGROUNDED — the OS stops the process, and it is+ /// not obliged to say so. Nothing here detects that at the time, and nothing can: a suspended+ /// process runs no code to notice with. Resuming is the first moment the app is able to look, so+ /// it is the moment it must.+ ///+ /// Safe to call on every resume. [WsPool.reconnectAll] skips connections that are already open+ /// and connections somebody closed on purpose, so a tab switch that cost nothing costs nothing.+ void handleAppResumed() => _pool?.reconnectAll();+/// What the local CLI closing this machine's socket with [code] does to the/// model — the `WsPool.onLocalFailure` path, without a socket.@visibleForTestingdiff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dartindex e48e2e6ef..6a5e2cc21 100644--- a/mobile/lib/ws/ws_conn.dart+++ b/mobile/lib/ws/ws_conn.dart@@ -725,6 +725,26 @@ class WsConn {_reconnectTimer = Timer(delay, connect);}+ /// Stops waiting out the backoff and dials now — the app has just come back to the foreground,+ /// and the delay that made sense while it was away is pure dead time in front of somebody.+ ///+ /// ⚠️ A no-op when a channel is already open. A phone loses this socket by being backgrounded,+ /// and the OS does not always tell us: coming back to a connection that is in fact alive must not+ /// tear it down to prove it, or every tab switch would cost a fresh handshake.+ ///+ /// ⚠️ A no-op when [_closing]. That flag means somebody decided this connection should stop —+ /// signed out, machine unlinked, 4403 — and resuming the app is not a reason to revive it.+ void reconnectNow() {+ if (_closing || _channel != null) return;+ _reconnectTimer?.cancel();+ _reconnectTimer = null;+ // The clock restarts too. Failures from BEFORE the app went away say nothing about the network+ // it is on now, and without this a phone that had backed off to its 30s ceiling keeps that+ // ceiling against a connection that would succeed immediately.+ _attempt = 0;+ unawaited(connect());+ }+void _rejectPending(String reason) {_settleReadiness(reason);for (final pending in _pending.values) {diff --git a/mobile/lib/ws/ws_pool.dart b/mobile/lib/ws/ws_pool.dartindex e45bfde0f..0b6f9704d 100644--- a/mobile/lib/ws/ws_pool.dart+++ b/mobile/lib/ws/ws_pool.dart@@ -86,6 +86,17 @@ class WsPool {WsConn? operator [](String machineId) => _conns[machineId];bool has(String machineId) => _conns.containsKey(machineId);+ /// Dials every machine that is not currently connected, without waiting out its backoff — see+ /// [WsConn.reconnectNow], which decides per connection whether there is anything to do.+ ///+ /// The whole pool, not just the machine on screen: a phone comes back to a list of machines, and+ /// one that reconnects only when tapped reads as broken until it is.+ void reconnectAll() {+ for (final conn in _conns.values) {+ conn.reconnectNow();+ }+ }+Future<void> closeMachine(String machineId) async {final conn = _conns.remove(machineId);if (conn != null) await conn.close();diff --git a/mobile/test/ws_resume_test.dart b/mobile/test/ws_resume_test.dartnew file mode 100644index 000000000..3bca60414--- /dev/null+++ b/mobile/test/ws_resume_test.dart@@ -0,0 +1,153 @@+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/core/models.dart';+import 'package:harness_mobile/ws/ws_conn.dart';++/// Counts how many times anybody opened a socket, and can drop the ones it holds.+///+/// A phone loses this socket by being backgrounded, which no client-side event reports — so what+/// these tests reproduce is the shape of that loss, not its cause: the wire goes away, and the app+/// finds out by being unable to use it.+class _Hub {+ _Hub._(this.server);++ final HttpServer server;+ final List<WebSocket> live = [];+ int opened = 0;++ int get port => server.port;++ static Future<_Hub> start() async {+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ final hub = _Hub._(server);+ server.listen((request) async {+ if (!WebSocketTransformer.isUpgradeRequest(request)) {+ request.response.statusCode = 404;+ await request.response.close();+ return;+ }+ final ws = await WebSocketTransformer.upgrade(+ request,+ protocolSelector: (protocols) =>+ protocols.isNotEmpty ? protocols.first : null,+ );+ hub.opened++;+ hub.live.add(ws);+ // Whatever the client says, this hub only counts connections.+ ws.listen((_) {}, onDone: () => hub.live.remove(ws));+ });+ return hub;+ }++ Future<void> dropAll() async {+ final all = live.toList();+ live.clear();+ for (final ws in all) {+ await ws.close();+ }+ }++ Future<void> stop() async => server.close(force: true);+}++void main() {+ late _Hub hub;+ final statuses = <ConnectionStatus>[];++ setUp(() async {+ hub = await _Hub.start();+ statuses.clear();+ });++ tearDown(() async => hub.stop());++ WsConn newConn() => WsConn(+ wsBaseUrl: 'ws://127.0.0.1:${hub.port}',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => 'token',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: statuses.add,+ );++ /// Polls rather than waiting a fixed time, and takes a DEADLINE rather than assuming one.+ ///+ /// ⚠️ The deadline is what makes the backoff test mean anything. The first retry is armed at one+ /// second, so a generous wait would go green whether the kick worked or the backoff simply fired+ /// on its own — a test that passes without the fix, which is worse than no test.+ Future<bool> opensReach(+ int count, {+ Duration within = const Duration(seconds: 2),+ }) async {+ final deadline = DateTime.now().add(within);+ while (DateTime.now().isBefore(deadline)) {+ if (hub.opened >= count) return true;+ await Future<void>.delayed(const Duration(milliseconds: 10));+ }+ return hub.opened >= count;+ }++ test('a live connection is left alone', () async {+ final conn = newConn();+ addTearDown(conn.close);+ await conn.connect();+ expect(await opensReach(1), isTrue);++ conn.reconnectNow();+ conn.reconnectNow();+ await Future<void>.delayed(const Duration(milliseconds: 120));++ expect(+ hub.opened,+ 1,+ reason:+ 'a tab switch that cost nothing must cost nothing — tearing down '+ 'a working socket to prove it is alive is a fresh handshake per switch',+ );+ });++ test(+ 'a lost connection dials again without waiting out its backoff',+ () async {+ final conn = newConn();+ addTearDown(conn.close);+ await conn.connect();+ expect(await opensReach(1), isTrue);++ // The wire goes away the way a backgrounded phone's does: from the far end, with nothing said.+ await hub.dropAll();+ // Long enough for the client to notice and arm its backoff, short enough that the backoff+ // itself — a second on the first attempt, climbing to thirty — has not fired.+ await Future<void>.delayed(const Duration(milliseconds: 150));+ final beforeKick = hub.opened;++ conn.reconnectNow();++ // ⚠️ Well inside the ~850ms still left on that first backoff. Reaching the hub this early is+ // the whole assertion: the dial can only have come from the kick.+ expect(+ await opensReach(+ beforeKick + 1,+ within: const Duration(milliseconds: 350),+ ),+ isTrue,+ );+ },+ );++ test('a connection somebody closed stays closed', () async {+ final conn = newConn();+ await conn.connect();+ expect(await opensReach(1), isTrue);+ await conn.close();+ final afterClose = hub.opened;++ // Signed out, machine unlinked, SSO refused: resuming the app is not a reason to revive it.+ conn.reconnectNow();+ await Future<void>.delayed(const Duration(milliseconds: 150));++ expect(hub.opened, afterClose);+ });+}