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): redial a socket that went silent instead of waiting
tony8ca5a9ef9af4
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 277f3261d..fd6cf2501 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -4993,6 +4993,50 @@ class AppNotifier extends ChangeNotifier {unawaited(connection.forceReconnect());}+ /// A socket that still calls itself open but has stopped bringing anything from its machine:+ /// put its terminals down as a dropped socket's are, and dial it again. True when it did; false+ /// leaves everything as it was, for the caller's own repair.+ ///+ /// Two callers, one rule each:+ /// - a terminal stream quiet for 15s on a socket that heard nothing from the machine in that time+ /// ([TerminalSession.onTransportSilent]);+ /// - the app back from the background after [resumeRedialAfter], on a socket that heard nothing+ /// while it was away ([handleAppResumed]).+ ///+ /// ⚠️ **The sessions go down first, because [WsConn.forceReconnect] does not say so.** It drops+ /// the old channel without a close event and dials again reporting `connecting`, which+ /// [_onConnectionStatus] — rightly — does not read as a lost socket. Without this, every+ /// terminal would stay `controlling` on a stream that left with the old socket, and wait out its+ /// own watchdog all over again. Marked lost here, as the `reconnecting` branch there marks them,+ /// the new socket's `connected` puts them back: the one on screen through+ /// [MachineState.pendingOfflineAgentId], the rest through `_attachPendingPanes`, each in place+ /// with its screen kept ([_reattachPane]).+ ///+ /// ⚠️ **Not offline.** The machine may be perfectly fine — it is the phone's own line to the+ /// relay that went (a network switch, a tunnel), so this is [_recoverStaleSession]'s redial+ /// without its offline flag, which would flash "Offline" over a machine nobody lost.+ ///+ /// ⚠️ **Only a connection that is up and can redial.** One mid-dial is already on its way back,+ /// and redialling it would throw that dial away; one that cannot redial+ /// ([WsConn.canForceReconnect]) would leave the sessions marked lost with no socket coming.+ bool _redialStaleTransport(+ MachineState machine,+ WsConn connection, {+ required String why,+ }) {+ if (_disposed || !connection.isReady || !connection.canForceReconnect) {+ return false;+ }+ appLog.info(+ 'ws',+ '${_shortId(machine.machine.machineId)}: $why — dialling the relay again',+ );+ _markSessionsUnreachable(machine, 'Connection lost. Reconnecting…');+ notifyListeners();+ unawaited(connection.forceReconnect());+ return true;+ }+bool _machineWorkCurrent(MachineState machine, int revision) =>_authWorkCurrent(revision) &&identical(machineStates[machine.machine.machineId], machine);@@ -7840,6 +7884,19 @@ class AppNotifier extends ChangeNotifier {await connection.forceReconnect();return true;},+ // A live stream gone quiet on a socket that heard nothing from the machine either — see+ // [TerminalSession.onTransportSilent]. The socket held now, never one built for the asking:+ // a pane whose machine has no socket has nothing to redial.+ onTransportSilent: () {+ final machine = machineStates[pane.machineId];+ final connection = _heldConnection(pane.machineId);+ if (machine == null || connection == null) return false;+ return _redialStaleTransport(+ machine,+ connection,+ why: 'a terminal stream and its socket went quiet',+ );+ },// ⚠️ **Opening IS taking, for everything a person does.** A page opened, swiped onto or// restored at launch claims the terminal; the one open that still asks politely is the warm// tile the pager builds ahead of the thumb, which is a guess and must not cost the desktop@@ -8808,6 +8865,9 @@ class AppNotifier extends ChangeNotifier {////// 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.+ ///+ /// An open socket is not always a live one, though: after [resumeRedialAfter] away, one that+ /// heard nothing from its machine meanwhile is dialled again too — see [_redialSocketsSilentSince].void handleAppResumed() {if (kTypingTrace) {final pane = focusedPane;@@ -8816,7 +8876,15 @@ class AppNotifier extends ChangeNotifier {' ${pane == null ? '-' : '${_shortId(pane.machineId)}/${_shortId(pane.agentId ?? '-')}'}',);}+ final pausedAt = _pausedAt;+ _pausedAt = null;_pool?.reconnectAll();+ // After reconnectAll, not before: a socket it has just started dialling is not ready, and is+ // left to that dial.+ if (pausedAt != null &&+ DateTime.now().difference(pausedAt) >= resumeRedialAfter) {+ _redialSocketsSilentSince(pausedAt);+ }// Back in front of the agent that was on screen: whatever it finished// while the phone was in a pocket has now been seen._seeWatchedAgent();@@ -8847,12 +8915,68 @@ class AppNotifier extends ChangeNotifier {/// And write the machine cache now ([_keepMachineCache]): this is the last moment the app is sure/// to run, since closing it from the app switcher starts by sending it here.void handleAppPaused() {+ // The first pause of this time away: a second without a resume between (the OS repeating+ // itself) does not move the moment the phone actually left.+ _pausedAt ??= DateTime.now();_desk.pause();_stopDeafPoll();// The agents this run learned between lists, for the next launch — see [_keepMachineCache]._keepMachineCache();}+ /// When the app last went into the background ([handleAppPaused]); null while it is in front.+ DateTime? _pausedAt;++ /// How long the app has to have been away before [handleAppResumed] stops trusting an open+ /// socket that heard nothing from its machine in that time.+ ///+ /// ⚠️ **Thirty seconds, the daemon's terminal lease** (`HEARTBEAT_TIMEOUT_MS`,+ /// `cli/src/lib/terminalStreamManager.ts`). A phone the OS suspended sends no `terminal_alive`, so+ /// past this the daemon has closed this phone's terminal streams anyway, and they have to be+ /// opened again whatever the socket: a fresh socket costs nothing they were not going to cost.+ /// Shorter, a glance at another app would redial a socket that was fine and reopen terminals+ /// that were still live — the "every tab switch costs a handshake" [WsConn.reconnectNow] warns+ /// about.+ ///+ /// A field rather than a constant only so a test can stand in for half a minute in a pocket, as+ /// [trustSettleRound] does for its wait.+ @visibleForTesting+ Duration resumeRedialAfter = const Duration(seconds: 30);++ /// Back after [resumeRedialAfter] away: dial again every socket that still calls itself open+ /// but heard nothing from its machine since [since], the moment the app left.+ ///+ /// ⚠️ **Why an open socket is not taken at its word.** The phone's line to the relay is lost by+ /// being backgrounded, and above all by the network changing under it — Wi-Fi giving way to 4G+ /// in a pocket — and the OS does not always say so: the old socket stays "open", bound to a+ /// network that is gone, and takes every send while nothing comes back. Waited out, that was the+ /// terminal's 15s watchdog plus its repairs, about twenty seconds of a screen that looked live+ /// and took no keys; dialled now, the terminal is back in a couple of seconds.+ ///+ /// ⚠️ **Nothing heard while away is the test, not the time away alone.** A phone whose OS let it+ /// run in the background (Android often does, for a while) kept its streams alive and heard+ /// their sync frames: that socket is proved alive and left alone, terminals and all.+ ///+ /// Only a machine with a terminal attached: this exists to bring terminals back, and a machine+ /// with none has nothing on screen waiting — its socket keeps its own repairs, as it did.+ void _redialSocketsSilentSince(DateTime since) {+ if (status != AppStatus.authenticated) return;+ final away = DateTime.now().difference(since).inSeconds;+ for (final machine in machineStates.values.toList()) {+ final machineId = machine.machine.machineId;+ if (!panesFor(machineId).any((pane) => pane.session != null)) continue;+ final connection = _heldConnection(machineId);+ if (connection == null) continue;+ final heard = connection.lastHeardFromMachineAt;+ if (heard != null && heard.isAfter(since)) continue;+ _redialStaleTransport(+ machine,+ connection,+ why: 'back after ${away}s away with nothing heard from it',+ );+ }+ }+/// The app lost the foreground for a moment — the app switcher, a system sheet. Nothing stops;/// only the machine cache is written ([_keepMachineCache]), because the switcher is where an app/// is closed, and closing it there need not pass through [handleAppPaused] first.diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dartindex a88685ac6..b9ed2388e 100644--- a/mobile/lib/terminal/terminal_session.dart+++ b/mobile/lib/terminal/terminal_session.dart@@ -169,9 +169,23 @@ class TerminalSession extends ChangeNotifier {/// When the transport last heard from this session's MACHINE — a frame it sealed, not the/// relay's own (`WsConn.lastHeardFromMachineAt`). Null hook: the open watchdog keeps its old,- /// impatient rule (see [_openPatience]).+ /// impatient rule (see [_openPatience]), and a quiet stream is always resynced+ /// ([_sendHeartbeat]) rather than its transport redialled.final DateTime? Function()? lastHeardFromMachine;+ /// Takes this machine's whole transport down and dials it again, because a stream on it went+ /// quiet and the socket heard nothing from the machine in that time either — see+ /// [_sendHeartbeat]. Returns whether it did; false (the socket is mid-dial already, or cannot+ /// redial) leaves the stream to its own resync.+ ///+ /// ⚠️ **The whole socket, not this stream.** A socket left half-open (Wi-Fi giving way to 4G)+ /// carries every terminal of the machine, and every one of them is as dead as this one. Asking+ /// the daemon for a resync over it would wait out three unanswered tries and an open's patience —+ /// about twenty more seconds — before anything redialled. The caller marks the machine's+ /// sessions lost before the redial (`AppNotifier._redialStaleTransport`), which is what puts+ /// them back, screens kept, once the new socket is up.+ final bool Function()? onTransportSilent;+/// This client's own introduction, sent with every `terminal_open`; null/// for a viewer that never takes control and so is never anyone's taker.final TerminalClientDescriptor? client;@@ -186,6 +200,7 @@ class TerminalSession extends ChangeNotifier {this.client,this.onOpenStalled,this.lastHeardFromMachine,+ this.onTransportSilent,this.resyncTimeout = const Duration(seconds: 4),this.takeover = true,this.scrollMemory,@@ -386,6 +401,11 @@ class TerminalSession extends ChangeNotifier {/// Heartbeats in a row that heard nothing on this stream — see [_sendHeartbeat].int _quietBeats = 0;+ /// When this stream was last heard from: its `terminal_ready`, then each frame of it. Set beside+ /// every reset of [_quietBeats], and compared against [lastHeardFromMachine] — never with a+ /// clock's duration — to tell a dead socket from a dead stream ([_transportSilentToo]).+ DateTime? _lastHeardOnStream;+/// The heartbeats a live stream cannot go without a frame: at least 15s of silence, the/// desktop's limit. Four, not three, because the count is of beats that heard nothing, and the/// last frame may have landed just before the first of them.@@ -825,6 +845,7 @@ class TerminalSession extends ChangeNotifier {// beating after [dispose]._heartbeat?.cancel();_quietBeats = 0;+ _lastHeardOnStream = DateTime.now();_heartbeat = Timer.periodic(const Duration(seconds: 5),(_) => unawaited(_sendHeartbeat()),@@ -1012,6 +1033,7 @@ class TerminalSession extends ChangeNotifier {if (_disposed || frame.streamId != streamId) return;// Heard from: whatever the frame turns out to be, the stream is alive — see [_sendHeartbeat]._quietBeats = 0;+ _lastHeardOnStream = DateTime.now();final generation = _generation;_renderTail = _renderTail.then((_) async {@@ -2030,6 +2052,13 @@ class TerminalSession extends ChangeNotifier {////// Counted in beats, not by the clock, on purpose: an app the OS suspended runs no timers, so/// the gap it was away is no beat at all, and coming back is not taken for a silence.+ ///+ /// Which repair, once the stream has gone quiet that long:+ /// - **The socket heard nothing from the machine either** ([_transportSilentToo]): the socket is+ /// what died, and every stream on it with it. It is redialled at once ([onTransportSilent]),+ /// skipping the resync tries and the open's patience that only a live socket could answer.+ /// - **The socket still hears the machine** (another agent's output, its sync frames, a reply):+ /// only this stream is gone, and the daemon can repair it — the resync, then a reopen.Future<void> _sendHeartbeat() async {if (!acceptsInput) return;final generation = _generation;@@ -2041,9 +2070,30 @@ class TerminalSession extends ChangeNotifier {if (!_isCurrent(generation) || !acceptsInput) return;if (++_quietBeats < _quietBeatsBeforeResync) return;_quietBeats = 0;+ if (_transportSilentToo() && (onTransportSilent?.call() ?? false)) return;+ // Read again: a redial the hook declined may still have taken this session down meanwhile —+ // another stream of the machine got there first — and a resync now would overwrite its+ // "Connection lost" with a timeout for a stream that is already being put back.+ if (!_isCurrent(generation) || !acceptsInput) return;await _requestResync('TERMINAL_STREAM_TIMEOUT');}+ /// Whether the machine's socket has heard nothing from the machine since this stream was last+ /// heard from — so the silence is the socket's, not this stream's alone.+ ///+ /// Both times are moments, compared with each other, never a duration on a clock: an app the OS+ /// suspended keeps both where they were, and the comparison stays true across the gap. A socket+ /// carries every frame its machine seals — this stream's sync frames among them, every five+ /// seconds — so on a live socket the machine is heard from after this stream's last frame as+ /// soon as anything else of it arrives. False when there is no hook to ask, or the socket has+ /// never heard the machine at all: the resync stays the repair, as it was before this check.+ bool _transportSilentToo() {+ final heard = lastHeardFromMachine?.call();+ final streamHeard = _lastHeardOnStream;+ if (heard == null || streamHeard == null) return false;+ return !heard.isAfter(streamHeard);+ }+Future<void> _requestResync(String reason) async {if (kTypingTrace) {typingEvent(diff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dartindex 4bc4f71c1..1831d2a90 100644--- a/mobile/lib/ws/ws_conn.dart+++ b/mobile/lib/ws/ws_conn.dart@@ -199,6 +199,11 @@ class WsConn {/// True once this connection has permanently given up (a deliberate [close], or a non-retryable/// local failure like NO_PEER_LINK) — [WsPool] must not hand a closed connection back out.bool get isClosed => _closing;++ /// Whether [forceReconnect] would dial again: a relay connection nobody has closed. Read it+ /// before taking this machine's terminals down for a redial — when it is false, the redial is a+ /// no-op, and the terminals would sit on "Connection lost" waiting for a socket that never comes.+ bool get canForceReconnect => !_closing && relayCodecs != null;String get endpointKey => 'cloud:$wsBaseUrl:$autonomousEnv';WsConn({diff --git a/mobile/test/state/stale_socket_redial_test.dart b/mobile/test/state/stale_socket_redial_test.dartnew file mode 100644index 000000000..3f92f2475--- /dev/null+++ b/mobile/test/state/stale_socket_redial_test.dart@@ -0,0 +1,258 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/terminal/terminal_session.dart';++import '../phone_edge/edge_fixture.dart';++/// A machine's socket as the app holds it, with the three things a stale-socket redial reads made+/// settable: whether it is up, whether it can dial again, and when it last heard its machine. A+/// redial is counted, never dialled.+class _HeldConn extends EdgeConn {+ bool ready = true;+ bool redials = true;+ DateTime? heard;+ int redialled = 0;++ @override+ bool get isReady => ready;++ @override+ bool get canForceReconnect => redials;++ @override+ DateTime? get lastHeardFromMachineAt => heard;++ @override+ Future<void> forceReconnect() async => redialled++;+}++/// A socket that still calls itself open but brings nothing from its machine — Wi-Fi giving way to+/// 4G under a phone in a pocket — is dialled again, and the terminals on it are put back once the+/// new one is up: on the way back from the background (`handleAppResumed`), and when a terminal+/// stream goes quiet with its socket quiet too (`TerminalSession.onTransportSilent`).+void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ late _HeldConn conn;+ late AppNotifier app;++ setUp(() {+ conn = _HeldConn();+ // Signed in, as a phone with terminals open is: a signed-out one has nothing to dial again.+ app = edgeApp(conn: conn)..status = AppStatus.authenticated;+ addTearDown(app.dispose);+ });++ /// A terminal on agent `a`, live and held.+ Future<TerminalSession> attached() => liveTerminal(app, 'a');++ /// The phone in a pocket and back at once, with [threshold] standing in for the half-minute the+ /// redial waits for: zero, any time away counts.+ void awayAndBack({Duration threshold = Duration.zero}) {+ app.resumeRedialAfter = threshold;+ app.handleAppPaused();+ app.handleAppResumed();+ }++ group('back from the background', () {+ test(+ 'a socket that heard nothing while the phone was away is dialled '+ 'again, and its terminal marked lost so the new socket puts it back',+ () async {+ final session = await attached();+ conn.heard = DateTime(2000);++ awayAndBack();++ expect(conn.redialled, 1);+ expect(session.status, TerminalSessionStatus.error);+ expect(session.errorMessage, 'Connection lost. Reconnecting…');+ // What the reconnect's `connected` reattaches first: the terminal on screen.+ expect(app.stateOf('m')!.pendingOfflineAgentId, 'a');+ // The phone's line went, not the machine: nothing reads "Offline".+ expect(app.stateOf('m')!.nodeOnline, isNot(false));+ },+ );++ test(+ 'a socket that never heard its machine at all is dialled again too',+ () async {+ await attached();+ conn.heard = null;++ awayAndBack();++ expect(conn.redialled, 1);+ },+ );++ test('a socket that heard its machine while the phone was away is left '+ 'alone, terminal and all', () async {+ final session = await attached();+ app.resumeRedialAfter = Duration.zero;+ app.handleAppPaused();+ // The OS let it run (Android often does): sync frames kept arriving.+ conn.heard = DateTime.now().add(const Duration(seconds: 1));+ app.handleAppResumed();++ expect(conn.redialled, 0);+ expect(session.status, TerminalSessionStatus.controlling);+ });++ test('a glance at another app keeps the socket: shorter than the '+ "daemon's lease, nothing is dialled again", () async {+ final session = await attached();+ conn.heard = DateTime(2000);++ awayAndBack(threshold: const Duration(seconds: 30));++ expect(conn.redialled, 0);+ expect(session.status, TerminalSessionStatus.controlling);+ });++ test('a resume with no pause before it — the shell mounting at launch — '+ 'dials nothing again', () async {+ await attached();+ conn.heard = DateTime(2000);+ app.resumeRedialAfter = Duration.zero;++ app.handleAppResumed();++ expect(conn.redialled, 0);+ });++ test(+ 'only the first pause counts: away is from when the phone left',+ () async {+ await attached();+ conn.heard = DateTime(2000);+ app.resumeRedialAfter = Duration.zero;+ app.handleAppPaused();+ app.handleAppPaused();+ app.handleAppResumed();+ // Spent by that resume: a second resume with no pause is a launch, not a return.+ app.handleAppResumed();++ expect(conn.redialled, 1);+ },+ );++ test('a socket mid-dial is left to its dial', () async {+ final session = await attached();+ conn+ ..heard = DateTime(2000)+ ..ready = false;++ awayAndBack();++ expect(conn.redialled, 0);+ expect(session.status, TerminalSessionStatus.controlling);+ });++ test('a socket that cannot dial again is not taken down', () async {+ final session = await attached();+ conn+ ..heard = DateTime(2000)+ ..redials = false;++ awayAndBack();++ expect(conn.redialled, 0);+ expect(session.status, TerminalSessionStatus.controlling);+ });++ test(+ 'a machine with no terminal attached is left to its own repairs',+ () async {+ conn.heard = DateTime(2000);++ awayAndBack();++ expect(conn.redialled, 0);+ },+ );++ test('a phone not signed in dials nothing again', () async {+ await attached();+ conn.heard = DateTime(2000);+ app.status = AppStatus.unauthenticated;++ awayAndBack();++ expect(conn.redialled, 0);+ });++ test('a terminal another app took stays taken while the socket is dialled '+ 'again', () async {+ final session = await attached();+ await session.handleFrame('terminal_closed', {+ 'streamId': session.streamId,+ 'code': 'TERMINAL_TAKEN_OVER',+ 'reason': 'another client connected',+ });+ conn.heard = DateTime(2000);++ awayAndBack();++ expect(conn.redialled, 1);+ // Only the person's own retry may win it back — see `transportLost`.+ expect(session.status, TerminalSessionStatus.takenOver);+ expect(app.stateOf('m')!.pendingOfflineAgentId, isNull);+ });+ });++ group('a terminal stream and its socket gone quiet', () {+ /// A terminal the app opened itself, so it carries the app's own hooks.+ Future<TerminalSession> opened() async {+ app.stateOf('m')!.terminalCapabilityAvailable = true;+ await app.selectAgent('m', 'a');+ final session = app.paneOfAgent('m', 'a')?.session;+ expect(session, isNotNull, reason: 'the app opened a terminal');+ return session!;+ }++ test("the app's hook dials the socket again and marks the machine's "+ 'terminals lost', () async {+ final session = await opened();++ expect(session.onTransportSilent!(), isTrue);++ expect(conn.redialled, 1);+ expect(session.status, TerminalSessionStatus.error);+ expect(session.errorMessage, 'Connection lost. Reconnecting…');+ expect(app.stateOf('m')!.nodeOnline, isNot(false));+ });++ test('its hook asks the socket the app holds when it last heard the '+ 'machine', () async {+ final session = await opened();+ final heard = DateTime(2024, 5, 6);+ conn.heard = heard;++ expect(session.lastHeardFromMachine!(), heard);+ });++ test(+ 'declined while the socket is mid-dial: nothing is taken down, and the '+ 'stream keeps its own repair',+ () async {+ final session = await opened();+ final before = session.status;+ conn.ready = false;++ expect(session.onTransportSilent!(), isFalse);++ expect(conn.redialled, 0);+ expect(session.status, before);+ },+ );++ test('declined when the socket cannot dial again', () async {+ final session = await opened();+ conn.redials = false;++ expect(session.onTransportSilent!(), isFalse);+ expect(conn.redialled, 0);+ });+ });+}diff --git a/mobile/test/terminal_session_protocol_test.dart b/mobile/test/terminal_session_protocol_test.dartindex 1b7059cfa..63af47f6f 100644--- a/mobile/test/terminal_session_protocol_test.dart+++ b/mobile/test/terminal_session_protocol_test.dart@@ -22,6 +22,8 @@ void main() {String engine = 'claude',bool takeover = true,Future<bool> Function()? onOpenStalled,+ DateTime? Function()? lastHeardFromMachine,+ bool Function()? onTransportSilent,Duration resync = const Duration(milliseconds: 40),bool disposeAtEnd = true,}) {@@ -34,6 +36,8 @@ void main() {sendBinary: wire.sendBinary,client: const TerminalClientDescriptor(kind: 'phone', name: 'Pat'),onOpenStalled: onOpenStalled,+ lastHeardFromMachine: lastHeardFromMachine,+ onTransportSilent: onTransportSilent,resyncTimeout: resync,takeover: takeover,);@@ -484,6 +488,150 @@ void main() {s.dispose();});});++ // The socket heard nothing from the machine for as long as the stream was quiet: the socket is+ // what died (a half-open line after a network switch), and a resync over it would only wait+ // out three unanswered tries and an open's patience before anything redialled.+ group('quiet on a socket that is quiet too', () {+ /// The socket's last word from the machine, [heard], as the hook reports it; and every call+ /// of the redial hook, answered [redials].+ ({TerminalSession s, List<void> asked}) quietOn(+ FakeAsync async, {+ required DateTime? heard,+ bool redials = true,+ bool hook = true,+ }) {+ final asked = <void>[];+ final s = session(+ disposeAtEnd: false,+ lastHeardFromMachine: () => heard,+ onTransportSilent: hook+ ? () {+ asked.add(null);+ return redials;+ }+ : null,+ );+ liveOn(async, s);+ return (s: s, asked: asked);+ }++ test('the socket is dialled again at once, the stream not resynced', () {+ fakeAsync((async) {+ final (:s, :asked) = quietOn(async, heard: DateTime(2000));++ async.elapse(const Duration(seconds: 15));+ expect(asked, isEmpty, reason: 'three beats are not yet a silence');++ async.elapse(const Duration(seconds: 5));+ expect(asked, hasLength(1));+ expect(wire.of('terminal_resync'), isEmpty);+ s.dispose();+ });+ });++ test('a socket that still hears the machine leaves the repair to the '+ 'stream: resynced, nothing redialled', () {+ fakeAsync((async) {+ // Heard after this stream's last frame: another agent's output, a reply.+ final (:s, :asked) = quietOn(+ async,+ heard: DateTime.now().add(const Duration(hours: 1)),+ );++ async.elapse(const Duration(seconds: 20));++ expect(asked, isEmpty);+ expect(s.errorCode, 'TERMINAL_STREAM_TIMEOUT');+ expect(wire.of('terminal_resync'), hasLength(1));+ s.dispose();+ });+ });++ test('a redial the app declines leaves the stream to its resync', () {+ fakeAsync((async) {+ final (:s, :asked) = quietOn(+ async,+ heard: DateTime(2000),+ redials: false,+ );++ async.elapse(const Duration(seconds: 20));++ expect(asked, hasLength(1));+ expect(wire.of('terminal_resync'), hasLength(1));+ s.dispose();+ });+ });++ test('a socket that never heard the machine is no proof: resynced', () {+ fakeAsync((async) {+ final (:s, :asked) = quietOn(async, heard: null);++ async.elapse(const Duration(seconds: 20));++ expect(asked, isEmpty);+ expect(wire.of('terminal_resync'), hasLength(1));+ s.dispose();+ });+ });++ test('with no redial hook, the stream is resynced as before', () {+ fakeAsync((async) {+ final (:s, asked: _) = quietOn(+ async,+ heard: DateTime(2000),+ hook: false,+ );++ async.elapse(const Duration(seconds: 20));++ expect(wire.of('terminal_resync'), hasLength(1));+ s.dispose();+ });+ });++ test('a redial that took the session down meanwhile is not followed by '+ 'a resync over its "Connection lost"', () {+ fakeAsync((async) {+ late TerminalSession s;+ s = session(+ disposeAtEnd: false,+ lastHeardFromMachine: () => DateTime(2000),+ // Declined for this stream, but another stream of the machine got there first and+ // the app took every session of it down.+ onTransportSilent: () {+ s.transportLost('Connection lost. Reconnecting…');+ return false;+ },+ );+ liveOn(async, s);++ async.elapse(const Duration(seconds: 20));++ expect(wire.of('terminal_resync'), isEmpty);+ expect(s.errorMessage, 'Connection lost. Reconnecting…');+ s.dispose();+ });+ });++ test('the stream heard from again resets it: no redial for a quiet '+ 'that ended', () {+ fakeAsync((async) {+ final (:s, :asked) = quietOn(async, heard: DateTime(2000));+ final streamId = s.streamId!;++ async.elapse(const Duration(seconds: 15));+ s.handleBinary(_sync(streamId, 1));+ async.flushMicrotasks();+ async.elapse(const Duration(seconds: 15));++ expect(asked, isEmpty);+ expect(wire.of('terminal_resync'), isEmpty);+ s.dispose();+ });+ });+ });});group('the screen and the output after it', () {diff --git a/mobile/test/ws/ws_conn_relay_test.dart b/mobile/test/ws/ws_conn_relay_test.dartindex e40c4a575..56a665ad0 100644--- a/mobile/test/ws/ws_conn_relay_test.dart+++ b/mobile/test/ws/ws_conn_relay_test.dart@@ -625,4 +625,40 @@ void main() {},);});++ // Read before the app takes a machine's terminals down for a redial (a socket gone quiet, a+ // return from the background): when it is false, `forceReconnect` would do nothing, and the+ // terminals would wait on "Connection lost" for a socket that never comes.+ group('whether a redial would dial', () {+ test('a relay connection, up, can be dialled again', () async {+ final (conn, _) = await connected();++ expect(conn.canForceReconnect, isTrue);+ });++ test('and is: a forced redial opens a fresh socket', () async {+ final (conn, _) = await connected();+ final next = relay.nextLink();++ await conn.forceReconnect();++ await next.timeout(const Duration(seconds: 3));+ await conn.waitUntilReady(timeout: const Duration(seconds: 3));+ expect(conn.canForceReconnect, isTrue);+ });++ test('one closed on purpose cannot', () async {+ final (conn, _) = await connected();++ await conn.close();++ expect(conn.canForceReconnect, isFalse);+ });++ test('one with no relay codecs cannot — its forced redial is a no-op', () {+ final conn = newConn(noCodecs: true);++ expect(conn.canForceReconnect, isFalse);+ });+ });}