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.

62.4 KB
Raw Blame
import 'dart:async';
import 'dart:convert';
import 'dart:isolate';
import 'dart:math';

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

import '../logging/app_log.dart';
import '../logging/redact.dart';
import '../logging/startup_trace.dart';
import '../logging/typing_trace.dart';
import '../core/client_build.dart';
import '../core/models.dart';
import '../core/test_run.dart';
import 'relay_codec.dart';
import 'terminal_transport_plugin.dart';

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

/// Thrown by an [AccessTokenProvider] when the session is gone for good — the refresh token was
/// refused, or there never was one. Only this signs the person out.
///
/// ⚠️ Anything else a provider throws is taken for a blip and retried. A refresh that never reached
/// the server says nothing about the session, and a sign-out cannot be undone by the network
/// coming back.
class WsCredentialRevoked implements Exception {
  const WsCredentialRevoked(this.message);

  final String message;

  @override
  String toString() => message;
}

/// Socket construction can be replaced by an in-process channel in tests.
typedef WsChannelFactory = WebSocketChannel Function(
  Uri uri, {
  Iterable<String>? protocols,
});

/// 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.hold,
  });

  /// 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;

  /// A code naming why the peer holds the request, when it sends one — `PROGRAM_REPLACED` from a
  /// Change agent handoff. A code, never words to show: the caller picks its own sentence.
  final String? hold;

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

/// One SSO-authenticated, machine-scoped connection to `/api/web-ws`.
class WsConn {
  final WsChannelFactory? connectChannel;
  final String wsBaseUrl;
  final String autonomousEnv;
  final String machineId;
  final AccessTokenProvider accessTokenProvider;
  final void Function(String message) onAuthFailure;

  /// A peer-link failure that needs user action, surfaced instead of retrying
  /// a connection until trust has been established.
  final void Function(int code, String reason)? onLocalFailure;

  /// 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;

  /// What this build says of itself in the socket's query ([ClientBuild]): its release, and whether it is a
  /// debug or simulator build, so the backend's count of the phone's opens can tell them apart. Asked at
  /// every dial, with the credential; null: nothing is said, as an older app.
  final Future<ClientBuild> Function()? clientBuild;

  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;
  Timer? _reconnectTimer;
  String? _tokenUsed;

  /// The relay said this connection's machine is offline, and the connection is waiting for it to
  /// come back rather than redialling — see [parkUntilOnline].
  bool _parked = false;
  bool get isParked => _parked;

  /// How long a parked connection first waits before it dials again of its own accord, with nothing
  /// having said the machine is back — the fallback under [wake], not the way back.
  ///
  /// ⚠️ **Each such recheck waits twice as long as the one before, up to [_parkedRecheckCeiling]
  /// (2026-10-20).** At a flat minute, an app left open beside a machine that is switched off
  /// dialled it sixty times an hour for as long as it stayed open — a simulator left running did
  /// exactly that through 2026-10-19/20, while the relay counted 15,104 phone sockets against 344
  /// the day before and the people using the phone stayed level. Each dial is a token, a key mint
  /// on this thread and a TLS handshake here, and an auth, a lookup and a write at the relay.
  /// Nothing is slower to come back for it: the relay's push, `/api/machines`, a tap and the app's
  /// return all [wake] it at once and start the waits over.
  static const _parkedRecheck = Duration(seconds: 60);
  static const _parkedRecheckCeiling = Duration(minutes: 15);

  /// The rechecks this connection has dialled in a row on its own ([wake] with `recheck`), each
  /// one parked again: what [parkedRecheckAfter] doubles the next wait by.
  int _parkedRechecks = 0;

  /// The wait before a parked connection's next recheck after [rechecks] of them in a row:
  /// a minute, then 2, 4, 8, and 15 at most.
  @visibleForTesting
  static Duration parkedRecheckAfter(int rechecks) {
    final wait = _parkedRecheck * (1 << min(max(rechecks, 0), 4));
    return wait > _parkedRecheckCeiling ? _parkedRecheckCeiling : wait;
  }

  /// This socket's `e2e_hello` went out right behind its `machine_select`, so the select's ack must
  /// not send another — see [connect]. Reset on every dial.
  bool _helloAhead = false;

  /// How long a dial may take to open before it counts as failed. Without one, a socket dialled
  /// into a network that swallows packets waits out the OS's own TCP timeout — over a minute on
  /// iOS — with the machine showing "reconnecting" the whole time.
  static const _dialTimeout = Duration(seconds: 15);

  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;

  /// When this connection last opened a frame its MACHINE sealed — proof the end-to-end session
  /// with the machine is alive, as against the relay merely being up. Null until the first.
  ///
  /// ⚠️ **Sealed frames only, never the relay's own.** `node_status`, `machines_status` and the
  /// handshake come from the backend, and keep coming while the session behind them is dead (the
  /// machine's Harness restarted and dropped it); counted, they would make a stale session look
  /// like a slow one. Read by a terminal's open watchdog (`TerminalSession.lastHeardFromMachine`)
  /// and by the agent-list timeout, to tell a machine that is slow from one that is gone.
  DateTime? get lastHeardFromMachineAt => _lastHeardFromMachineAt;
  DateTime? _lastHeardFromMachineAt;

  void _heardFromMachine() => _lastHeardFromMachineAt = DateTime.now();

  /// 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);
    return ready.future
        .timeout(
          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;

  /// 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({
    required this.wsBaseUrl,
    this.connectChannel,
    required this.autonomousEnv,
    required this.machineId,
    required this.accessTokenProvider,
    required this.onAuthFailure,
    this.onLocalFailure,
    required this.onEvent,
    required this.onStatus,
    this.relayCodecs,
    this.transportPlugins,
    this.clientBuild,
  });

  /// [clientBuild], bounded and never failing: a dial does not wait on its own bookkeeping.
  Future<ClientBuild?> _clientBuild() async {
    final ask = clientBuild;
    if (ask == null) return null;
    try {
      return await ask().timeout(const Duration(milliseconds: 500));
    } catch (_) {
      return null;
    }
  }

  Future<void> connect() async {
    if (_closing || _connecting) return;
    _connecting = true;
    _ready = false;
    // A dial is under way: whatever parked the last one is over ([parkUntilOnline]).
    _parked = false;
    // ⚠️ **The outbound queue starts empty on every dial, and it did not used
    // to.** `_outboundTail` is a chain each send appends itself to, so one link
    // that never completes stalls every frame queued behind it — for the life of
    // the connection, redials included, because the chain outlived them. A dial
    // whose `machine_select` never reached the socket therefore could not be
    // rescued by dialling again: the new select joined the same stuck queue.
    //
    // Safe to drop here because a new socket makes the old queue meaningless.
    // Anything still pending on it was addressed to a channel that is gone, and
    // `_flushQueue` re-sends what actually matters once the session is ready.
    _outboundTail = Future<void>.value();
    _helloAhead = false;
    WebSocketChannel? dialing;
    onStatus(
      _attempt == 0
          ? ConnectionStatus.connecting
          : ConnectionStatus.reconnecting,
    );
    try {
      // ⚠️ Started together, then awaited: the credential comes from the session
      // (and may go to the network to refresh), while the codec comes off disk
      // and mints an ephemeral key — neither has ever needed the other's result.
      // In series they were two waits stacked in front of the dial, on the
      // stretch the phone shows as "Connecting to your computer…", and every
      // reconnect paid it again.
      final codecs = relayCodecs;
      final pendingToken = StartupTrace.time(
        'ws.accessToken',
        () => accessTokenProvider(false, null),
      );
      // ⚠️ **The codec's own failure is captured HERE, where the future is made,
      // not where it is awaited.** The credential is awaited first and can
      // throw — a refresh against a dead network does — and every path out of
      // this method from that point leaves nobody to await the codec. An
      // unhandled rejection on that abandoned future reaches the zone's error
      // handler and is reported as a crash, for a dial that merely failed.
      //
      // ⚠️ Captured, NOT flattened to null: a null codec means "this device has
      // no link to that machine", which [_refusePeer] answers by closing the
      // connection for good. A failed READ of the link is a different thing —
      // the file was locked, or briefly unreadable — and must stay retryable, so
      // it is rethrown below into the catch that schedules the reconnect.
      final pendingCodec = codecs == null
          ? null
          : StartupTrace.time(
              'ws.relayCodec',
              () => codecs(machineId),
            ).then<({RelayCodec? codec, Object? error})>(
              (codec) => (codec: codec, error: null),
              onError: (Object error) => (codec: null, error: error),
            );
      // What the codec said while the credential was being fetched, if it has said it yet.
      ({RelayCodec? codec, Object? error})? codecAnswered;
      unawaited(pendingCodec?.then((result) => codecAnswered = result));
      // Asked with the credential and the codec, so it adds no wait of its own: once the app has read
      // its version (at launch) the answer is already there. Never a reason not to dial.
      final pendingBuild = _clientBuild();
      final token = await pendingToken;
      if (token.isEmpty) {
        throw StateError('WebSocket credential is missing');
      }
      final build = await pendingBuild;
      if (_closing) return;
      // The codec's "no link" comes from links held in memory, a handful of microtasks behind its
      // start — and the credential, also from memory, often lands in the same turn, just ahead of
      // it: measured, Find dialled three unlinked machines that way. A few microtask hops let an
      // answer already on its way arrive. Microtasks only, so this never waits on the event loop or
      // a frame; a codec still reading the disk or minting a key is not waited for.
      for (
        var hop = 0;
        hop < _codecAnswerHops && pendingCodec != null && codecAnswered == null;
        hop++
      ) {
        await Future<void>.value();
      }
      if (_closing) return;
      // ⚠️ **No link, no dial (owner, 2026-10-02).** The codec answers "no link to this machine"
      // from the links this device holds in memory, usually before the credential is back — and
      // the dial below went out anyway, a TCP + TLS + upgrade opened only to be dropped by
      // [_refusePeer] the moment the codec was awaited. Opening Find did that for every machine
      // this phone never linked, on every opening. Said already, it is said here, with no socket;
      // not said yet, the dial goes ahead as before and the same refusal follows it.
      final early = codecAnswered;
      if (early != null && early.codec == null && early.error == null) {
        _refusePeer('NO_PEER_LINK');
        return;
      }
      _tokenUsed = token;
      final base = Uri.parse('$wsBaseUrl/api/web-ws');
      final uri = base.replace(
        queryParameters: {
          ...base.queryParameters,
          'autonomousEnv': autonomousEnv,
          // Counts this person as on the mobile app today (backend user_daily_client_presence).
          'client': 'mobile',
          // And which release, and whether a debug or simulator build (backend relay_mobile_opens).
          ...?build?.query,
        },
      );
      // ⚠️ **Dialled BEFORE the codec is awaited (owner, 2026-10-01).** The socket needs only the
      // credential; the codec is not used until the first frame. Awaited first, its disk read and key
      // mint (~65ms at launch) stood in front of a TCP + TLS + upgrade that could have been under way.
      //
      // ⚠️ But NOT made [_channel] until the codec is in place: a frame sent in between would go
      // out with no codec to seal it — in the clear. Until then the socket is this method's alone,
      // and closed here on every way out.
      final channel = (connectChannel ?? WebSocketChannel.connect)(
        uri,
        protocols: [token],
      );
      void dropChannel() =>
          unawaited(channel.sink.close().catchError((Object _) {}));
      // Its outcome captured here, where the future is made: the ways out below leave without
      // awaiting it, and an unhandled rejection would be reported as a crash.
      final opening = StartupTrace.time(
        'ws.dial',
        () => channel.ready.timeout(_dialTimeout),
      ).then<Object?>((_) => null, onError: (Object error) => error);
      if (pendingCodec != null) {
        final result = await pendingCodec;
        if (_closing) {
          dropChannel();
          return;
        }
        final failure = result.error;
        if (failure != null) {
          dropChannel();
          throw failure;
        }
        final codec = result.codec;
        if (codec == null) {
          dropChannel();
          _refusePeer('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);
      }
      _channel = dialing = channel;
      final dialFailure = await opening;
      if (dialFailure != null) throw dialFailure;
      if (_closing || !identical(_channel, channel)) {
        // Logged because this is a silent exit from a dial that otherwise looks
        // successful — the trace shows `ws.dial` completing and then nothing at
        // all, which is indistinguishable from a relay that went quiet.
        final superseded = !identical(_channel, channel);
        appLog.warn(
          'ws',
          'dial abandoned after ready (closing=$_closing '
              'superseded=$superseded) $machineId',
        );
        await channel.sink.close();
        // ⚠️ A superseded dial must leave a live connection behind it. This used
        // to just return, on the assumption that whoever replaced `_channel` was
        // finishing the job — but the replacement is a `connect()` that
        // `_connecting` had already turned away, so there was nobody to finish
        // it. The guard in [reconnectNow] stops the overlap happening at all;
        // this makes the outcome survivable if it ever does again.
        if (superseded && !_closing && _channel == null) _scheduleReconnect();
        return;
      }
      _sub = channel.stream.listen(
        _onRaw,
        onDone: () => _onDone(channel),
        onError: (_) => _onDone(channel),
      );
      // ⚠️ **Armed BEFORE the send, and deliberately not after it.** `sendFrame`
      // queues behind `_outboundTail`, so it resolves when this frame reaches
      // the socket — which is not guaranteed to be soon, and on a fresh dial was
      // observed never to happen at all. Arming afterwards made the watchdog
      // itself unreachable in exactly the case it exists for: the launch hung
      // with the last log line being the dial, and no select, no answer and no
      // retry after it.
      //
      // Armed first, the timer covers the whole of "asked and not answered",
      // whether the asking stalled in the queue or the answering stalled at the
      // relay. Cancelled by [_markReady], by [_onDone] and by [close].
      _armSelectWatchdog();
      appLog.debug('ws', '→ machine_select $machineId');
      final selected = await _enqueueFrame({
        'type': 'machine_select',
        'payload': {'machineId': machineId},
      });
      // ⚠️ **The hello goes right behind the select, not on its ack (owner, 2026-10-01).** The
      // relay takes a socket's frames strictly in order (`backend/src/lib/orderedInbox.ts`), so it
      // reaches the machine only once the select has bound — waiting for the ack added a whole
      // phone↔relay round trip in front of every handshake. A select the relay refuses drops it
      // (no machine bound), which is harmless. The ack still reaches the plugin before the welcome:
      // the relay sends it before it handles the hello. See the `connected` case in [_onRelayFrame].
      final codec = _codec;
      if (selected &&
          codec != null &&
          !_closing &&
          !_ready &&
          identical(_channel, channel)) {
        channel.sink.add(jsonEncode(codec.helloFrame()));
        _helloAhead = true;
      }
    } on WsCredentialRevoked catch (error) {
      // ⚠️ Not for a connection somebody already closed. Signing out closes every connection, and
      // one still waiting on its credential then learns the session is gone — which is the
      // sign-out in progress, not news. Reported, it re-entered the app's sign-out halfway through
      // that one, which then stopped early.
      if (!_closing) _signOut(error.message);
    } catch (error) {
      // Swallowed for control flow — a failed dial is retried, not surfaced —
      // but not silently: this branch covers the credential, the codec, the
      // dial itself and the select, and with no line of its own a launch that
      // died in any of them looked exactly like one that simply stopped.
      appLog.warn('ws', 'dial failed $machineId', error: error);
      _abandonDial(dialing);
      if (!_closing) _scheduleReconnect();
    } finally {
      _connecting = false;
    }
  }

  /// Lets go of a channel whose dial failed.
  ///
  /// ⚠️ Left in place, it reads as a live socket: [reconnectNow] skips a connection that has one,
  /// so the app coming back to the foreground would wait out the whole backoff — up to 30s — rather
  /// than dial.
  void _abandonDial(WebSocketChannel? channel) {
    if (channel == null || !identical(_channel, channel)) return;
    _channel = null;
    final sub = _sub;
    _sub = null;
    unawaited(sub?.cancel());
    unawaited(channel.sink.close().catchError((Object _) {}));
  }

  /// Refusals 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. Every code the relay's
  /// `machine_select` answers with besides these may pass (`backend/src/lib/webWs.ts`).
  static const _finalSelectRefusals = {
    'NOT_YOUR_MACHINE',
    'MACHINE_ENV_MISMATCH',
    'MACHINE_PAYMENT_PENDING',
    'MACHINE_SUBSCRIPTION_REQUIRED',
  };

  /// The relay refused this connection's select. The app still hears the refusal ([onEvent]); the
  /// connection stops here for good when no redial can change it, or else waits out its backoff.
  ///
  /// ⚠️ **Why (prod, 2026-10-28).** Nothing here read the refusal, so [_armSelectWatchdog] took the
  /// silence after it for a relay gone quiet and redialled six seconds later, for as long as the app
  /// was open: a laptop removed from the account in September was still selected every ~7 s, about
  /// 20 dials in ten minutes from one phone, each a fresh credential, key and TLS dial.
  void _selectRefused(Map<String, dynamic> message) {
    final payload = message['payload'];
    if (payload is! Map || payload['machineId'] != machineId) return;
    if (_closing || _ready) return;
    _selectWatchdog?.cancel();
    _selectWatchdog = null;
    final code = '${payload['error'] ?? ''}';
    appLog.info('ws', 'machine_select refused for $machineId: $code');
    if (!_finalSelectRefusals.contains(code)) {
      _abandonDial(_channel);
      _scheduleReconnect();
      return;
    }
    _closing = true;
    _reconnectTimer?.cancel();
    _reconnectTimer = null;
    _disposePlugin();
    onStatus(ConnectionStatus.disconnected);
    final channel = _channel;
    _channel = null;
    unawaited(channel?.sink.close().catchError((Object _) {}));
  }

  void _signOut(String message) {
    _closing = true;
    onStatus(ConnectionStatus.disconnected);
    onAuthFailure(message);
  }

  /// How many microtask hops [connect] gives the codec's answer before dialling — more than the
  /// in-memory link lookup takes to reach it (~6), and still nothing a person could measure.
  static const _codecAnswerHops = 12;

  /// From this many characters a relay text frame is decoded off the UI isolate — see [_onRaw].
  static const _decodeOffThreadFrom = 64 * 1024;

  /// [raw]'s JSON object, decoded on a background isolate; null for anything that is not one. An
  /// isolate that will not start is the decode done here.
  static Future<Map<String, dynamic>?> _decodeOffThread(String raw) async {
    Object? decoded;
    try {
      decoded = await Isolate.run(() => jsonDecode(raw));
    } on FormatException {
      return null;
    } on Object {
      try {
        decoded = jsonDecode(raw);
      } on Object {
        return null;
      }
    }
    return decoded is Map<String, dynamic> ? decoded : null;
  }

  /// A relay frame's turn in the inbound line, against when the socket handed it over: said when it
  /// waited (or [always]), and only while somebody types — the channel's frames share this line
  /// (`TerminalTransportHost.enqueueInbound`), so a wait here is a wait for the terminal too.
  static void _traceInbound(String what, int arrivedMs, {bool always = false}) {
    final waited = typingNowMs() - arrivedMs;
    final line =
        'ws in $what arrived t=$arrivedMs, waited ${waited}ms in the inbound line';
    if (always) {
      typingEvent(line);
    } else if (waited >= 10) {
      typingNote(line);
    }
  }

  static String _typeOf(Map<String, dynamic> message) =>
      message['type'] is String ? message['type'] as String : '?';

  static String _short(String machineId) =>
      machineId.length <= 8 ? machineId : machineId.substring(0, 8);

  void _onRaw(dynamic raw) {
    final codec = _codec;
    // When the socket handed the frame over, against when its turn in the inbound line came — see
    // [_traceInbound].
    final arrivedMs = kTypingTrace ? typingNowMs() : 0;
    if (raw is List<int>) {
      // The socket already hands over a Uint8List; copying it cost one allocation per chunk of
      // terminal output, for nothing.
      final bytes = raw is Uint8List ? raw : Uint8List.fromList(raw);
      _inboundTail = _inboundTail
          .then((_) async {
            if (kTypingTrace) _traceInbound('binary', arrivedMs);
            final local = codec == null ? bytes : codec.decodeBinary(bytes);
            if (local == null) return;
            // Every relay binary frame is sealed by the machine — see [lastHeardFromMachineAt].
            if (codec != null) _heardFromMachine();
            await _plugin?.observeWsBinary(local);
            await onBinaryFrame?.call(local);
          })
          .catchError((_) {
            // Binary E2EE/session code owns recovery for bad frames.
          });
      return;
    }
    // ⚠️ **A large frame is decoded off the UI isolate, in its place in the line (owner,
    // 2026-10-02).** A machine's whole agent list arrives as one frame of hundreds of KB, and its
    // JSON was decoded right here on the thread drawing the screen — then opened (below), then
    // decoded again. Done inside the inbound chain rather than before it, so it keeps its place:
    // the frames behind it wait for it exactly as they waited for the decode done here.
    if (codec != null &&
        raw is String &&
        raw.length >= _decodeOffThreadFrom &&
        !kUnderTest) {
      if (kTypingTrace) {
        typingEvent(
          'ws in large frame ${(raw.length / 1024).round()}KB arrived t=$arrivedMs',
        );
      }
      _inboundTail = _inboundTail
          .then((_) async {
            if (kTypingTrace) {
              _traceInbound('large frame', arrivedMs, always: true);
            }
            final clock = Stopwatch()..start();
            final message = await _decodeOffThread(raw);
            if (message == null) return;
            final decodeMs = clock.elapsedMilliseconds;
            await _onRelayFrame(codec, message);
            appLog.info(
              'ws',
              'large frame · ${(raw.length / 1024).round()}KB '
                  '${_typeOf(message)} · decoded off-thread in ${decodeMs}ms, '
                  'handled in ${clock.elapsedMilliseconds}ms · ${_short(machineId)}',
            );
          })
          .catchError((_) {
            // Keep the FIFO alive: a frame that will not open is dropped, never dispatched.
          });
      return;
    }
    final Map<String, dynamic> message;
    try {
      message = jsonDecode(raw as String) as Map<String, dynamic>;
    } catch (_) {
      return;
    }
    if (message['type'] == 'machine_select_error') _selectRefused(message);
    if (codec != null) {
      _inboundTail = _inboundTail
          .then((_) {
            if (kTypingTrace) _traceInbound(_typeOf(message), arrivedMs);
            return _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.
        });
  }

  /// How long the relay gets to answer `machine_select` before this redials.
  ///
  /// Measured against the real thing: a relay that answers at all answers in
  /// well under a second (dial ~0.8s, then `machines_status` and the E2EE
  /// welcome within ~1.3s). Six seconds is far outside that and still far inside
  /// a person's patience.
  static const _selectTimeout = Duration(seconds: 6);

  Timer? _selectWatchdog;

  /// Redial if the relay never answers the select.
  ///
  /// ⚠️ **A dial can complete and then go quiet, and nothing else notices.** The
  /// socket opens, `machine_select` goes out, and the relay simply never sends
  /// `machines_status` — observed on the FIRST dial of a launch, reproducibly,
  /// against a machine that was up the whole time. There is no close, no error
  /// and no frame: `_onDone` never runs, the reconnect backoff never arms, and
  /// the connection sits there looking healthy forever.
  ///
  /// It used to be papered over from a long way away: `agents_list` would time
  /// out after ten seconds, be misread as the machine having gone offline, and
  /// `forceReconnect()` would redial — which worked, and cost twelve seconds and
  /// a spurious "Disconnected" on screen. Removing that accidental rescue is
  /// what turned this from slow into a permanent hang, which is how it was
  /// finally found.
  ///
  /// Handled here, where the evidence is: this connection asked a question and
  /// got no answer, so it asks again on a new socket. Six seconds rather than
  /// ten, and no state anywhere else is told the machine is offline, because
  /// nothing here says it is.
  void _armSelectWatchdog() {
    _selectWatchdog?.cancel();
    _selectWatchdog = Timer(_selectTimeout, () {
      if (_closing || _ready || _channel == null) return;
      appLog.warn('ws', 'machine_select unanswered; redialling $machineId');
      // Through the ordinary dial path, so the attempt counter and its backoff
      // apply: a relay that is genuinely down must not be hammered every six
      // seconds by a client that thinks it is being helpful.
      _abandonDial(_channel);
      _scheduleReconnect();
    });
  }

  /// The relay has just said this connection's machine is offline: stop treating the silence that
  /// follows as a dial gone wrong, and wait for the machine instead.
  ///
  /// ⚠️ **Why (owner, 2026-10-02).** Without this, a machine that is switched off was redialled for
  /// as long as the app ran: [_armSelectWatchdog] read the welcome that never came as a relay gone
  /// quiet, and every redial on its 1–30s backoff paid a fresh credential, a key mint and a TLS
  /// dial — the key mint pure Dart on the UI thread. Opening Find dials every machine on the
  /// account, so four machines that were off cost about twenty of those in Find's first minute.
  ///
  /// The socket is KEPT, not closed. The relay pushes every one of the account's machines'
  /// status changes down every socket (`machines_status`), so the app hears this machine come back
  /// through it — or through any other machine's socket, or `/api/machines` — and calls [wake]. A
  /// welcome that arrives anyway (the relay was wrong) still makes it ready ([_markReady]). With
  /// nothing heard at all, it dials again after [parkedRecheckAfter] — longer each time.
  ///
  /// Only a connection that never became ready: a live session's machine going away is the
  /// `node_status` the app already handles, on a socket that is still up.
  void parkUntilOnline() {
    if (_closing || _ready || _parked || _channel == null) return;
    _parked = true;
    _selectWatchdog?.cancel();
    _selectWatchdog = null;
    _reconnectTimer?.cancel();
    final wait = parkedRecheckAfter(_parkedRechecks);
    _reconnectTimer = Timer(wait, () => wake(_recheck));
    appLog.info(
      'ws',
      'parked $machineId · the relay says it is offline; '
          'waiting for it (recheck ${wait.inSeconds}s)',
    );
  }

  /// [wake]'s reason when nothing said the machine is back: the parked connection's own timer.
  static const _recheck = 'recheck';

  /// The app has gone to the background: a parked connection stops dialling again on its own. A
  /// phone that runs no code would not have dialled anyway, but one that still does (Android for a
  /// while, a simulator) was dialling for nobody. Nothing else changes: it stays parked, a push still
  /// [wake]s it, and coming back to the front asks again at once ([reconnectNow]).
  void pauseParkedRecheck() {
    if (!_parked) return;
    _reconnectTimer?.cancel();
    _reconnectTimer = null;
  }

  /// Dial a parked connection now — its machine was reported back ([reason] goes to the log).
  /// Nothing for a connection that is not parked.
  void wake(String reason) {
    if (!_parked) return;
    _parked = false;
    // Its own recheck makes the next wait longer; anything else — the machine reported back,
    // somebody asking for it — starts the waits over.
    _parkedRechecks = reason == _recheck ? _parkedRechecks + 1 : 0;
    _reconnectTimer?.cancel();
    _reconnectTimer = null;
    if (_closing || _ready) return;
    appLog.info('ws', 'woken $machineId · $reason');
    _abandonDial(_channel);
    _attempt = 0;
    // A dial still finishing would turn [connect] away, and nothing would dial after it: the
    // ordinary backoff picks it up instead.
    if (_connecting) {
      _scheduleReconnect();
      return;
    }
    unawaited(connect());
  }

  void _markReady() {
    _selectWatchdog?.cancel();
    _selectWatchdog = null;
    // The machine answered after all: the recheck a park armed is not wanted.
    if (_parked) {
      _parked = false;
      _reconnectTimer?.cancel();
      _reconnectTimer = null;
    }
    _parkedRechecks = 0;
    _ready = true;
    _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 {
    final payload = (message['payload'] as Map<String, dynamic>?) ?? {};
    switch (message['type']) {
      case 'connected':
        // 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);
          // Already sent behind this socket's select — see [connect]. Exactly one hello per
          // session: a second one would have the machine start the handshake over.
          if (_helloAhead) {
            _helloAhead = false;
            return;
          }
          _channel?.sink.add(jsonEncode(codec.helloFrame()));
        }
        return;
      case 'e2e_welcome':
        // 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;
        // The verify and key agreement behind this are pure-Dart Ed25519/X25519
        // on the UI isolate, so this span is CPU on the very thread drawing the
        // spinner — worth its own line to tell it apart from time spent waiting
        // on the machine to answer.
        if (await StartupTrace.time(
          'ws.e2eeWelcome',
          () => codec.handleWelcome(payload),
        )) {
          StartupTrace.mark('ws.ready');
          _markReady();
          _plugin?.onSessionReady();
        } else {
          _refusePeer('E2EE_WELCOME_INVALID');
        }
        return;
      case 'e2e_denied':
        _refusePeer('E2E_DENIED');
        return;
      case 'e2e_rekey':
        codec.handleRekey(payload);
        return;
    }
    // A large sealed payload is opened off the UI isolate, by a codec that can.
    final clear = codec is OffThreadRelayDecoder
        ? await (codec as OffThreadRelayDecoder).decodeFrameOffThread(message)
        : codec.decodeFrame(message);
    if (clear == null) return;
    // Only a frame that arrived sealed and opened: the relay's own frames pass through
    // [RelayCodec.decodeFrame] in the clear — see [lastHeardFromMachineAt].
    if (payload['__e2e'] is Map) _heardFromMachine();
    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;
    _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'];
        final hold = payload['hold'];
        pending.completer.completeError(
          WsRequestFailure(
            responseType: message['type'] as String? ?? 'unknown_result',
            code: '${payload['error']}',
            detail: detail is String && detail.isNotEmpty ? detail : null,
            hold: hold is String && hold.isNotEmpty ? hold : null,
          ),
        );
      } else {
        pending.completer.complete(payload);
      }
      return;
    }
    final eventType = message['type'];
    if (eventType is String && worthLogging(eventType)) {
      appLog.debug('ws', '↓ $eventType ${_summaryOf(eventType, payload)}');
    }
    await onEvent({...message, 'payload': payload});
  }

  /// [payload] for the log line of a [type] frame.
  ///
  /// ⚠️ **The two that come in bursts say which agent and what state, not the whole agent.** A
  /// machine re-sends every agent it has as `agent_synced` each time it reconciles (every five
  /// minutes), and `agent_activity` beats for every agent mid-turn: rendered in full, each was a
  /// whole agent — project, git context, model — turned into 1,200 characters on the UI thread,
  /// four thousand lines a day of it. Which agent, and whether it is up, is what the timeline is
  /// read for.
  static String _summaryOf(String type, Map<String, dynamic> payload) {
    switch (type) {
      case 'agent_synced':
        final agent = payload['agent'];
        if (agent is! Map) break;
        final launch = agent['launch'];
        final terminal = agent['terminal'];
        return '{id: ${agent['id']}, status: ${agent['status']}'
            '${launch is Map ? ', launch: ${launch['state']}' : ''}'
            '${terminal is Map ? ', terminal: ${terminal['available']}' : ''}}';
      case 'agent_activity':
        final activity = payload['activity'];
        return '{agentId: ${payload['agentId']}'
            '${activity is Map ? ', state: ${activity['state']}' : ''}}';
    }
    return summariseForLog(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',
    'terminal_output',
    'terminal_input',
    'terminal_resize',
    'terminal_sync',
    'dial_scroll',
    'dial_focus',
    'ping',
    'pong',
    // Every agent's live chat, pushed to every client selecting the machine
    // (`SessionEvent`/`LiveEvent` in cli/src/lib/normalize.ts). It is what the
    // person typed and what the agent answered — prompts, tool input and
    // output, even pasted images — and it streams several frames a second per
    // agent, each one a synchronous flushed write on the UI thread.
    'user_message',
    'thinking_delta',
    'thinking_title',
    'text_delta',
    'tool_start',
    'tool_end',
    'context_compact',
    'done',
    'turn_started',
    'turn_heartbeat',
    'subagent_finished',
  };

  @visibleForTesting
  static bool worthLogging(String type) => !_unlogged.contains(type);

  /// The requests this phone sends that a machine's daemon counts by who sent them — of `actions` and
  /// `message` in cli/src/lib/productUsageSignals.ts, the ones it sends (never a type it does not:
  /// every machine request named in `lib/` must be sealed, `encrypted_down_types_test.dart`). Over the
  /// relay the phone is a remote app client like the browser, so these carry `usageSurface: 'phone'`
  /// (as a model list a person opened carries `userAction`) and are counted as the phone's. Nothing
  /// else gets the word: not the E2EE handshake, not the relay's own frames. A daemon from before it
  /// reads past it.
  @visibleForTesting
  static const usageMeasuredRequests = {
    'agent_create',
    'agent_resume',
    'agent_restart',
    'agent_retarget',
    'agent_recent',
    'agent_fork',
    'agent_close',
    'agent_delete',
    'session_search',
    'session_tail',
    'dsh_list',
    'dsh_install',
    'dsh_update',
    'dsh_remove',
    'models_list',
    'grid_models_list',
    'browser_open',
    'message',
  };

  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>>();
    final timer = Timer(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.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);
    // Every JSON frame goes out through here — a request, a terminal's `message`, one held in the
    // queue across a redial — so this is the one place the word is added.
    if (usageMeasuredRequests.contains(type)) {
      payload = {...payload, 'usageSurface': 'phone'};
    }
    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;
    _channel = null;
    _sub = null;
    // A parked socket that closed is redialled on the backoff below, which replaces the recheck.
    _parked = false;
    _codec = null;
    _disposePlugin();
    _ready = false;
    // The socket answered by closing, which is an answer — the watchdog is for
    // a socket that says nothing at all. Cancelled here so the redial below is
    // the only one, rather than one of two racing each other.
    _selectWatchdog?.cancel();
    _selectWatchdog = null;
    _rejectPending('WS disconnected');
    if (_closing) {
      onStatus(ConnectionStatus.disconnected);
      return;
    }
    final code = channel.closeCode;
    if (code == 4401) {
      unawaited(_refreshAndReconnect());
      return;
    }
    if (code == 4403) {
      _signOut('SSO environment does not match this backend');
      return;
    }
    _scheduleReconnect();
  }

  Future<void> _refreshAndReconnect() async {
    onStatus(ConnectionStatus.reconnecting);
    try {
      await accessTokenProvider(true, _tokenUsed);
    } on WsCredentialRevoked {
      // As in [connect]: a closed connection has nobody left to sign out.
      if (!_closing) {
        _signOut('Your SSO session expired. Please sign in again.');
      }
      return;
    } catch (_) {
      // The token is still stale, so the next dial refreshes again on its own.
      _scheduleReconnect();
      return;
    }
    if (_closing) return;
    // ⚠️ **Straight back only the first time.** An expired token is renewed and redialled at once
    // — the ordinary case, and nobody should wait for it. But a relay that refuses every token (the
    // backend and the account API disagreeing about a session, say) was asked again the moment
    // each refresh landed: a refresh and a dial per round trip, with no backoff at all, for as
    // long as the app stayed open. A second 4401 before the session came up waits its turn.
    if (_attempt == 0) {
      _attempt++;
      await connect();
    } else {
      _scheduleReconnect();
    }
  }

  void _scheduleReconnect() {
    if (_closing) return;
    _attempt++;
    onStatus(ConnectionStatus.reconnecting);
    _reconnectTimer?.cancel();
    final exponent = min(max(_attempt - 1, 0), 5);
    final delay = Duration(milliseconds: min(30000, 1000 * (1 << exponent)));
    _reconnectTimer = Timer(delay, connect);
  }

  /// Stops waiting out the backoff and dials now — the app has just come back to the foreground,
  /// and the delay that made sense while it was away is pure dead time in front of somebody.
  ///
  /// ⚠️ A no-op when a channel is already open. A phone loses this socket by being backgrounded,
  /// and the OS does not always tell us: coming back to a connection that is in fact alive must not
  /// tear it down to prove it, or every tab switch would cost a fresh handshake.
  ///
  /// ⚠️ A no-op when [_closing]. That flag means somebody decided this connection should stop —
  /// signed out, machine unlinked, 4403 — and resuming the app is not a reason to revive it.
  /// ⚠️ **A no-op while a dial is already in flight, which `_channel` alone does
  /// not tell you.** `_channel` is assigned only after `channel.ready` resolves,
  /// so for the ~800ms a relay dial takes there is a connect running with a null
  /// channel — and this would start a SECOND one. The second overwrote
  /// `_channel`, the first then found itself superseded and bailed out without
  /// sending `machine_select`, and the second never sent one either because
  /// `connect()`'s own `_connecting` guard had turned it away. The socket was
  /// open, the relay was waiting to be told which machine, and neither side ever
  /// spoke: the launch hung on "Connecting to your computer…" indefinitely.
  ///
  /// Reachable on every launch, not just on a real resume: the phone's shell
  /// calls `handleAppResumed` as it mounts, which is a few hundred milliseconds
  /// after the warm start has begun dialling.
  void reconnectNow() {
    // Parked, the socket is open but waiting on a machine the relay called offline
    // ([parkUntilOnline]): somebody arriving is worth asking again, once, as it always was.
    if (_parked) {
      wake('asked for');
      return;
    }
    if (_closing || _connecting || _channel != null) {
      return;
    }
    _reconnectTimer?.cancel();
    _reconnectTimer = null;
    // The clock restarts too. Failures from BEFORE the app went away say nothing about the network
    // it is on now, and without this a phone that had backed off to its 30s ceiling keeps that
    // ceiling against a connection that would succeed immediately.
    _attempt = 0;
    unawaited(connect());
  }

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

  Future<void> close() async {
    _closing = true;
    _ready = false;
    _parked = false;
    _parkedRechecks = 0;
    _codec = null;
    _disposePlugin();
    _reconnectTimer?.cancel();
    _reconnectTimer = null;
    // A watchdog left running would redial a connection somebody deliberately
    // closed — see [_armSelectWatchdog].
    _selectWatchdog?.cancel();
    _selectWatchdog = null;
    _rejectPending('WS closed');
    final sub = _sub;
    _sub = null;
    await sub?.cancel();
    final channel = _channel;
    _channel = null;
    await channel?.sink.close();
    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 || relayCodecs == null) return;
    _reconnectTimer?.cancel();
    // This dials again itself; a pending watchdog would make that two dials.
    _selectWatchdog?.cancel();
    _selectWatchdog = null;
    _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 {
    // Opened from the data channel with this session's keys: the machine's own, as on the relay.
    _conn._heardFromMachine();
    await _conn.onBinaryFrame?.call(localFrame);
  }
}

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