Skip to content

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.

fix: optimize local daemon reconnection with fixed delay and handle machine ID mismatches

0xken15609b4456d859
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 770c7c84f..5d3d71fbc 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1312,6 +1312,7 @@ class AppNotifier extends ChangeNotifier {
bool get hasAvailableUpdate => availableUpdate != null;
static const offlineRetryInterval = Duration(seconds: 5);
+ static const localDaemonReconnectDelay = Duration(seconds: 1);
static const agentSyncInterval = Duration(seconds: 60);
MachineState? stateOf(String machineId) => machineStates[machineId];
@@ -1639,6 +1640,13 @@ class AppNotifier extends ChangeNotifier {
// with no separate app-side readiness gate to wait on anymore.
if (machine.isLocalMachine) {
machine.transportMode = MachineTransportMode.localPlaintext;
+ // The socket that just connected IS the endpoint. A machine refresh that ran while the
+ // daemon was restarting (connection refused, or still scanning) had probed nothing and
+ // cleared this — and with it `usesLocalTransport`, which `_canAttachPane` and the pane
+ // header both read. The socket then came back on its own 1s retry, `nodeOnline` went true,
+ // the offline poll (the one thing that would have re-probed) stopped, and the tiles sat on
+ // "Offline" over a live terminal with nothing left to restore them. Measured 2026-09-18 21:50.
+ machine.localEndpoint ??= _cliEndpoint;
} else {
machine.transportMode = MachineTransportMode.cloudE2ee;
}
@@ -2868,7 +2876,14 @@ class AppNotifier extends ChangeNotifier {
void _onLocalFailure(String machineId, int code, String reason) {
final machine = machineStates[machineId];
- if (machine == null || code != 4404) return;
+ if (machine == null) return;
+ if (code == 4403) {
+ if (machine.isLocalMachine) {
+ unawaited(_onLocalMachineMismatch(machine, reason));
+ }
+ return;
+ }
+ if (code != 4404) return;
// The local CLI's relay found no linked trust for this machine — it now owns E2EE entirely.
// A `harness link connect` run in a terminal (or another app instance) has no way to notify
// this one directly, so poll every few seconds until it's picked up instead of waiting for
@@ -2890,6 +2905,54 @@ class AppNotifier extends ChangeNotifier {
_startLinkRetry(machineId);
}
+ /// The daemon on this computer closed our select with 4403: it serves a different machine id than
+ /// the row we hold for "this computer". Ask it which (`/api/status.machineId`), say so in the log —
+ /// this used to be a silent reconnect every 30s, forever — and stand its machine up beside the
+ /// stale row so the person can keep working; the stale row's tiles are told why they are dark. A
+ /// machine list refresh re-keys everything properly once the backend answers.
+ Future<void> _onLocalMachineMismatch(
+ MachineState machine,
+ String reason,
+ ) async {
+ final machineId = machine.machine.machineId;
+ if (!_localMismatchReported.add(machineId)) return;
+ final endpoint = viewer == null ? await _discovery.discover() : null;
+ final served = endpoint?.machineId;
+ appLog.warn(
+ 'daemon',
+ 'refused machine_select for $machineId ($reason) — the daemon serves '
+ '${served ?? 'an unknown machine id'}',
+ );
+ if (_disposed || served == null || served == machineId) return;
+ _markSessionsUnreachable(
+ machine,
+ 'This computer now runs as a different machine (sign-in changed). Open it from the rail.',
+ );
+ // Awaited: the close reports `disconnected`, whose handler arms the offline retry — stopping
+ // it before that would be undone a microtask later. `_connectMachine` also refuses this id now.
+ await _pool?.closeMachine(machineId);
+ _stopOfflineRetry(machineId);
+ if (!machineStates.containsKey(served)) {
+ _adoptLocalMachineFromDaemon(
+ endpoint,
+ await _discovery.computerId(),
+ listUnavailable: _backendOnline == false,
+ );
+ final adopted = machineStates[served];
+ if (adopted != null) {
+ adopted.localEndpoint = endpoint;
+ adopted.transportMode = MachineTransportMode.localPlaintext;
+ _connectMachine(adopted);
+ }
+ }
+ notifyListeners();
+ if (_backendOnline != false) unawaited(retryMachines());
+ }
+
+ /// Local machine ids a 4403 has already been reported for — one log line and one adoption per
+ /// stale id, not one per 30s retry.
+ final Set<String> _localMismatchReported = {};
+
void _ensurePool() {
if (_pool != null) return;
_pool = WsPool(
@@ -3126,6 +3189,15 @@ class AppNotifier extends ChangeNotifier {
state.transportMode = state.connectionStatus == ConnectionStatus.connected
? MachineTransportMode.localPlaintext
: MachineTransportMode.localOffline;
+ } else if (state.localOnly &&
+ localEndpoint == null &&
+ state.localEndpoint != null &&
+ state.connectionStatus == ConnectionStatus.connected) {
+ // The probe found nothing this time (the daemon mid-restart, or mid-scan) but the socket to
+ // it is open and answering right now — the socket is the better witness. Keep the endpoint
+ // it was dialed through; demoting a live connection to "offline" on a missed probe is what
+ // took a working terminal's tiles dark.
+ state.transportMode = MachineTransportMode.localPlaintext;
} else if (state.localOnly) {
// The token still identifies this as local, but the CLI is offline or
// failed its identity/capability check. Never fall back to cloud E2EE.
@@ -3219,6 +3291,11 @@ class AppNotifier extends ChangeNotifier {
}
}
machineStates.removeWhere((id, _) => !visible.contains(id));
+ // A retired id the fresh list no longer carries has been re-keyed or removed — its 4403 verdict
+ // is over with it. One the list STILL carries keeps the verdict: on the loopback the daemon is
+ // the authority for which id it serves, and re-dialing on every 15s refresh would be a 4403
+ // and a log line each time.
+ _localMismatchReported.removeWhere((id) => !visible.contains(id));
for (final machine in machines) {
final state = machineStates.update(
machine.machineId,
@@ -3554,6 +3631,9 @@ class AppNotifier extends ChangeNotifier {
);
if (endpoint == null || endpoint.computerId != localComputerId) return;
machine.localEndpoint = endpoint;
+ // The gate never got here (the daemon was down at boot): this is the endpoint it would have
+ // recorded, and every later dial reads it.
+ _cliEndpoint ??= endpoint;
machine.localOnly = true;
machine.transportMode = MachineTransportMode.localPlaintext;
machine.nodeOnline = true;
@@ -3715,6 +3795,10 @@ class AppNotifier extends ChangeNotifier {
void _connectMachine(MachineState machine) {
if (machine.machine.isShared) return;
+ // A row the daemon has refused as "not the machine I serve" is retired until a machine list
+ // re-keys it (_onLocalMachineMismatch): the offline poll and the 15s refresh both reconnect
+ // every row, and would otherwise dial that id again every few seconds, 4403 after 4403.
+ if (_localMismatchReported.contains(machine.machine.machineId)) return;
// connFor() starts a new socket and reports `connecting` through onStatus,
// or returns the existing socket with its current status intact. Do not
// overwrite an already-connected socket when the user collapses and
@@ -3932,9 +4016,23 @@ class AppNotifier extends ChangeNotifier {
: _pool!.connFor(
machineId,
transportKind: WsTransportKind.localPlaintext,
- localWsUri: _cliEndpoint?.wsUri,
+ // The endpoint the offline poll (or the machine refresh) found for THIS row first; the
+ // boot gate's global one only as the fallback. `_cliEndpoint` is set only by a gate that
+ // succeeded, so a boot that found the daemon down and a poll that later found it up
+ // used to dial a null uri — a StateError per attempt, never a socket.
+ localWsUri:
+ machineStates[machineId]?.localEndpoint?.wsUri ??
+ _cliEndpoint?.wsUri,
localProtocolVersion:
- _cliEndpoint?.protocolVersion ?? localWsProtocolVersion,
+ machineStates[machineId]?.localEndpoint?.protocolVersion ??
+ _cliEndpoint?.protocolVersion ??
+ localWsProtocolVersion,
+ // This computer's own daemon: retry every second (see WsConn.fixedReconnectDelay). A
+ // relayed machine keeps the backoff — its select costs the daemon a backend dial.
+ fixedReconnectDelay:
+ machineStates[machineId]?.isLocalMachine == true
+ ? localDaemonReconnectDelay
+ : null,
);
_wireConnectionHooks(connection, machineId);
return connection;
@@ -5631,6 +5729,15 @@ class AppNotifier extends ChangeNotifier {
}
// Do not send terminal_close: the adapter is already gone and the
// next client attachment should be the only stream that owns the pane.
+ //
+ // Once per outage, not once per reconnect attempt: the local socket retries every second
+ // now, and each attempt lands here again through the `reconnecting` status. A pane already
+ // dark with this very message has nothing to learn and nothing to repaint.
+ if (session.status == TerminalSessionStatus.error &&
+ session.errorCode == 'TERMINAL_DISCONNECTED' &&
+ session.errorMessage == message) {
+ continue;
+ }
session.transportLost(message);
}
}
diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dart
index 1ce65bd9c..0eddbef8f 100644
--- a/desktop/lib/ws/ws_conn.dart
+++ b/desktop/lib/ws/ws_conn.dart
@@ -82,6 +82,14 @@ class WsConn {
final String? observerShareId;
final int localProtocolVersion;
+ /// A flat delay between reconnect attempts instead of the exponential backoff (1s→30s). Set for
+ /// the socket to THIS computer's daemon: a refused connect on the loopback costs microseconds and
+ /// nothing on the wire, and the daemon comes back within a second or two of a restart or an
+ /// update handoff — waiting up to 30s to notice is what made a local terminal sit on
+ /// "reconnecting" long after the daemon was up. Null keeps the backoff, which the relayed
+ /// machines need: every one of their selects has the daemon dial the backend (15s handshake).
+ final Duration? fixedReconnectDelay;
+
/// A viewer build's end-to-end session with the machine, minted fresh on every connect — the
/// role the harness CLI plays everywhere else (see [RelayCodec]). Null leaves the relay's frames
/// as they are, which is right for the local transport and the dev fixture.
@@ -154,8 +162,12 @@ class WsConn {
/// local failure like NO_PEER_LINK) — [WsPool] must not hand a closed connection back out.
bool get isClosed => _closing;
bool get isLocal => transportKind == WsTransportKind.localPlaintext;
+
+ /// Must produce exactly what WsPool.connFor computes as its desired key — the pool reuses a
+ /// socket only when the two agree, and closes it otherwise. A key that could never match churned
+ /// every socket on every `_conn()` call (measured: `agents_list` failing "WS closed" in a loop).
String get endpointKey => isLocal
- ? 'local:${localWsUri.toString()}'
+ ? 'local:${localWsUri.toString()}:${fixedReconnectDelay?.inMilliseconds ?? 'backoff'}'
: 'cloud:$wsBaseUrl:$autonomousEnv';
WsConn({
@@ -172,6 +184,7 @@ class WsConn {
this.localApiKey,
this.observerShareId,
this.localProtocolVersion = 1,
+ this.fixedReconnectDelay,
this.relayCodecs,
this.transportPlugins,
});
@@ -692,6 +705,15 @@ class WsConn {
onStatus(ConnectionStatus.disconnected);
return;
}
+ if (code == 4403) {
+ // The daemon does not serve the machine id this socket selected ("machine mismatch",
+ // localWsServer.ts): it runs on another id now — a sign-out and sign-in gave the account a
+ // new machine, or a first start with no backend left it on the computer id. Retrying the
+ // same select every 30s used to be the whole response, silently and for good. Reported so
+ // the app can look up which id the daemon does serve; the retry stays, in case the answer
+ // is a re-key of this very row.
+ onLocalFailure?.call(code!, channel.closeReason ?? 'machine mismatch');
+ }
_scheduleReconnect();
return;
}
@@ -726,7 +748,9 @@ class WsConn {
onStatus(ConnectionStatus.reconnecting);
_reconnectTimer?.cancel();
final exponent = min(max(_attempt - 1, 0), 5);
- final delay = Duration(milliseconds: min(30000, 1000 * (1 << exponent)));
+ final delay =
+ fixedReconnectDelay ??
+ Duration(milliseconds: min(30000, 1000 * (1 << exponent)));
_reconnectTimer = Timer(delay, connect);
}
@@ -755,7 +779,13 @@ class WsConn {
await sub?.cancel();
final channel = _channel;
_channel = null;
- await channel?.sink.close();
+ // Bounded: a channel whose connect was refused (the daemon down, a 1s retry in flight) has a
+ // sink whose close never completes, and this used to wait on it for good — an app closing a
+ // machine while its daemon was down hung right here.
+ await channel?.sink.close().timeout(
+ const Duration(seconds: 2),
+ onTimeout: () => null,
+ );
onStatus(ConnectionStatus.disconnected);
}
diff --git a/desktop/lib/ws/ws_pool.dart b/desktop/lib/ws/ws_pool.dart
index e45bfde0f..30b97e695 100644
--- a/desktop/lib/ws/ws_pool.dart
+++ b/desktop/lib/ws/ws_pool.dart
@@ -45,9 +45,12 @@ class WsPool {
Uri? localWsUri,
String? localApiKey,
int localProtocolVersion = 1,
+ Duration? fixedReconnectDelay,
}) {
+ // The reconnect policy is part of the key: a row that turns out to be this computer's after its
+ // socket was made gets a new socket with the flat delay, not the old backoff.
final desiredKey = transportKind == WsTransportKind.localPlaintext
- ? 'local:${localWsUri.toString()}'
+ ? 'local:${localWsUri.toString()}:${fixedReconnectDelay?.inMilliseconds ?? 'backoff'}'
: 'cloud:$wsBaseUrl:$autonomousEnv';
final current = _conns[machineId];
if (current != null &&
@@ -77,6 +80,7 @@ class WsPool {
localWsUri: localWsUri,
localApiKey: localApiKey,
localProtocolVersion: localProtocolVersion,
+ fixedReconnectDelay: fixedReconnectDelay,
);
_conns[machineId] = conn;
unawaited(conn.connect());
diff --git a/desktop/test/daemon_readiness_test.dart b/desktop/test/daemon_readiness_test.dart
index 0fde6d276..5073cbe37 100644
--- a/desktop/test/daemon_readiness_test.dart
+++ b/desktop/test/daemon_readiness_test.dart
@@ -8,6 +8,7 @@ import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/swarm_catalog.dart';
import 'package:harness/ws/local_cli_discovery.dart';
+import 'package:harness/ws/ws_conn.dart';
/// A daemon that answers whatever the test says, with the supervisor's callbacks captured so the
/// test can fire "it became ready" itself.
@@ -59,6 +60,28 @@ class _SignedInCli extends CliLogin {
}
/// Stops at the machine list: this test is about the daemon gate, not what comes after it.
+/// A socket that answers nothing: the load a connect triggers must not reach for a real pool.
+class _QuietConnection extends WsConn {
+ _QuietConnection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm-local',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ @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 => const {'agents': []};
+}
+
class _Notifier extends AppNotifier {
int refreshes = 0;
_Notifier(LocalCliDiscovery discovery)
@@ -68,6 +91,7 @@ class _Notifier extends AppNotifier {
configStore: null,
localCliDiscovery: discovery,
cliLogin: _SignedInCli(),
+ connectionForTest: (_) => _QuietConnection(),
) {
// Already known, so the retry path does not go looking for it over the
// network — this test is about the daemon gate, not the profile.
@@ -199,6 +223,39 @@ void main() {
);
});
+ test(
+ 'the socket that just connected restores a cleared local endpoint',
+ () async {
+ // A refresh during the daemon's restart cleared this row's endpoint; the socket then came back
+ // on its own retry. `connected` is the proof the endpoint is good — put it back, or the tiles
+ // stay "Offline" and `_canAttachPane` refuses them for good.
+ final discovery = _ScriptedDiscovery([LocalCliProbe.ready(_endpoint)]);
+ final notifier = _Notifier(discovery)..status = AppStatus.authenticated;
+ addTearDown(notifier.dispose);
+ await notifier.ensureCliDaemonReady();
+
+ const row = Machine(
+ machineId: 'm-local',
+ computerId: '0123456789abcdef0123456789abcdef',
+ authMode: MachineAuthMode.remote,
+ status: 'online',
+ );
+ notifier.machines = [row];
+ final state = MachineState(row)
+ ..localOnly = true
+ ..localEndpoint = null
+ ..connectionStatus = ConnectionStatus.connected;
+ notifier.machineStates['m-local'] = state;
+ expect(state.usesLocalTransport, isFalse);
+
+ notifier.onMachineConnectedForTest('m-local');
+
+ expect(state.usesLocalTransport, isTrue);
+ expect(state.localEndpoint, same(_endpoint));
+ expect(state.transportMode, MachineTransportMode.localPlaintext);
+ },
+ );
+
test('a daemon nobody answers for is still "did not start"', () async {
final discovery = _ScriptedDiscovery([
const LocalCliProbe.down('connection refused'),
diff --git a/desktop/test/machine_list_outage_test.dart b/desktop/test/machine_list_outage_test.dart
index 5874dfb08..90f27e88f 100644
--- a/desktop/test/machine_list_outage_test.dart
+++ b/desktop/test/machine_list_outage_test.dart
@@ -56,18 +56,26 @@ class _Discovery extends LocalCliDiscovery {
/// What the daemon says about its own backend link. The real probe reads `/api/status.connected`.
bool backendOnline = true;
+ /// The machine id the daemon serves (`/api/status.machineId`).
+ String servedMachineId = 'local-machine';
+
+ /// The daemon is not answering the probe right now (restarting, or still scanning).
+ bool probeMisses = false;
+
@override
Future<String?> computerId() async => _computerId;
@override
Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>
- LocalCliEndpoint(
- computerId: _computerId,
- wsUri: Uri.parse('ws://127.0.0.1:18473/ws'),
- protocolVersion: localWsProtocolVersion,
- terminalProtocolVersion: 1,
- machineId: 'local-machine',
- backendOnline: backendOnline,
- );
+ probeMisses
+ ? null
+ : LocalCliEndpoint(
+ computerId: _computerId,
+ wsUri: Uri.parse('ws://127.0.0.1:18473/ws'),
+ protocolVersion: localWsProtocolVersion,
+ terminalProtocolVersion: 1,
+ machineId: servedMachineId,
+ backendOnline: backendOnline,
+ );
}
class _Connection extends WsConn {
@@ -284,6 +292,73 @@ void main() {
disposedEarly = true;
});
+ test('a daemon serving another machine id is adopted, and the stale row says why it is dark', () async {
+ // `harness logout` + `harness login` gave the account a new machine; the app still holds the
+ // old row and selects its id, which the daemon closes with 4403. That used to be a silent
+ // reconnect every 30s, forever. Now: the daemon is asked which id it serves, that machine is
+ // stood up so the person can work, and the old row's tiles are told.
+ app.discovery.backendOnline = false;
+ app.discovery.servedMachineId = 'new-machine';
+ final stale = app.machineStates['local-machine']!
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = true;
+
+ app.localFailureForTest('local-machine', 4403, 'machine mismatch');
+ await _tick();
+ await _tick();
+
+ final adopted = app.machineStates['new-machine'];
+ expect(adopted, isNotNull, reason: 'built from the id the daemon serves');
+ expect(adopted!.localOnly, isTrue);
+ expect(adopted.localEndpoint?.machineId, 'new-machine');
+ expect(adopted.transportMode, MachineTransportMode.localPlaintext);
+ expect(app.machines.map((m) => m.machineId), contains('new-machine'));
+ // Still there, so its tiles keep their context — but not retried as if it were merely offline.
+ expect(app.machineStates['local-machine'], same(stale));
+
+ // Reported once per stale id, not once per 30s retry.
+ app.localFailureForTest('local-machine', 4403, 'machine mismatch');
+ await _tick();
+ expect(
+ app.machineStates.keys.where((k) => k == 'new-machine'),
+ hasLength(1),
+ );
+
+ app.dispose();
+ disposedEarly = true;
+ });
+
+ test('a probe that misses while the socket is live does not take the local terminal dark', () async {
+ // The 15s refresh ran while the daemon was restarting: the list came from the cache, the
+ // probe found nothing. The socket to the daemon, meanwhile, was open and answering. The
+ // probe used to win — endpoint cleared, tiles "Offline", nothing to restore them since the
+ // socket never went down. Measured 2026-09-18 21:50.
+ final local = app.machineStates['local-machine']!
+ ..connectionStatus = ConnectionStatus.connected
+ ..nodeOnline = true;
+ final seed = app.refreshMachines();
+ await _tick();
+ api.lists.single.complete([_localMachine]);
+ await seed;
+ await _tick();
+ expect(local.localEndpoint, isNotNull);
+
+ app.discovery.probeMisses = true;
+ final refresh = app.refreshMachines();
+ await _tick();
+ api.lists.last.complete([_localMachine]);
+ await refresh;
+ await _tick();
+
+ expect(
+ local.usesLocalTransport,
+ isTrue,
+ reason: 'the live socket is the witness',
+ );
+ expect(local.transportMode, MachineTransportMode.localPlaintext);
+ expect(local.nodeOnline, isTrue);
+ });
+
test('a fresh answer ends the job', () async {
api.nextIsStale = false;
final retry = app.retryMachines();
diff --git a/desktop/test/ws_conn_test.dart b/desktop/test/ws_conn_test.dart
index d02f65852..fa541a27a 100644
--- a/desktop/test/ws_conn_test.dart
+++ b/desktop/test/ws_conn_test.dart
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'dart:io';
+import 'package:harness/core/models.dart' show ConnectionStatus;
import 'package:harness/ws/ws_conn.dart';
import 'package:harness/ws/ws_pool.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -300,6 +301,67 @@ void main() {
expect(conn!.isClosed, isTrue);
});
+ test(
+ 'a fixed reconnect delay retries at that pace instead of backing off',
+ () async {
+ // Nobody on the port: each attempt is refused at once. With the backoff the second attempt is
+ // 2s out and the third 4s; with a flat delay they come every tick — the policy the socket to
+ // this computer's own daemon uses, so a restarted daemon is found within a second.
+ final free = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ final port = free.port;
+ await free.close();
+ var reconnecting = 0;
+ conn = WsConn(
+ wsBaseUrl: 'wss://unused.example',
+ autonomousEnv: 'prod',
+ machineId: 'm1',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (status) {
+ if (status == ConnectionStatus.reconnecting) reconnecting++;
+ },
+ transportKind: WsTransportKind.localPlaintext,
+ localWsUri: Uri.parse('ws://127.0.0.1:$port/api/local-ws'),
+ fixedReconnectDelay: const Duration(milliseconds: 100),
+ );
+ await conn!.connect();
+ await Future<void>.delayed(const Duration(milliseconds: 650));
+ expect(
+ reconnecting,
+ greaterThanOrEqualTo(4),
+ reason: 'backoff would allow one',
+ );
+ },
+ );
+
+ test('4403 on a local socket is reported, and the retry goes on', () async {
+ // "machine mismatch": the daemon serves another id than the one selected. The app is told so it
+ // can find out which; the socket keeps retrying (the answer may be a re-key of this very row)
+ // instead of the silent 30s loop this used to be.
+ hub = await FakeHub.start(closeCodeOnSelect: 4403);
+ final failures = <String>[];
+ final statuses = <ConnectionStatus>[];
+ conn = WsConn(
+ wsBaseUrl: 'wss://unused.example',
+ autonomousEnv: 'prod',
+ machineId: 'm1',
+ accessTokenProvider: (_, _) async => 'sso-token',
+ onAuthFailure: (_) {},
+ onLocalFailure: (code, reason) => failures.add('$code:$reason'),
+ onEvent: (_) {},
+ onStatus: statuses.add,
+ transportKind: WsTransportKind.localPlaintext,
+ localWsUri: Uri.parse('ws://127.0.0.1:${hub.port}/api/local-ws'),
+ );
+ await conn!.connect();
+ await Future<void>.delayed(const Duration(milliseconds: 250));
+ expect(failures, hasLength(1));
+ expect(failures.single, startsWith('4403:'));
+ expect(statuses, contains(ConnectionStatus.reconnecting));
+ expect(conn!.isClosed, isFalse);
+ });
+
test(
'4401 refreshes once and reconnects with the new access token',
() async {
@@ -380,4 +442,45 @@ void main() {
await pool.closeAll();
},
);
+
+ test('WsPool reuses a local socket asked for with the same reconnect policy, and swaps it on a change', () async {
+ // The pool reuses a socket only when its own key and the socket's `endpointKey` agree. A key
+ // computed on one side and not the other churned EVERY socket on EVERY lookup — measured in
+ // the running app as `agents_list … failed: Bad state: WS closed` in a loop.
+ hub = await FakeHub.start();
+ final pool = WsPool(
+ wsBaseUrl: 'wss://unused.example',
+ autonomousEnv: 'prod',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_, _) {},
+ onStatus: (_, _) {},
+ );
+ final uri = Uri.parse('ws://127.0.0.1:${hub.port}/api/local-ws');
+ final flat = pool.connFor(
+ 'm1',
+ transportKind: WsTransportKind.localPlaintext,
+ localWsUri: uri,
+ fixedReconnectDelay: const Duration(seconds: 1),
+ );
+ final again = pool.connFor(
+ 'm1',
+ transportKind: WsTransportKind.localPlaintext,
+ localWsUri: uri,
+ fixedReconnectDelay: const Duration(seconds: 1),
+ );
+ expect(identical(flat, again), isTrue, reason: 'same policy, same socket');
+ final backoff = pool.connFor(
+ 'm1',
+ transportKind: WsTransportKind.localPlaintext,
+ localWsUri: uri,
+ );
+ expect(
+ identical(flat, backoff),
+ isFalse,
+ reason: 'a new policy is a new socket',
+ );
+ expect(flat.isClosed, isTrue);
+ await pool.closeAll();
+ });
}