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.

54.9 KB
Raw Blame
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

import '../core/app_version.dart';
import '../core/sleep_aware.dart';
import '../core/test_run.dart';
import '../logging/app_log.dart';
import '../logging/redact.dart';
import '../core/models.dart';
import 'local_daemon_transport.dart';
import 'relay_codec.dart';
import 'terminal_transport_plugin.dart';
import 'trusted_pipe.dart';
import 'windows_pipe.dart';

typedef AccessTokenProvider = Future<String> Function(
  bool forceRefresh,
  String? failedToken,
);

enum WsTransportKind { cloudE2ee, localPlaintext }

/// Opens a backend socket ([WsConn.cloudSocket]).
typedef CloudSocketFactory = WebSocketChannel Function(
  Uri uri,
  Iterable<String>? protocols,
);

/// How long [WsConn] waits before its [attempt]th reconnect: a window that doubles from 1 s to a
/// 30 s ceiling, the wait somewhere in its second half. The jitter spreads the tabs a backend
/// restart dropped together; the half that is not random is what keeps a socket that fails at once
/// to a handful of dials a minute, which no draw can undercut.
Duration reconnectDelay(int attempt, Random random) {
  final exponent = min(max(attempt - 1, 0), 5);
  final window = min(30000, 1000 * (1 << exponent));
  return Duration(
    milliseconds: window ~/ 2 + (random.nextDouble() * (window / 2)).round(),
  );
}

/// How many times a Desktop connection that has never been up retries quickly while it opens
/// ([firstConnectRetryDelay]). It says connecting through them: nothing has been lost yet, and
/// `reconnecting` is what marks a machine offline. Few, because each can cost the daemon a backend
/// dial, and only once per connection: the socket that fails at once for good goes on to the backoff.
const firstConnectRetries = 3;

/// The wait before the [attempt]th retry of a first connect, of [firstConnectRetries]. Opening used
/// to spend these tries on the backoff's 0.5 to 7 s, on top of the 1 and 2 s the daemon itself holds a
/// failed machine for (a retry inside that hold is answered from its memory, without a dial).
Duration firstConnectRetryDelay(int attempt) => attempt <= 1
    ? const Duration(milliseconds: 500)
    : const Duration(seconds: 1);

/// How long a Desktop connection that has never been up goes on saying connecting, past its quick
/// tries. `reconnecting` marks a machine offline, and a daemon just started has its backend some
/// seconds later (6 s on 10-30): those seconds are not a computer that is off. As long as the
/// daemon's own wait for one dial. A relay that says the machine is off is believed at once ([_park]).
const firstConnectWindow = Duration(seconds: 15);

/// How long a connection has to stay up before its next drop starts the backoff over. Resetting it
/// the moment a socket was up made a socket the backend dropped right after its handshake redial
/// every second, for good: about 54 dials a minute from one browser tab (prod, 2026-10-28).
const connectionStableAfter = Duration(minutes: 1);

/// This build's version, which every backend socket it dials says (`?v=`), read once at start-up
/// ([rememberAppVersionForSockets]). Null until then, and a socket dialled before says no version.
String? declaredAppVersion;

/// The read behind [declaredAppVersion] while it is out; null natively before start-up and in tests.
Future<void>? appVersionRead;

/// Reads this build's version for [declaredAppVersion]; a build that cannot say leaves it null.
Future<void> rememberAppVersionForSockets() {
  final read = () async {
    try {
      declaredAppVersion = await runningAppVersion();
    } catch (_) {
      // Sockets go on saying what they are, without a version.
    }
  }();
  appVersionRead = read;
  return read;
}

/// How long a backend dial waits for [appVersionRead]: the browser reads its version from the
/// host's release file, and a socket dialled before that read lands would carry none.
const _appVersionWait = Duration(seconds: 1);

/// The backend's refusals of a `machine_select` that no redial can change: the machine left the
/// account or was never shared with it, it belongs to another environment, or its subscription stops
/// it (`backend/src/lib/webWs.ts`). Through this computer's daemon they arrive as the relay's close,
/// with the code for its reason (`cli/src/localWsServer.ts`). Prod, 2026-10-28: a laptop removed in
/// September was still selected every few seconds.
const finalSelectRefusals = {
  'NOT_YOUR_MACHINE',
  'MACHINE_ENV_MISMATCH',
  'MACHINE_PAYMENT_PENDING',
  'MACHINE_SUBSCRIPTION_REQUIRED',
};

/// A `request()` call got no reply within its timeout — distinct from other request-level errors
/// (an explicit `{error: ...}` response) so callers can tell "the peer is unresponsive" apart from
/// "the peer answered with a failure."
class WsRequestTimeout implements Exception {
  final String type;
  const WsRequestTimeout(this.type);
  @override
  String toString() => 'WS request timed out: $type';
}

/// The peer ANSWERED a `request()` with an explicit `{error: ...}` — a refusal it meant, as opposed
/// to [WsRequestTimeout]'s silence.
///
/// The code travels as a field rather than only inside the message because that is what callers act
/// on: `AGENT_BUSY` becomes "move it when the turn finishes", `UNSUPPORTED` becomes "update the CLI
/// on this machine". Before this existed every refusal arrived as a bare `Exception` whose only
/// content was its own `toString()`, so the mapping in `AppNotifier` sat behind an `if` on a reply
/// that had already thrown and could never run — the user got the wire code.
///
/// [toString] is the sentence this used to be thrown with, so a call site that only prints it is
/// unchanged.
class WsRequestFailure implements Exception {
  const WsRequestFailure({
    required this.responseType,
    required this.code,
    this.detail,
    this.payload = const {},
  });

  /// The frame that carried the refusal — `agent_create_result`, say.
  final String responseType;

  /// The peer's own error code.
  final String code;

  /// The underlying cause behind the code, when the peer sends one — the tmux message behind
  /// SPAWN_FAILED. Already reads as a sentence; prefer it to anything rewritten from [code].
  final String? detail;

  /// Additional reply fields needed to handle a refusal, such as the activity
  /// that made an idle Close unsafe. These must survive the error boundary.
  final Map<String, dynamic> payload;

  @override
  String toString() => detail == null || detail!.isEmpty
      ? '$responseType: $code'
      : '$responseType: $code — $detail';
}

/// One SSO-authenticated, machine-scoped connection to `/api/web-ws`.
class WsConn {
  /// Above this a frame decodes in an isolate. Starting one holds this thread about 3 ms itself, the time of a decode of about
  /// this size on a current Mac (566 KB took 7 ms, measured for #2195), so below it the isolate would cost more than it saves.
  static const largeFrameChars = 256 * 1024;

  /// How a large frame decodes; tests hold it to see the order.
  @visibleForTesting
  static Future<Object?> Function(String raw) decodeLargeFrame =
      decodeInIsolate;

  /// The decoded frame, or null for what will not parse. `compute` hands the result back without a copy, and runs inline on the web.
  static Future<Object?> decodeInIsolate(String raw) =>
      compute(_decodeOrNull, raw);

  static Object? _decodeOrNull(String raw) {
    try {
      return jsonDecode(raw);
    } catch (_) {
      return null;
    }
  }

  final String wsBaseUrl;
  final String autonomousEnv;
  final String machineId;
  final AccessTokenProvider accessTokenProvider;
  final void Function(String message) onAuthFailure;

  /// The local CLI closed this connection with a specific, non-retryable reason (currently just
  /// `NO_PEER_LINK`: the target machine has no `harness link import`ed trust yet) — surfaced instead
  /// of silently reconnecting forever against a failure the user has to act on to fix.
  final void Function(int code, String reason)? onLocalFailure;
  final WsTransportKind transportKind;
  final Uri? localWsUri;

  /// How the local daemon is reached (see [LocalDaemonTransport]). When it
  /// names a socket, a local connection dials [localWsUri]'s path over it and
  /// falls back to the port. Windows uses only the authenticated pipe.
  final LocalDaemonTransport? localTransport;

  /// A loopback WebSocket fixture has no daemon pipe. This opt-in works only
  /// under flutter test; installed Windows builds always require the pipe.
  @visibleForTesting
  final bool allowLocalTcpFixture;

  /// Retained only for fixture constructor compatibility. Local transport ignores it.
  final String? localApiKey;
  final String? observerShareId;
  final bool observerLink;
  bool get _directObserver => !isLocal && observerShareId != null;
  final int localProtocolVersion;

  /// An auxiliary local client must not count as an active desktop window.
  final bool localToolClient;

  /// This computer's own window connection: the one the daemon takes its
  /// `daemon_*` frames on, and only over its own socket. On Windows that is
  /// its pipe ([LocalDaemonTransport.trustedPipe]), so this connection dials
  /// the pipe first. Elsewhere it changes nothing.
  final bool trustedLocal;

  /// 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.
  final RelayCodecFactory? relayCodecs;

  /// A second wire beside the relay socket (a viewer's WebRTC data channel to the
  /// machine), built per connect once the codec exists. Null — the desktop, the
  /// local transport, the dev fixture — means every frame rides the socket.
  final TerminalTransportPluginFactory? transportPlugins;

  /// Opens the backend socket. Null dials a real one; tests pass a fake.
  @visibleForTesting
  final CloudSocketFactory? cloudSocket;

  /// [firstConnectWindow]; a test's own.
  final Duration firstConnectFor;

  /// The reconnect jitter's source. Null is a fresh [Random].
  final Random _random;

  Future<Map<String, dynamic>> Function(
    String type,
    Map<String, dynamic> payload,
  )?
  onOutgoing;
  Future<Map<String, dynamic>?> Function(Map<String, dynamic> frame)?
  onE2eeFrame;
  Future<void> Function(Uint8List frame)? onBinaryFrame;

  final FutureOr<void> Function(Map<String, dynamic> event) onEvent;
  final void Function(ConnectionStatus status) onStatus;

  WebSocketChannel? _channel;
  RelayCodec? _codec;
  TerminalTransportPlugin? _plugin;
  StreamSubscription? _sub;
  bool _closing = false;
  bool _connecting = false;
  bool _ready = false;
  int _attempt = 0;

  /// Has been up at least once. Until then, a Desktop connection is still on its first connect.
  bool _everReady = false;

  /// From the first dial to the first time up, for the log: what opening the app waited for.
  Stopwatch? _firstConnect;
  Timer? _reconnectTimer;
  Timer? _stableTimer;
  Timer? _observerHandshakeTimer;
  String? _tokenUsed;

  /// The token a 4401 refresh just handed over, until a connection is up on it. The backend
  /// refusing that one too means the sign-in itself is gone; refreshing again only loops.
  String? _refreshedToken;
  bool _forceRelayReconnect = false;
  final _pending = <String, _PendingRpc>{};
  final _readinessWaiters = <Completer<void>>{};
  final _queue = <Map<String, dynamic>>[];
  Future<void> _outboundTail = Future<void>.value();
  Future<void> _inboundTail = Future<void>.value();

  bool get isReady => _ready && _channel != null;

  /// Waiting for its machine, which the daemon's relay said is off ([_park]).
  bool get isParked => _parked;
  bool _parked = false;

  /// The rechecks dialled in a row on their own, each parked again: what doubles the next wait.
  int _parkedRechecks = 0;
  static const _recheck = 'recheck';

  /// The wait before a parked connection dials again on its own after [rechecks] of them in a
  /// row: 30 s, then a minute, 2, 4, 8, and 15 at most. Anything that says the machine is back
  /// [wake]s it. The first is the relay's own retry-after for an offline machine (backend
  /// `OFFLINE_RETRY_AFTER_MS`): a wake that reaches the daemon while it still answers from that
  /// refusal parks again, and a machine back online must not then wait a minute more.
  static Duration parkedRecheckAfter(int rechecks) {
    final wait = const Duration(seconds: 30) * (1 << min(max(rechecks, 0), 5));
    return wait > const Duration(minutes: 15)
        ? const Duration(minutes: 15)
        : wait;
  }

  /// The daemon's relay refused this machine as off (`MACHINE_OFFLINE`): wait for it.
  ///
  /// ⚠️ **Why (prod, 2026-10-28).** Daemon relays made 2,304 of 2,308 backend socket opens in 15
  /// minutes, living a median 0.4 s. A relayed machine that was off was redialled on the 15–30 s
  /// backoff for as long as the app ran, and each dial cost the daemon a backend socket refused at
  /// once: about 2.7 a minute for every machine that was off, in every window.
  void _park() {
    _parked = true;
    _reconnectTimer?.cancel();
    final wait = parkedRecheckAfter(_parkedRechecks);
    _reconnectTimer = Timer(wait, () => wake(_recheck));
    onStatus(ConnectionStatus.reconnecting);
    appLog.info(
      'ws',
      'parked $machineId · the relay says it is off; recheck in ${wait.inSeconds}s',
    );
  }

  /// Dial a parked connection now: the machine is reported back, or somebody asks for it. Its own
  /// recheck makes the next wait longer; anything else starts the waits over.
  void wake(String reason) {
    if (!_parked || _closing) return;
    _parked = false;
    _parkedRechecks = reason == _recheck ? _parkedRechecks + 1 : 0;
    _reconnectTimer?.cancel();
    _reconnectTimer = null;
    _attempt = 0;
    unawaited(connect());
  }

  /// Wait for this machine's handshake without queuing a request or changing
  /// its timeout. Callers can then start independent RPCs with their own budgets.
  Future<void> waitUntilReady({required Duration timeout}) {
    if (isReady) return Future<void>.value();
    if (_closing) return Future<void>.error(StateError('WS closed'));
    final ready = Completer<void>();
    _readinessWaiters.add(ready);
    // Awake time: a wait begun before the lid closed must not expire on the wake (see sleep_aware).
    return awakeTimeout<void>(
      ready.future,
      timeout,
      onTimeout: () => throw const WsRequestTimeout('machine_select'),
    ).whenComplete(() => _readinessWaiters.remove(ready));
  }

  void _settleReadiness([String? failure]) {
    final waiters = _readinessWaiters.toList();
    _readinessWaiters.clear();
    for (final waiter in waiters) {
      if (failure == null) {
        waiter.complete();
      } else {
        waiter.completeError(StateError(failure));
      }
    }
  }

  /// 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;
  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()}:${fixedReconnectDelay?.inMilliseconds ?? 'backoff'}${trustedLocal ? ':trusted' : ''}'
      : 'cloud:$wsBaseUrl:$autonomousEnv';

  bool _overPipe = false;

  /// Whether the last connection attempt could not establish the private
  /// pipe. The normal reconnect loop asks for the current pipe again.
  bool get trustedPipeMissing =>
      trustedLocal &&
      (localTransport?.trustedPipe?.unavailable ?? false) &&
      !_overPipe;

  WsConn({
    required this.wsBaseUrl,
    required this.autonomousEnv,
    required this.machineId,
    required this.accessTokenProvider,
    required this.onAuthFailure,
    this.onLocalFailure,
    required this.onEvent,
    required this.onStatus,
    this.transportKind = WsTransportKind.cloudE2ee,
    this.localWsUri,
    this.localTransport,
    this.allowLocalTcpFixture = false,
    this.localApiKey,
    this.observerShareId,
    this.observerLink = false,
    this.localProtocolVersion = 1,
    this.localToolClient = false,
    this.trustedLocal = false,
    this.fixedReconnectDelay,
    this.relayCodecs,
    this.transportPlugins,
    this.cloudSocket,
    Random? random,
    @visibleForTesting this.firstConnectFor = firstConnectWindow,
  }) : _random = random ?? Random();

  /// The socket to dial, decided afresh on every connect: whether the file is
  /// there now, not whether it was the last time something looked. A dial
  /// that failed while the daemon restarted must not keep this connection on
  /// the port for good once the daemon is back with its socket.
  String? _localSocket() {
    final transport = localTransport;
    if (transport == null) return null;
    if (transport.socketPresent) return transport.candidate;
    transport.useTcp();
    return null;
  }

  /// The local WebSocket over the daemon's Unix socket, or null when that
  /// failed and the loopback port should be used instead. A socket that could
  /// not be reached at all sends everything back to the port until discovery
  /// finds it again.
  Future<WebSocketChannel?> _connectLocalSocket(Uri uri, String socket) async {
    final pending = WebSocket.connect(
      Uri(scheme: 'ws', host: 'localhost', path: uri.path).toString(),
      customClient: unixHttpClient(socket),
    );
    try {
      return IOWebSocketChannel(
        await pending.timeout(const Duration(seconds: 5)),
      );
    } on TimeoutException {
      // The dial goes on after the timeout; a socket it opens late is nobody's.
      unawaited(pending.then((ws) => ws.close(), onError: (_) {}));
      return null;
    } catch (error) {
      if (isConnectionFailure(error)) localTransport?.useTcp();
      return null;
    }
  }

  /// The daemon's Windows pipe, or null when it is missing or unproven. The
  /// pipe is looked up afresh on every reconnect, including after a restart.
  Future<WebSocketChannel?> _connectTrustedPipe(
    Uri uri,
    TrustedPipe pipe,
  ) async {
    try {
      return IOWebSocketChannel(await pipe.webSocket(uri.path));
    } on PipeFailure {
      return null;
    }
  }

  /// The local WebSocket over the daemon's loopback port, showing its local
  /// credential: the port takes any OS user's process, the socket only ours.
  WebSocketChannel _connectLocalPort(Uri uri) {
    if (Platform.isWindows && !(kUnderTest && allowLocalTcpFixture)) {
      throw StateError('The local daemon pipe is unavailable');
    }
    final transport = localTransport ?? LocalDaemonTransport.detect(uri);
    if (!transport.portAllowed) {
      throw StateError('The local daemon socket is unavailable');
    }
    return IOWebSocketChannel.connect(uri, headers: transport.tcpHeaders());
  }

  Future<void> connect() async {
    if (_closing || _connecting) return;
    // A dial asked for while parked (a forced redial) is the recheck's too.
    if (_parked) {
      _parked = false;
      _reconnectTimer?.cancel();
      _reconnectTimer = null;
    }
    _connecting = true;
    _ready = false;
    _firstConnect ??= Stopwatch()..start();
    onStatus(
      _attempt == 0 || _saysConnecting
          ? ConnectionStatus.connecting
          : ConnectionStatus.reconnecting,
    );
    try {
      final token = isLocal ? null : await accessTokenProvider(false, null);
      if (!isLocal &&
          !(_directObserver && observerLink) &&
          (token == null || token.isEmpty)) {
        throw StateError('WebSocket credential is missing');
      }
      if (_closing) return;
      _tokenUsed = token;
      final codecs = isLocal ? null : relayCodecs;
      if (_directObserver && codecs == null) {
        _refusePeer('Shared harnesses require a verified owner identity.');
        return;
      }
      if (codecs != null) {
        final codec = await codecs(machineId);
        if (_closing) return;
        if (codec == null) {
          _refusePeer(
            _directObserver
                ? 'This invitation has no owner identity. Ask the owner to share it again.'
                : 'NO_PEER_LINK',
          );
          return;
        }
        _codec = codec;
        // A dial that failed past this point left one behind; this connect owns a new one.
        _disposePlugin();
        final plugins = transportPlugins;
        if (plugins != null) _plugin = plugins(_PluginHost(this), machineId);
      }
      final Uri uri;
      if (isLocal) {
        final local = localWsUri;
        if (local == null ||
            (local.host != '127.0.0.1' && local.host != 'localhost')) {
          throw StateError('Local WebSocket must use loopback');
        }
        uri = local;
      } else {
        final versionRead = appVersionRead;
        if (versionRead != null && declaredAppVersion == null) {
          await versionRead.timeout(
            _appVersionWait,
            // Waited out once: a read that never ends must not hold every later dial too.
            onTimeout: () {
              if (identical(appVersionRead, versionRead)) appVersionRead = null;
            },
          );
          if (_closing) return;
        }
        final base = Uri.parse(
          '$wsBaseUrl/api/${_directObserver ? 'observer-ws' : 'web-ws'}',
        );
        uri = base.replace(
          queryParameters: {
            ...base.queryParameters,
            'autonomousEnv': autonomousEnv,
            if (_directObserver)
              (observerLink ? 'link' : 'share'): observerShareId!,
            // The browser counts its person as on the web today (backend
            // user_daily_client_presence). Other viewer builds say they are the desktop app,
            // which counts no presence. Both say which build (WebSocket roadmap Phase 0).
            'client': kIsWeb ? 'web' : 'desktop',
            'v': ?declaredAppVersion,
          },
        );
      }
      final pipe = isLocal ? localTransport?.trustedPipe : null;
      final overPipe = pipe == null
          ? null
          : await _connectTrustedPipe(uri, pipe);
      if (pipe != null && overPipe == null) {
        throw StateError('The local daemon pipe is unavailable');
      }
      final socket = isLocal && overPipe == null ? _localSocket() : null;
      final channel =
          overPipe ??
          (!isLocal
              ? (cloudSocket ?? _connectCloud)(
                  uri,
                  token == null || token.isEmpty ? null : [token],
                )
              : socket != null
              ? await _connectLocalSocket(uri, socket) ?? _connectLocalPort(uri)
              : _connectLocalPort(uri));
      _overPipe = overPipe != null;
      if (_closing) {
        await channel.sink.close();
        return;
      }
      _channel = channel;
      if (_directObserver) {
        _observerHandshakeTimer?.cancel();
        _observerHandshakeTimer = Timer(const Duration(seconds: 15), () {
          if (!_closing && !_ready && identical(_channel, channel)) {
            unawaited(channel.sink.close());
            _onDone(channel);
          }
        });
      }
      if (_directObserver) {
        await channel.ready.timeout(const Duration(seconds: 15));
      } else {
        await channel.ready;
      }
      if (_closing || !identical(_channel, channel)) {
        await channel.sink.close();
        return;
      }
      _sub = channel.stream.listen(
        _onRaw,
        onDone: () => _onDone(channel),
        onError: (_) => _onDone(channel),
      );
      final forceRelayReconnect = _forceRelayReconnect;
      _forceRelayReconnect = false;
      if (!_directObserver) {
        await sendFrame({
          'type': 'machine_select',
          'payload': {
            'machineId': machineId,
            if (observerShareId != null) 'shareId': observerShareId,
            if (isLocal) 'localProtocolVersion': localProtocolVersion,
            if (isLocal && localToolClient) 'tool': true,
            if (isLocal && forceRelayReconnect) 'forceReconnect': true,
          },
        });
      }
    } catch (_) {
      _observerHandshakeTimer?.cancel();
      if (!_closing) _scheduleReconnect();
    } finally {
      _connecting = false;
    }
  }

  /// Frames behind a large one wait for it, whatever their kind, so nothing overtakes it.
  Future<void> _decodeTail = Future<void>.value();
  int _decoding = 0;

  void _onRaw(dynamic raw) {
    // A frame belongs to the connection it came on, sealed or not, whenever its turn comes: once
    // that connection has gone, it reaches nothing, and its seal is never read afresh.
    final channel = _channel, codec = _codec;
    if (_decoding == 0 && !(raw is String && raw.length >= largeFrameChars)) {
      _handleRaw(raw, codec);
      return;
    }
    _decoding++;
    _decodeTail = _decodeTail
        .then((_) async {
          bool gone() => _closing || !identical(_channel, channel);
          if (gone()) return;
          if (raw is String && raw.length >= largeFrameChars) {
            Object? decoded;
            try {
              decoded = await decodeLargeFrame(raw);
            } catch (_) {
              // No isolate to be had: as it always was, on this thread.
              decoded = _decodeOrNull(raw);
            }
            if (gone()) return;
            if (decoded is Map<String, dynamic>) _handleMessage(decoded, codec);
          } else {
            _handleRaw(raw, codec);
          }
        })
        .catchError((Object _) {
          // Keep the queue alive: one frame that fails is dropped, as a bad frame always was.
        })
        .whenComplete(() => _decoding--);
  }

  void _handleRaw(dynamic raw, RelayCodec? codec) {
    if (raw is List<int>) {
      final bytes = Uint8List.fromList(raw);
      _inboundTail = _inboundTail
          .then((_) async {
            final local = codec == null ? bytes : codec.decodeBinary(bytes);
            if (local == null) return;
            await _plugin?.observeWsBinary(local);
            await onBinaryFrame?.call(local);
          })
          .catchError((_) {
            // Binary E2EE/session code owns recovery for bad frames.
          });
      return;
    }
    final Map<String, dynamic> message;
    try {
      message = jsonDecode(raw as String) as Map<String, dynamic>;
    } catch (_) {
      return;
    }
    _handleMessage(message, codec);
  }

  void _handleMessage(Map<String, dynamic> message, RelayCodec? codec) {
    if (message['type'] == 'machine_select_error') _selectRefused(message);
    if (codec != null) {
      _inboundTail = _inboundTail
          .then((_) => _onRelayFrame(codec, message))
          .catchError((_) {
            // Keep the FIFO alive: a frame that will not open is dropped, never dispatched.
          });
      return;
    }
    final type = message['type'] as String? ?? '';
    final payload = (message['payload'] as Map<String, dynamic>?) ?? {};

    if (type == 'connected') {
      if (payload['machineId'] == machineId) _markReady();
      return;
    }
    final normalized = <String, dynamic>{...message, 'payload': payload};
    _inboundTail = _inboundTail
        .then((_) async {
          final isE2ee =
              type.startsWith('e2e_') ||
              (payload.containsKey('__e2e') && payload['__e2e'] is Map);
          if (isE2ee && onE2eeFrame != null) {
            await _handleE2ee(normalized);
          } else {
            await _dispatch(normalized);
          }
        })
        .catchError((_) {
          // Keep the FIFO alive. E2EE/session code owns recovery for bad frames.
        });
  }

  void _markReady() {
    _observerHandshakeTimer?.cancel();
    _parkedRechecks = 0;
    _ready = true;
    if (!_everReady) {
      _everReady = true;
      // The short id and the times only: what a person's opening really took, on their own Mac.
      appLog.debug(
        'ws',
        'first connect ${machineId.length > 8 ? machineId.substring(0, 8) : machineId} '
            'in ${_firstConnect?.elapsedMilliseconds ?? 0} ms, $_attempt retries',
      );
    }
    _refreshedToken = null;
    _stableTimer?.cancel();
    _stableTimer = Timer(connectionStableAfter, () => _attempt = 0);
    onStatus(ConnectionStatus.connected);
    _flushQueue();
    _settleReadiness();
  }

  /// A frame on a relay connection whose E2EE session this app holds: relayClient.ts's dial
  /// handshake, then open-and-dispatch. Nothing is ready — and nothing queued goes out — until the
  /// machine's welcome proves it holds the identity this device pinned for it.
  Future<void> _onRelayFrame(
    RelayCodec codec,
    Map<String, dynamic> message,
  ) async {
    if (_closing || !identical(_codec, codec)) return;
    final payload = (message['payload'] as Map<String, dynamic>?) ?? {};
    switch (message['type']) {
      case 'observer_connected':
        if (_directObserver) _channel?.sink.add(jsonEncode(codec.helloFrame()));
        return;
      case 'observer_welcome':
        if (!_directObserver) return;
        final verified = await codec.handleWelcome(payload);
        if (_closing || !identical(_codec, codec)) return;
        if (verified) {
          _markReady();
        } else {
          _refusePeer('The shared harness identity could not be verified.');
        }
        return;
      case 'observer_closed':
        if (!_directObserver) return;
        if (payload['retry'] == true) {
          unawaited(_channel?.sink.close());
        } else {
          _refusePeer(payload['reason'] as String? ?? 'Sharing ended.');
        }
        return;
      case 'connected':
        if (_directObserver) return;
        // The socket's first `connected` answers the socket itself (it names the user, not a
        // machine); only the select's own ack starts the handshake.
        if (payload['machineId'] == machineId) {
          // The policy rides the ack; the plugin must have it before the welcome
          // that decides whether to act on it.
          _plugin?.onConnectedAck(payload);
          _channel?.sink.add(jsonEncode(codec.helloFrame()));
        }
        return;
      case 'e2e_welcome':
        if (_directObserver) return;
        // One per session (see `RelaySessionCrypto.handleWelcome`): another once this one is up
        // is the relay repeating itself — not the machine failing to prove who it is, which is
        // what refusing the peer below would take it for.
        if (_ready) return;
        final verified = await codec.handleWelcome(payload);
        if (_closing || !identical(_codec, codec)) return;
        if (verified) {
          _markReady();
          _plugin?.onSessionReady();
        } else {
          _refusePeer('E2EE_WELCOME_INVALID');
        }
        return;
      case 'e2e_denied':
        _refusePeer('E2E_DENIED');
        return;
      case 'e2e_rekey':
        codec.handleRekey(payload);
        return;
    }
    final clear = codec.decodeFrame(message);
    if (clear == null) {
      if (_directObserver && message['type'] == 'observer_frame') {
        _refusePeer('Shared harness verification failed.');
      }
      return;
    }
    if (_directObserver && clear['type'] == 'observer_binary') {
      final bytes = (clear['payload'] as Map?)?['bytes'];
      if (bytes is String) await onBinaryFrame?.call(base64Decode(bytes));
      return;
    }
    final plain = <String, dynamic>{
      ...clear,
      'payload': (clear['payload'] as Map<String, dynamic>?) ?? {},
    };
    final plugin = _plugin;
    final type = plain['type'];
    if (plugin != null && type is String && plugin.consumesInbound(type)) {
      await plugin.handleInbound(
        type,
        plain['payload'] as Map<String, dynamic>,
      );
      return;
    }
    await _dispatch(plain);
    // After, not before: for `terminal_ready` the session learns its streamId from
    // the frame itself, and anything the plugin derives from it (its own
    // `terminal_link_mode`) must land once that has happened.
    await _plugin?.observeWsFrame(plain);
  }

  /// The machine is reachable but this device may not talk to it: never linked, the link revoked
  /// on its side, or a welcome that did not prove the pinned identity. No retry can fix any of the
  /// three — only a link can — so this stops and says so the way the CLI's own relay does, with
  /// 4404.
  void _refusePeer(String reason) {
    appLog.info(
      'ws',
      'refused ${machineId.length > 8 ? machineId.substring(0, 8) : machineId}: $reason',
    );
    _closing = true;
    _ready = false;
    _observerHandshakeTimer?.cancel();
    _rejectPending(reason);
    _disposePlugin();
    // needsLink first: AppNotifier's onStatus handler reads machine.needsLink to decide whether a
    // disconnect should be treated as the node going offline — it has to see it flipped before
    // onStatus runs, or the very first 4404 for this machine reads as offline for one retry cycle.
    onLocalFailure?.call(4404, reason);
    onStatus(ConnectionStatus.disconnected);
    unawaited(_channel?.sink.close());
  }

  Future<void> _dispatch(Map<String, dynamic> message) async {
    final payload = (message['payload'] as Map<String, dynamic>?) ?? {};
    final requestId = payload['requestId'];
    if (requestId is String && _pending.containsKey(requestId)) {
      final pending = _pending.remove(requestId)!;
      pending.timer.cancel();
      if (payload['error'] != null) {
        // `detail`, when the peer sends one, is the underlying cause behind the code — the tmux
        // message behind SPAWN_FAILED, say. Without it an error code alone sends the user to a log file
        // on a machine that is not the one in front of them.
        final detail = payload['detail'];
        pending.completer.completeError(
          WsRequestFailure(
            responseType: message['type'] as String? ?? 'unknown_result',
            code: '${payload['error']}',
            detail: detail is String && detail.isNotEmpty ? detail : null,
            payload: Map.unmodifiable(payload),
          ),
        );
      } else {
        pending.completer.complete(payload);
      }
      return;
    }
    final eventType = message['type'];
    if (eventType is String && _worthLogging(eventType)) {
      appLog.debug('ws', '↓ $eventType ${summariseForLog(payload)}');
    }
    await onEvent({...message, 'payload': payload});
  }

  Future<void> _handleE2ee(Map<String, dynamic> frame) async {
    final decrypted = await onE2eeFrame!(frame);
    if (decrypted != null) await _dispatch(decrypted);
  }

  /// Frame types deliberately kept OUT of the log.
  ///
  /// Terminal traffic is the overwhelming majority of what crosses this socket
  /// and none of it is diagnostic — it is somebody's screen. Logging it would
  /// bury every frame that matters, cost an fsync per keystroke, and write the
  /// contents of their editor to disk. The hardware dial's events are dropped
  /// for the volume alone.
  static const _unlogged = {
    // File paths and media contents are user data, not frame diagnostics.
    'agent_read_file',
    'agent_read_file_result',
    // Conversation-derived: file names and the project folder.
    'agent_handoff_prepare',
    'agent_handoff_prepare_result',
    'agent_handoff_complete',
    'agent_handoff_complete_result',
    'project_preview',
    'project_preview_result',
    // A name made from the panes' titles, asked again every few seconds
    // while the daemon is still writing it.
    'window_name',
    'window_name_result',
    'git_project_info',
    'git_project_info_result',
    'git_pull_requests_status',
    'git_pull_requests_status_result',
    'terminal_output',
    'terminal_input',
    'terminal_resize',
    'terminal_sync',
    'dial_scroll',
    'dial_focus',
    'dial_selection',
    'app_selection_result',
    'dial_visit',
    'app_visit_result',
    'dial_form',
    'app_form_result',
    'ping',
    'pong',
  };

  static bool _worthLogging(String type) =>
      !_unlogged.contains(type) &&
      !type.startsWith('phone_pair') &&
      !type.startsWith('viewer_surface') &&
      !type.startsWith('api_connections') &&
      !type.startsWith('connectors') &&
      !type.startsWith('orchestrator') &&
      !type.startsWith('super_tabs') &&
      !type.startsWith('route_') &&
      !type.startsWith('harness_share_') &&
      // Pair responses can contain retained memory quotations and one-use
      // owner capabilities. Never copy them into a second log retention path.
      type != 'pair' &&
      type != 'pair_result' &&
      !type.startsWith('observer_');

  /// Refusals that are the daemon working as designed, logged at DEBUG: Agent
  /// Messages off (the account default) and an action an older CLI does not
  /// know. At WARN each was an immediate, fsync'd write to the app log on the
  /// UI isolate — once a minute for `shares` alone, for every account that
  /// never turned Agent Messages on — while saying nothing anyone acts on.
  static const _expectedRefusals = {
    'MESSAGES_OFF',
    'UNKNOWN_ACTION',
    // A computer shared with this account answers some actions this way by design, not a fault.
    'GUEST_NOT_ALLOWED',
  };

  static bool _expectedRefusal(Object error) =>
      error is WsRequestFailure && _expectedRefusals.contains(error.code);

  Future<Map<String, dynamic>> request(
    String type, {
    Map<String, dynamic> payload = const {},
    Duration timeout = const Duration(seconds: 20),
  }) {
    final requestId = _newRequestId();
    final completer = Completer<Map<String, dynamic>>();
    // Awake time, not wall time: a request asked just before the lid closed used to "time out" on the
    // first turn after it opened, its answer a second behind — and a timed-out inventory is what
    // marks a machine offline (measured 2026-09-29 19:06:11).
    final timer = SleepAwareTimer(timeout, () {
      _pending.remove(requestId);
      _queue.removeWhere(
        (f) =>
            (f['payload'] as Map<String, dynamic>?)?['requestId'] == requestId,
      );
      if (!completer.isCompleted) {
        completer.completeError(WsRequestTimeout(type));
      }
    });
    _pending[requestId] = _PendingRpc(completer, timer);
    if (_worthLogging(type)) {
      appLog.debug('ws', '→ $type ${summariseForLog(payload)}');
      // A second listener on the same future purely to record how it ended. It
      // handles its own error, so the caller's handling is unchanged and nothing
      // becomes an unhandled rejection.
      completer.future.then(
        (value) => appLog.debug('ws', '← $type ${summariseForLog(value)}'),
        onError: (Object error) => appLog.record(
          _expectedRefusal(error) ? AppLogLevel.debug : AppLogLevel.warn,
          'ws',
          '← $type failed',
          error: error,
        ),
      );
    }
    final frame = {
      'type': type,
      'payload': {...payload, 'requestId': requestId},
    };
    if (_ready) {
      unawaited(_sendRpcFrame(frame, requestId, type));
    } else {
      _queue.add(frame);
    }
    return completer.future;
  }

  void sendRaw(String type, Map<String, dynamic> payload) =>
      unawaited(sendFrame({'type': type, 'payload': payload}));

  /// Terminal input is best-effort: it is never queued across reconnect and
  /// the caller gets false if the socket stopped being ready before send.
  Future<bool> sendTerminalFrame(
    String type,
    Map<String, dynamic> payload,
  ) async {
    // Outside the FIFO on purpose: the plugin may wait a bounded while for its wire
    // before an open, and that wait must not hold up other panes' input.
    var openViaPlugin = false;
    final plugin = _plugin;
    final requestId = payload['requestId'];
    // Not worth the wait when the frame cannot go anyway.
    if (plugin != null &&
        isReady &&
        type == 'terminal_open' &&
        requestId is String) {
      openViaPlugin = await plugin.prepareOpen(requestId);
    }
    return _enqueueFrame(
      {'type': type, 'payload': payload},
      requireReady: true,
      openViaPlugin: openViaPlugin,
    );
  }

  Future<bool> sendTerminalBinary(Uint8List bytes) {
    final completer = Completer<bool>();
    _outboundTail = _outboundTail
        .then((_) async {
          if (!isReady) {
            completer.complete(false);
            return;
          }
          final channel = _channel;
          if (channel == null) {
            completer.complete(false);
            return;
          }
          try {
            // Sealed here, inside the outbound FIFO, so frames take their counters in send order.
            final codec = _codec;
            final wire = codec == null ? bytes : codec.encodeBinary(bytes);
            if (wire == null) {
              completer.complete(false);
              return;
            }
            final plugin = _plugin;
            if (plugin != null && await plugin.sendBinary(bytes, wire)) {
              completer.complete(true);
              return;
            }
            channel.sink.add(wire);
            completer.complete(true);
          } catch (_) {
            completer.complete(false);
          }
        })
        .catchError((_) {
          if (!completer.isCompleted) completer.complete(false);
        });
    return completer.future;
  }

  Future<void> sendFrame(Map<String, dynamic> frame) async {
    await _enqueueFrame(frame);
  }

  Future<bool> _enqueueFrame(
    Map<String, dynamic> frame, {
    bool requireReady = false,
    bool openViaPlugin = false,
    TransportVia? force,
    void Function(Object error)? onFailure,
  }) {
    final completer = Completer<bool>();
    _outboundTail = _outboundTail
        .then((_) async {
          if (requireReady && !isReady) {
            completer.complete(false);
            return;
          }
          try {
            await _sendFrameNow(
              frame,
              openViaPlugin: openViaPlugin,
              force: force,
            );
            completer.complete(true);
          } catch (error) {
            onFailure?.call(error);
            completer.complete(false);
          }
        })
        .catchError((error) {
          onFailure?.call(error);
          if (!completer.isCompleted) completer.complete(false);
        });
    return completer.future;
  }

  Future<void> _sendRpcFrame(
    Map<String, dynamic> frame,
    String requestId,
    String type,
  ) async {
    Object? failure;
    final sent = await _enqueueFrame(
      frame,
      onFailure: (error) => failure = error,
    );
    if (sent) return;
    final pending = _pending.remove(requestId);
    if (pending == null) return;
    pending.timer.cancel();
    if (!pending.completer.isCompleted) {
      pending.completer.completeError(
        failure ?? StateError('WS request could not be sent: $type'),
      );
    }
  }

  Future<void> _sendFrameNow(
    Map<String, dynamic> frame, {
    bool openViaPlugin = false,
    TransportVia? force,
  }) async {
    final type = frame['type'] as String;
    var payload = (frame['payload'] as Map<String, dynamic>?) ?? {};
    if (onOutgoing != null) payload = await onOutgoing!(type, payload);
    final channel = _channel;
    if (channel == null) throw StateError('WS is not connected');
    final out = <String, dynamic>{'type': type, 'payload': payload};
    final codec = _codec;
    final wire = codec == null ? out : codec.encodeFrame(out);
    if (wire == null) throw StateError('E2EE session is not ready for $type');
    final encoded = jsonEncode(wire);
    // Sealed first, then offered: the counter is taken in send order whichever
    // wire ends up carrying the frame, which is what the peer's replay window needs.
    // Only once the session is up: nothing before that (the select, the hello) is
    // the plugin's to route.
    final plugin = _plugin;
    if (plugin != null &&
        _ready &&
        plugin.sendJson(
          type,
          payload,
          encoded,
          openViaPlugin: openViaPlugin,
          force: force,
        )) {
      return;
    }
    channel.sink.add(encoded);
  }

  void _flushQueue() {
    final queued = List<Map<String, dynamic>>.from(_queue);
    _queue.clear();
    for (final frame in queued) {
      final payload = (frame['payload'] as Map<String, dynamic>?) ?? const {};
      final requestId = payload['requestId'];
      if (requestId is String && _pending.containsKey(requestId)) {
        unawaited(
          _sendRpcFrame(
            frame,
            requestId,
            frame['type'] as String? ?? 'request',
          ),
        );
      } else {
        unawaited(sendFrame(frame));
      }
    }
  }

  void _onDone(WebSocketChannel channel) {
    if (!identical(_channel, channel)) return;
    _observerHandshakeTimer?.cancel();
    _stableTimer?.cancel();
    _channel = null;
    _sub = null;
    _codec = null;
    _disposePlugin();
    _ready = false;
    _rejectPending('WS disconnected');
    if (_closing) {
      onStatus(ConnectionStatus.disconnected);
      return;
    }
    final code = channel.closeCode;
    if (isLocal) {
      if (channel.closeReason == 'MACHINE_OFFLINE') {
        _park();
        return;
      }
      if (finalSelectRefusals.contains(channel.closeReason)) {
        // The relay could not select the machine, for good: told as a 4404 is, never redialled.
        _closing = true;
        onLocalFailure?.call(code ?? 1011, channel.closeReason!);
        onStatus(ConnectionStatus.disconnected);
        return;
      }
      if (code == 4404 || (observerShareId != null && code == 4403)) {
        _closing = true;
        // needsLink first: AppNotifier's onStatus handler reads machine.needsLink
        // to decide whether a disconnect should be treated as the node going
        // offline — it has to see it flipped before onStatus runs, or the very
        // first 4404 for this machine reads as offline for one retry cycle.
        onLocalFailure?.call(code!, channel.closeReason ?? 'NO_PEER_LINK');
        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;
    }
    if (code == 4401) {
      final token = _tokenUsed;
      if (token != null && token == _refreshedToken) {
        _closing = true;
        onStatus(ConnectionStatus.disconnected);
        onAuthFailure('Your SSO session expired. Please sign in again.');
        return;
      }
      unawaited(_refreshAndReconnect());
      return;
    }
    _refreshedToken = null;
    if (code == 4403) {
      _closing = true;
      onStatus(ConnectionStatus.disconnected);
      if (_directObserver) {
        onLocalFailure?.call(4403, 'Sharing ended or invitation expired.');
        return;
      }
      onAuthFailure('SSO environment does not match this backend');
      return;
    }
    _scheduleReconnect();
  }

  /// The backend refused this socket's select. The app still hears it ([onEvent]); a refusal no
  /// redial can change also ends the connection, which would otherwise sit open and unselected.
  void _selectRefused(Map<String, dynamic> message) {
    final payload = message['payload'];
    if (payload is! Map || payload['machineId'] != machineId) return;
    if (_closing || _ready || !finalSelectRefusals.contains(payload['error'])) {
      return;
    }
    _closing = true;
    _reconnectTimer?.cancel();
    _reconnectTimer = null;
    _disposePlugin();
    onStatus(ConnectionStatus.disconnected);
    final channel = _channel;
    _channel = null;
    unawaited(channel?.sink.close().catchError((Object _) {}));
  }

  Future<void> _refreshAndReconnect() async {
    onStatus(ConnectionStatus.reconnecting);
    try {
      _refreshedToken = await accessTokenProvider(true, _tokenUsed);
      if (_closing) return;
      // The first refusal in a run dials straight back with the new token; a run that keeps
      // failing waits its turn like any other drop.
      if (_attempt == 0) {
        _attempt = 1;
        await connect();
      } else {
        _scheduleReconnect();
      }
    } catch (_) {
      _closing = true;
      onStatus(ConnectionStatus.disconnected);
      onAuthFailure('Your SSO session expired. Please sign in again.');
    }
  }

  /// A Desktop connection that has not been up yet, within its quick retries. A browser's sockets
  /// each reach the backend itself, so it keeps the plain backoff.
  bool get _onFirstConnect =>
      isLocal && !_everReady && _attempt <= firstConnectRetries;

  /// Nothing has been lost yet: its quick tries, or the seconds of [firstConnectFor].
  bool get _saysConnecting =>
      _onFirstConnect ||
      (isLocal &&
          !_everReady &&
          (_firstConnect?.elapsed ?? Duration.zero) < firstConnectFor);

  void _scheduleReconnect() {
    if (_closing) return;
    _attempt++;
    onStatus(
      _saysConnecting
          ? ConnectionStatus.connecting
          : ConnectionStatus.reconnecting,
    );
    _reconnectTimer?.cancel();
    final delay =
        fixedReconnectDelay ??
        (_onFirstConnect
            ? firstConnectRetryDelay(_attempt)
            // The backoff starts from its beginning once the quick tries are spent.
            : reconnectDelay(
                isLocal && !_everReady
                    ? _attempt - firstConnectRetries
                    : _attempt,
                _random,
              ));
    _reconnectTimer = Timer(delay, connect);
  }

  static WebSocketChannel _connectCloud(Uri uri, Iterable<String>? protocols) =>
      WebSocketChannel.connect(uri, protocols: protocols);

  void _rejectPending(String reason) {
    _settleReadiness(reason);
    for (final pending in _pending.values) {
      pending.timer.cancel();
      if (!pending.completer.isCompleted) {
        pending.completer.completeError(Exception(reason));
      }
    }
    _pending.clear();
    _queue.clear();
  }

  Future<void> close() async {
    _closing = true;
    _observerHandshakeTimer?.cancel();
    _ready = false;
    _codec = null;
    _disposePlugin();
    _reconnectTimer?.cancel();
    _reconnectTimer = null;
    _stableTimer?.cancel();
    _rejectPending('WS closed');
    final sub = _sub;
    _sub = null;
    await sub?.cancel();
    final channel = _channel;
    _channel = null;
    // 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);
  }

  /// Forces a fresh upstream relay dial for this machine — the transport itself can stay technically
  /// "connected" (ping/pong healthy) while the *application*-level session behind it is dead, e.g. the
  /// relayed machine's own Harness process restarted and dropped its in-memory E2EE session state; no
  /// close event ever fires for that, so nothing else would ever redial. Callers reach for this after
  /// observing a live RPC time out on an otherwise "connected" machine. Closes the local connection and
  /// immediately reconnects with a `forceReconnect` hint so the CLI daemon drops its cached relay entry
  /// instead of reusing it.
  Future<void> forceReconnect() async {
    // A viewer's relay connection holds that session itself, so for it this is simply a fresh dial
    // — and with it a fresh session.
    if (_closing || (!isLocal && relayCodecs == null)) return;
    _observerHandshakeTimer?.cancel();
    _forceRelayReconnect = true;
    _reconnectTimer?.cancel();
    _ready = false;
    _codec = null;
    _disposePlugin();
    _rejectPending('forcing relay reconnect');
    final sub = _sub;
    _sub = null;
    await sub?.cancel();
    final channel = _channel;
    _channel = null;
    if (channel != null) {
      try {
        await channel.sink.close();
      } catch (_) {
        /* already gone */
      }
    }
    _attempt = 0;
    await connect();
  }

  /// Drops only the live transport so integration tests can exercise the real
  /// reconnect path. Unlike [close], this deliberately leaves reconnect
  /// enabled and does not queue terminal input while the socket is down.
  @visibleForTesting
  Future<void> debugDropTransport() async {
    final channel = _channel;
    if (channel == null) throw StateError('WS transport is not connected');
    // 1012 is a server-only close code and Dart correctly rejects clients that
    // try to send it. Use the application/private range so this still drives
    // the real onDone -> reconnect path without pretending to be the server.
    await channel.sink.close(4000, 'integration test transport drop');
  }

  void _disposePlugin() {
    final plugin = _plugin;
    _plugin = null;
    plugin?.dispose();
  }

  static String _newRequestId() {
    final random = Random.secure();
    final bytes = List<int>.generate(16, (_) => random.nextInt(256));
    return 'dsk_${bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join()}';
  }
}

/// The connection as its plugin sees it — see [TerminalTransportHost].
class _PluginHost implements TerminalTransportHost {
  _PluginHost(this._conn);
  final WsConn _conn;

  @override
  RelayCodec get codec {
    final codec = _conn._codec;
    if (codec == null) throw StateError('relay session is gone');
    return codec;
  }

  @override
  Future<bool> send(Map<String, dynamic> frame, {TransportVia? force}) =>
      _conn._enqueueFrame(frame, requireReady: true, force: force);

  @override
  void enqueueInbound(Future<void> Function() task) {
    _conn._inboundTail = _conn._inboundTail.then((_) => task()).catchError((_) {
      // Keep the FIFO alive, as the socket's own handlers do.
    });
  }

  @override
  Future<void> dispatch(Map<String, dynamic> plain) => _conn._dispatch({
    ...plain,
    'payload': (plain['payload'] as Map<String, dynamic>?) ?? {},
  });

  @override
  Future<void> deliverBinary(Uint8List localFrame) async {
    await _conn.onBinaryFrame?.call(localFrame);
  }
}

class _PendingRpc {
  final Completer<Map<String, dynamic>> completer;
  final Timer timer;
  _PendingRpc(this.completer, this.timer);
}