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.

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

import 'package:flutter/foundation.dart';
import 'package:xterm/utils.dart' show traceText;
import 'package:xterm/xterm.dart';

import '../core/crash_log.dart';
import '../logging/typing_trace.dart';
import 'control_chord.dart';
import 'keyframe_write.dart';
import 'screen_snapshot.dart';
import 'terminal_binary.dart';
import 'terminal_input.dart';
import 'terminal_prompt_zone.dart';
import 'terminal_viewport.dart';
import 'utf8_chunks.dart';

typedef TerminalFrameSender = Future<bool> Function(
  String type,
  Map<String, dynamic> payload,
);
typedef TerminalBinarySender = Future<bool> Function(TerminalBinaryFrame frame);

enum TerminalSessionStatus {
  closed,
  opening,
  controlling,
  resyncing,
  takenOver,
  error,
}

/// Who a terminal client is, as it says on `terminal_open` (`client`) and as
/// the daemon repeats to the client it displaces (`terminal_closed.takenBy`) —
/// so the banner can say "Mac mini took control" rather than "another app".
/// Self-declared: every client of a machine is the same account's, and the
/// daemon has no better name for a relayed desktop or a phone. [machineId] is
/// a desktop's own machine in the fleet, so the receiver can show that
/// machine's current name over the one declared.
class TerminalClientDescriptor {
  const TerminalClientDescriptor({
    required this.kind,
    required this.name,
    this.machineId,
  });

  /// `desktop`, `phone`, … — one lower-case word.
  final String kind;
  final String name;
  final String? machineId;

  static const nameMax = 64;

  Map<String, dynamic> toJson() => {
    'kind': kind,
    'name': name,
    if (machineId != null) 'machineId': machineId,
  };

  /// The wire shape, or null for anything else — a daemon that predates the
  /// field sends nothing, and a malformed one is treated the same.
  static TerminalClientDescriptor? fromJson(Object? raw) {
    if (raw is! Map) return null;
    final kind = raw['kind'];
    final name = raw['name'];
    final machineId = raw['machineId'];
    if (kind is! String || !RegExp(r'^[a-z]{1,16}$').hasMatch(kind)) {
      return null;
    }
    if (name is! String) return null;
    final clean = name.replaceAll(RegExp(r'[\u0000-\u001f\u007f]'), ' ').trim();
    if (clean.isEmpty || clean.length > nameMax) return null;
    if (machineId != null &&
        (machineId is! String ||
            !RegExp(r'^[a-f0-9]{16,64}$').hasMatch(machineId))) {
      return null;
    }
    return TerminalClientDescriptor(
      kind: kind,
      name: clean,
      machineId: machineId as String?,
    );
  }

  /// The name to show: the fleet's current name for [machineId] when the
  /// caller knows one, else the name the client declared.
  String label(String? Function(String machineId) resolveMachine) {
    final id = machineId;
    final fleet = id == null ? null : resolveMachine(id)?.trim();
    return fleet == null || fleet.isEmpty ? name : fleet;
  }
}

/// Transient progress for an in-flight [TerminalSession.pasteImage]/[TerminalSession.pasteFile]
/// chunked upload. `bytesWritten` reflects the daemon's own per-chunk ACKs, not bytes merely handed
/// to the local socket.
class UploadProgress {
  const UploadProgress({
    required this.label,
    required this.bytesWritten,
    required this.totalBytes,
  });

  /// The image/file name shown in the overlay — a filename for a file upload, a generic word for
  /// an image (which carries no name of its own).
  final String label;
  final int bytesWritten;
  final int totalBytes;

  double get percent =>
      totalBytes <= 0 ? 0 : (bytesWritten / totalBytes).clamp(0, 1);

  UploadProgress copyWith({int? bytesWritten, int? totalBytes}) =>
      UploadProgress(
        label: label,
        bytesWritten: bytesWritten ?? this.bytesWritten,
        totalBytes: totalBytes ?? this.totalBytes,
      );
}

/// Internal bookkeeping for one in-flight upload — see [TerminalSession._uploadBytes]. Two
/// Completers rather than one, since "the daemon accepted the announcement" and "the transfer is
/// over (however it ended)" are resolved at different points and by different frames.
class _ActiveUpload {
  Completer<bool> beginAccepted = Completer<bool>();
  final Completer<bool> finished = Completer<bool>();

  /// Why the daemon refused the last begin, as it said it.
  String? refusal;

  /// Bytes the daemon has confirmed holding (`terminal_chunked_upload_progress`).
  int acked = 0;
  Completer<void>? _ackWaiter;

  void ack(int bytes) {
    if (bytes <= acked) return;
    acked = bytes;
    final waiter = _ackWaiter;
    _ackWaiter = null;
    waiter?.complete();
  }

  /// Completes when the daemon next confirms more of the upload.
  Future<void> nextAck() => (_ackWaiter ??= Completer<void>()).future;
}

/// What a daemon answers a begin while it still holds an upload for the same pane. This pane runs
/// one upload at a time, so that one is an upload it already gave up on.
const _uploadAlreadyInProgress =
    'an upload is already in progress on this pane';

/// One controller stream for one remote Harness agent.
///
/// Sequence corruption is recovered with bounded resync retries and one clean
/// reopen, and so is a stream that goes quiet without a word ([_sendHeartbeat]).
class TerminalSession extends ChangeNotifier {
  static const protocolVersion = 3;
  static const minCols = 40;
  static const maxCols = 300;
  static const minRows = 12;
  static const maxRows = 120;

  final String machineId;
  final String agentId;
  String agentName;
  final String? engineId;

  /// What the view's scroll mirror knows of this agent's rows — kept by the app
  /// for the agent, not the session, so it outlives every keyframe and every
  /// reopen of it. See [RemoteScrollMemory]. Null keeps it in the view only.
  final RemoteScrollMemory? scrollMemory;
  final TerminalFrameSender send;
  final TerminalBinarySender sendBinary;

  final Duration resyncTimeout;

  /// How long an upload may wait for the daemon to confirm another chunk before it is taken as
  /// lost on the way and given up (see [_uploadBytes]).
  final Duration uploadStallTimeout;

  /// The progress of the last upload given up because it stalled; null once another starts.
  UploadProgress? lastStalledUpload;

  /// Forces a fresh transport dial (see `WsConn.forceReconnect`) — called once when the very first
  /// `terminal_open` never gets a `terminal_ready` back within [resyncTimeout]. Covers the relay
  /// going stale silently (the relayed machine's own Harness process restarted, dropping its E2EE
  /// session without the transport ever closing) so a reconnect looks like a couple of extra seconds
  /// of "attaching" instead of a hang the user has to notice and manually retry.
  /// Force a fresh transport dial for a stream that opened and then went silent.
  ///
  /// Returns whether a reconnect was actually started. False means the caller
  /// declined — the transport is not up yet, so there is nothing to reconnect —
  /// and [_recoverAndResend] then keeps its one-per-open budget rather than
  /// spending it on a no-op.
  final Future<bool> Function()? onOpenStalled;

  /// When the transport last heard from this session's MACHINE — a frame it sealed, not the
  /// relay's own (`WsConn.lastHeardFromMachineAt`). Null hook: the open watchdog keeps its old,
  /// impatient rule (see [_openPatience]), and a quiet stream is always resynced
  /// ([_sendHeartbeat]) rather than its transport redialled.
  final DateTime? Function()? lastHeardFromMachine;

  /// Takes this machine's whole transport down and dials it again, because a stream on it went
  /// quiet and the socket heard nothing from the machine in that time either — see
  /// [_sendHeartbeat]. Returns whether it did; false (the socket is mid-dial already, or cannot
  /// redial) leaves the stream to its own resync.
  ///
  /// ⚠️ **The whole socket, not this stream.** A socket left half-open (Wi-Fi giving way to 4G)
  /// carries every terminal of the machine, and every one of them is as dead as this one. Asking
  /// the daemon for a resync over it would wait out three unanswered tries and an open's patience —
  /// about twenty more seconds — before anything redialled. The caller marks the machine's
  /// sessions lost before the redial (`AppNotifier._redialStaleTransport`), which is what puts
  /// them back, screens kept, once the new socket is up.
  final bool Function()? onTransportSilent;

  /// This client's own introduction, sent with every `terminal_open`; null
  /// for a viewer that never takes control and so is never anyone's taker.
  final TerminalClientDescriptor? client;

  TerminalSession({
    required this.machineId,
    required this.agentId,
    required this.agentName,
    required this.engineId,
    required this.send,
    required this.sendBinary,
    this.client,
    this.onOpenStalled,
    this.lastHeardFromMachine,
    this.onTransportSilent,
    this.resyncTimeout = const Duration(seconds: 4),
    this.uploadStallTimeout = const Duration(seconds: 30),
    this.takeover = true,
    this.scrollMemory,
  }) {
    terminal = _newTerminal();
  }

  /// Whether opening this session may take the terminal away from another app that is driving it.
  ///
  /// True is what an open has always been: the daemon keeps one controller per agent, and the
  /// latest `terminal_open` wins. False is for a session nobody is looking at yet — the phone's
  /// pager attaching the agents a swipe away (see `AppNotifier.warmAgentPane`) — which asks only
  /// for a terminal that is FREE, and is answered `CONTROL_LEASE_HELD` while anyone else holds it.
  ///
  /// Read by every open this session sends, its own recoveries included, so a polite session never
  /// turns into a takeover behind a reconnect. What raises it is a person ARRIVING on the agent —
  /// `AppNotifier.selectAgent`, whether that is the app opening, a swipe landing, a card in the
  /// tabs panel or the "Take control" band — and a refusal that arrives after one asks again,
  /// properly: see the `terminal_error` branch of [handleFrame].
  ///
  /// ⚠️ **An arrival arms ONE open.** Lowered again as soon as an open it armed is answered (the
  /// `terminal_ready` branch of [handleFrame]), because by then the claim has become a lease this
  /// session holds and later opens rest on holding it. Left standing it would outlive the arrival:
  /// a phone in a pocket reconnecting hours later would take the terminal off whoever had it by
  /// then, with nobody having picked the phone up at all.
  ///
  /// ⚠️ Only meaningful against a daemon that advertises `noTakeover`: an older one ignores the key
  /// and takes over regardless. The caller checks — `MachineState.terminalNoTakeoverAvailable`.
  bool takeover;

  /// What the open now in flight asked for — [takeover] as it was when that `terminal_open` was
  /// built. The two differ when a person lands on the page while its polite open is still out.
  bool _openAskedTakeover = true;

  /// Whether the stream this session holds is a WATCHER: it renders the terminal, live, but does
  /// not hold it — another app does, and the daemon refuses anything this one tries to type (see
  /// `terminalStreamManager.ts`). Told by `readOnly` on `terminal_ready`.
  ///
  /// ⚠️ **This is a normal, useful state, not a failure.** The page shows real output and the
  /// header offers "Take control"; pressing it is what asks for the terminal itself. Reset by every
  /// open, so it can never outlive the stream it describes.
  bool watching = false;

  late Terminal terminal;
  TerminalSessionStatus status = TerminalSessionStatus.closed;
  String? streamId;

  /// How this pane's terminal bytes are currently reaching it — one of:
  ///
  ///   'p2p'   direct WebRTC, ICE nominated a direct candidate pair.
  ///   'turn'  WebRTC too, but ICE could only manage a relay pair, so Cloudflare TURN carries it.
  ///   'relay' no data channel at all; the bytes ride the backend WebSocket.
  ///
  /// Only ever set for a `harness link connect`-linked remote machine (the CLI never sends this frame
  /// for a local machine's own terminal, which has no such distinction), and reset alongside [streamId]
  /// so a stale mode can never survive into the next stream.
  String? linkMode;
  String? errorCode;
  String? errorMessage;

  /// Who took this terminal, while [status] is [TerminalSessionStatus.takenOver]
  /// and the daemon said (`terminal_closed.takenBy`); null from an older daemon
  /// or a taker that did not introduce itself — "another app", then.
  TerminalClientDescriptor? takenOverBy;

  /// Who is driving this terminal while this session only [watching] it — the daemon's
  /// `terminal_ready.heldBy`, so the banner can say "MacBook Pro is using this terminal" as the
  /// desktop names a taker. Null when not watching, from an older daemon, or when the holder never
  /// introduced itself — "another app", then.
  TerminalClientDescriptor? heldBy;
  int cols = 80;
  int rows = 24;

  /// Set while an image/file upload is in flight ([pasteImage]/[pasteFile]); `null` otherwise. The
  /// terminal panel's overlay shows a progress pill exactly when this is non-null.
  UploadProgress? uploadProgress;
  _ActiveUpload? _activeUpload;

  String? _openRequestId;
  int? _expectedSeq;

  /// For the typing trace (`typing_trace.dart`, off unless built in): when input last went out, on
  /// the trace clock, for an echo's latency; and the status last traced.
  int _lastInputSentMs = -1 << 30;
  TerminalSessionStatus? _tracedStatus;

  /// For the typing trace: input sends queued and not finished, and when the last one finished.
  int _sendsInFlight = 0;
  int _sendsIdleSinceMs = 0;

  @override
  void notifyListeners() {
    if (kTypingTrace && status != _tracedStatus) {
      typingEvent(
        'session ${agentId.length > 8 ? agentId.substring(0, 8) : agentId}'
        ' ${_tracedStatus?.name ?? '-'} → ${status.name}'
        '${errorCode == null ? '' : ' ($errorCode)'}',
      );
      _tracedStatus = status;
    }
    super.notifyListeners();
  }

  /// Frames dropped in a row as already drawn — see [_alreadyDrawn].
  int _staleInARow = 0;

  /// Past this many already-drawn frames in a row the numbering itself is in doubt, and a resync
  /// settles it rather than dropping frames for ever.
  static const _maxStaleInARow = 64;

  /// Whether this session has drawn anything yet.
  ///
  /// False from the moment the session opens until the machine's first
  /// `terminal_keyframe` lands — the window in which [status] already reads
  /// `controlling` and the emulator's buffer is still empty, so a terminal built
  /// on it paints a blank screen. The phone shows its skeleton across exactly
  /// this gap (`phone/terminal_page.dart`), which is why the flag is public
  /// rather than inferred from [status].
  ///
  /// Reads `_expectedSeq`, the sequence cursor set by that first frame and
  /// cleared by every reopen (see `_armInitialKeyframeWatchdog`, which treats
  /// the same null as "no keyframe arrived").
  bool get hasRenderedFrame => _expectedSeq != null;

  /// Whether [terminal] is a screen KEPT from the last time this agent was open on this phone,
  /// standing in until this attach's first keyframe replaces it. See [seedScreen].
  bool get showingKeptScreen => _showingKeptScreen;
  bool _showingKeptScreen = false;

  /// Something to show: this attach's first frame, or a kept screen standing in for it.
  bool get hasScreen => hasRenderedFrame || _showingKeptScreen;

  /// Whether a new stream of this session is on its way over a screen this session itself drew —
  /// a reopen once its socket was dialled again, a recovery — rather than an empty terminal
  /// waiting for its first keyframe.
  ///
  /// ⚠️ **Why the page needs to know.** An open forgets the stream's sequence ([hasRenderedFrame]
  /// goes false) but keeps the terminal and what is on it (`preserveTerminal`, which every reopen
  /// asks for). Read as "no screen", the page laid its attaching skeleton over that screen: back
  /// from a network switch, the reader saw their terminal vanish into a skeleton and come back a
  /// moment later. The page keeps it up under a spinner instead ([TerminalPage]).
  ///
  /// Only a screen of this session's own streams. A kept screen seeded from another session (the
  /// pager's, see [seedScreen]) is [hasScreen] already, and needs no word while it attaches.
  bool get showsEarlierScreen => !hasScreen && _drewScreen;

  /// Set when a keyframe of this session's lands, and cleared only when an open puts a blank
  /// terminal in its place — see [showsEarlierScreen].
  bool _drewScreen = false;

  /// The stream was lost with its socket ([transportLost]) and waits for the socket to come back
  /// — the one `error` the app repairs by itself, by reopening once the machine's socket is up.
  /// Other errors stay until somebody acts on them.
  bool get lostWithTransport =>
      status == TerminalSessionStatus.error &&
      errorCode == transportLostCode;

  /// The [errorCode] [transportLost] leaves.
  static const transportLostCode = 'TERMINAL_DISCONNECTED';

  /// Shows [kept] — the screen this agent had when the phone last left it — until the live stream's
  /// first keyframe lands and replaces it.
  ///
  /// ⚠️ **What makes switching back to an agent instant.** An attach waits a network round trip for
  /// its keyframe; until then the page showed a skeleton. The kept screen is what the reader last
  /// saw of this agent — seconds or minutes stale, which the header's "Attaching…" says — and the
  /// keyframe that follows replaces it whole.
  ///
  /// Rebound to this session: the kept terminal's callbacks still named the session it came from,
  /// which is gone.
  void seedScreen(Terminal kept) {
    if (hasRenderedFrame || _disposed) return;
    _bindTerminal(kept);
    terminal = kept;
    _showingKeptScreen = true;
    notifyListeners();
  }

  /// [snapshot] — a screen this run kept of this agent ([ScreenSnapshot]) — drawn into a terminal
  /// built like this session's own, and shown as [seedScreen] shows one.
  ///
  /// Never over something better: a screen already on show (a live frame, or the exact terminal
  /// kept from a moment ago) stays.
  void seedSnapshot(ScreenSnapshot snapshot) {
    if (hasScreen || _disposed) return;
    final kept = _newTerminal(bindCallbacks: false)
      ..resize(_clampCols(snapshot.cols), _clampRows(snapshot.rows))
      ..write(snapshot.ansi);
    seedScreen(kept);
  }

  /// This session's screen as a [ScreenSnapshot] to keep, or null with nothing live to keep — a
  /// screen still standing in from a kept one is not news, and keeping it again would only
  /// refresh its date.
  ScreenSnapshot? snapshotForKeeping() {
    if (_disposed || !hasRenderedFrame) return null;
    return ScreenSnapshot.capture(terminal);
  }

  int _lastRenderedSeq = -1;
  int _framesSinceAck = 0;
  int _renderedSinceAckBytes = 0;
  int _inputSeq = 0;

  /// The last `expectedSeq` a TERMINAL_INPUT_INVALID realigned the counter to.
  /// The daemon refuses every in-flight frame it cannot accept, each naming
  /// the SAME expected seq; only the first of those may rewind the counter,
  /// or frames accepted since would be re-sent under numbers already used.
  int? _lastRealignedTo;
  int _resizeSeq = 0;

  /// The size the last `terminal_resize` asked for, and when — until a keyframe of that size
  /// answers it. See [_answerOnItsWay].
  ({int cols, int rows, DateTime at})? _resizeAsked;

  /// Asks for the size again if the keyframe [_answerOnItsWay] waited for never came.
  Timer? _resizeAnswerTimer;

  /// How long a resize's own keyframe may take before a keyframe of another size is believed.
  static const _resizeAnswerWait = Duration(milliseconds: 1500);
  bool _resyncRequested = false;
  int _resyncAttempts = 0;
  int _autoReopenAttempts = 0;
  bool _openStallRecovered = false;

  /// Heartbeats in a row that heard nothing on this stream — see [_sendHeartbeat].
  int _quietBeats = 0;

  /// When this stream was last heard from: its `terminal_ready`, then each frame of it. Set beside
  /// every reset of [_quietBeats], and compared against [lastHeardFromMachine] — never with a
  /// clock's duration — to tell a dead socket from a dead stream ([_transportSilentToo]).
  DateTime? _lastHeardOnStream;

  /// The heartbeats a live stream cannot go without a frame: at least 15s of silence, the
  /// desktop's limit. Four, not three, because the count is of beats that heard nothing, and the
  /// last frame may have landed just before the first of them.
  static const _quietBeatsBeforeResync = 4;

  /// When the open now in flight first left — kept through its resends, so its patience
  /// ([_openPatience]) counts from the first ask rather than starting over at each one.
  DateTime? _openSentAt;

  /// How long an unanswered open waits while its machine is SILENT before [_handleOpenTimeout]
  /// redials — and while the machine is answering other things, the longer [_openSlowPatience].
  static const _openSilentPatience = Duration(seconds: 10);
  static const _openSlowPatience = Duration(seconds: 20);

  /// When this session last reopened itself after an open of this same device took its stream —
  /// see [_takenBySelf]. Spaced by [_ownTakeoverCooldown].
  DateTime? _ownTakeoverReopenedAt;
  static const _ownTakeoverCooldown = Duration(seconds: 30);

  bool _disposed = false;
  int _generation = 0;
  bool _remoteCursorVisible = true;
  bool _cursorBlinkPhaseVisible = true;

  /// Whether the cursor is hidden until the program draws again, because where the screen has it
  /// is not where the program put it.
  ///
  /// ⚠️ **A pane made shorter loses the rows under its cursor.** tmux shrinks a pane by deleting
  /// rows from the bottom up to the cursor before it pushes any into the history (`screen_resize_y`),
  /// and it never asks whether they were empty. A shell's are; Claude Code's classic screen parks
  /// the cursor on its prompt with four rows of its own under it (a border, two status lines, a
  /// blank). The keyboard coming up shrinks the pane and those rows go. When Claude Code's redraw
  /// for the resize follows the keyframe, it puts the cursor back on the prompt within milliseconds
  /// — but when it did not (seen 2026-10-06), the cursor stayed at the bottom row, under the status
  /// lines and against the key bar, until the first key typed made Claude Code draw again. So the
  /// cursor is not shown until the program's next output, whichever of the two that is.
  ///
  /// ⚠️ **Not when the screen the shrink is answered with has the cursor in the prompt** (owner,
  /// 2026-10-23: a keyboard up over a prompt shows the caret blinking in it). There it is where the
  /// program keeps it ([cursorInPrompt]), and hiding it waited on output that had already come:
  /// a redraw that landed before this keyframe left the prompt with no caret until a key was typed.
  bool _cursorAwaitsProgram = false;

  /// The pane height whose shrinking cut rows drawn under the cursor ([_noteCutUnderCursor]), spent
  /// on the keyframe that answers it.
  int? _cutUnderCursorFrom;
  List<int> _utf8Tail = const [];
  final List<int> _inputBytes = [];
  Timer? _heartbeat;
  Timer? _ackTimer;
  Timer? _inputTimer;
  Timer? _resizeTimer;
  DateTime? _lastInputFlushAt;

  /// When typing into this terminal last went out to the machine — null before it ever has. What
  /// the app's agent-list check reads to stay out of the way of somebody typing
  /// (`AppNotifier._typingOn`).
  DateTime? get lastInputAt => _lastInputFlushAt;
  DateTime? _lastResizeFlushAt;
  Timer? _resyncTimer;
  Timer? _scrollTimer;
  bool? _pendingScrollUp;
  int _pendingScrollLines = 0;
  int? _pendingCols;
  int? _pendingRows;
  TerminalViewport? _viewport;
  ({int cols, int rows})? _measuredViewport;
  final Completer<({int cols, int rows})> _viewportSize = Completer();
  Future<void> _renderTail = Future<void>.value();
  Future<void> _inputSendTail = Future<void>.value();

  bool get acceptsInput =>
      status == TerminalSessionStatus.controlling &&
      streamId != null &&
      // A watcher draws the terminal but never types into it — the daemon would refuse the frame
      // anyway, and a keystroke that vanishes reads as a broken pane. See [watching].
      !watching;

  /// Whether this session is the one driving the far terminal right now — the claim [takeover] is
  /// about, held rather than asked for. A session opening or resyncing is on its way to it and is
  /// counted, so an open in flight is not lowered to a polite one behind its own back.
  bool get holdsTerminal =>
      status == TerminalSessionStatus.controlling ||
      status == TerminalSessionStatus.opening ||
      status == TerminalSessionStatus.resyncing;

  /// Grok's CLI declares terminal mouse-tracking (so tmux defers wheel bytes to it, same as any
  /// alt-buffer program) but doesn't correctly handle wheel reports itself — confirmed live: it
  /// echoes the raw SGR escape bytes into its own prompt as literal characters instead of
  /// scrolling. Its alt-buffer scroll gestures route through the daemon's tmux copy-mode
  /// (`sendScrollCommand`/`terminal_scroll`) instead of the raw `mouseInput` path every other
  /// engine already uses correctly.
  bool get scrollViaTmuxCopyMode => engineId == 'grok';

  void renameAgent(String name) {
    final cleanName = name.trim();
    if (cleanName.isEmpty || cleanName == agentName) return;
    agentName = cleanName;
    notifyListeners();
  }

  Future<void> open({
    int initialCols = 80,
    int initialRows = 24,
    bool waitForViewportSize = false,
  }) => _open(
    initialCols: initialCols,
    initialRows: initialRows,
    waitForViewportSize: waitForViewportSize,
    resetRecovery: true,
    preserveTerminal: false,
  );

  /// Reconnect the same agent without discarding its last usable screen.
  /// Input resumes only after the replacement stream's first keyframe.
  ///
  /// [force] reopens a stream that is perfectly alive, which is normally the one thing this must
  /// not do. The case for it is a WATCHER being promoted: it is `controlling` a read-only stream
  /// and a person has just asked for the keyboard, so the only way to get it is a fresh open that
  /// takes the lease. See [watching] and `AppNotifier.selectAgent`.
  Future<void> reopen({bool force = false}) async {
    if (_disposed) return;
    if (!force &&
        (status == TerminalSessionStatus.opening ||
            status == TerminalSessionStatus.controlling ||
            status == TerminalSessionStatus.resyncing)) {
      return;
    }
    await _open(
      initialCols: _measuredViewport?.cols ?? cols,
      initialRows: _measuredViewport?.rows ?? rows,
      waitForViewportSize: false,
      resetRecovery: true,
      preserveTerminal: true,
    );
  }

  bool _isCurrent(int generation) => !_disposed && generation == _generation;

  Future<void> _open({
    required int initialCols,
    required int initialRows,
    required bool waitForViewportSize,
    required bool resetRecovery,
    required bool preserveTerminal,
  }) async {
    if (_disposed) return;
    final generation = ++_generation;
    _cancelTimers();
    _abortActiveUpload();
    _inputBytes.clear();
    _pendingScrollUp = null;
    _pendingScrollLines = 0;
    _lastInputFlushAt = null;
    _lastResizeFlushAt = null;
    _renderTail = Future<void>.value();
    _inputSendTail = Future<void>.value();
    streamId = null;
    linkMode = null;
    watching = false;
    heldBy = null;
    errorCode = null;
    errorMessage = null;
    takenOverBy = null;
    _expectedSeq = null;
    _staleInARow = 0;
    _lastRenderedSeq = -1;
    _framesSinceAck = 0;
    _renderedSinceAckBytes = 0;
    _inputSeq = 0;
    _lastRealignedTo = null;
    _resizeSeq = 0;
    _resizeAsked = null;
    _utf8Tail = const [];
    _remoteCursorVisible = true;
    _cursorBlinkPhaseVisible = true;
    _cursorAwaitsProgram = false;
    _cutUnderCursorFrom = null;
    _resyncRequested = false;
    _resyncAttempts = 0;
    _openSentAt = null;
    if (resetRecovery) {
      _autoReopenAttempts = 0;
      _openStallRecovered = false;
    }
    cols = _clampCols(initialCols);
    rows = _clampRows(initialRows);
    // ⚠️ A kept screen ([seedScreen]) is kept through the open, which is the
    // whole of its job: it is seeded just before the first open, and a fresh
    // terminal here threw it away in the same breath — the page then drew a
    // blank terminal where the reader's last screen should have been, with
    // [hasScreen] telling it not to show the skeleton either.
    final keep = preserveTerminal || _showingKeptScreen;
    if (!keep) {
      terminal = _newTerminal()..resize(cols, rows);
      // A blank terminal: whatever this session drew before is gone with the old one.
      _drewScreen = false;
    }
    status = TerminalSessionStatus.opening;
    _openRequestId =
        'term_${DateTime.now().microsecondsSinceEpoch}_${Random.secure().nextInt(1 << 31)}';
    notifyListeners();

    if (waitForViewportSize) {
      try {
        final measured = await _viewportSize.future.timeout(
          const Duration(seconds: 2),
        );
        if (!_isCurrent(generation) ||
            status != TerminalSessionStatus.opening) {
          return;
        }
        cols = _clampCols(measured.cols);
        rows = _clampRows(measured.rows);
        if (!keep) terminal.resize(cols, rows);
        notifyListeners();
      } on TimeoutException {
        // Keep the conservative fallback when the terminal viewport cannot be
        // measured; the normal resize path will reconcile it after attach.
      }
    }

    if (!_isCurrent(generation) || status != TerminalSessionStatus.opening) {
      return;
    }

    _openAskedTakeover = takeover;
    final openPayload = {
      'protocolVersion': protocolVersion,
      'requestId': _openRequestId,
      'agentId': agentId,
      'cols': cols,
      'rows': rows,
      'compression': const ['zlib', 'none'],
      // Only ever sent as `false`: absent is the takeover every daemon understands — see [takeover].
      if (!takeover) 'takeover': false,
      if (client != null) 'client': client!.toJson(),
    };
    var sent = await send('terminal_open', openPayload);
    if (!_isCurrent(generation) ||
        status != TerminalSessionStatus.opening ||
        streamId != null) {
      return;
    }
    if (!sent) {
      // Most commonly transient: the local transport is mid-reconnect at this exact instant (e.g.
      // right after the app itself just started, or another machine's relay hiccupped a moment ago).
      sent = await _recoverAndResend(openPayload, generation);
    }
    if (!_isCurrent(generation) ||
        status != TerminalSessionStatus.opening ||
        streamId != null) {
      return;
    }
    if (!sent) {
      transportLost('Could not send terminal_open');
      return;
    }
    _openSentAt ??= DateTime.now();
    // An immediate ready/keyframe can arrive before send() resolves. Its
    // watchdog or live stream must not be replaced by an open timeout.
    if (status != TerminalSessionStatus.opening || streamId != null) return;
    // Armed unconditionally (not just on reopen attempts): a `terminal_open` sent through a silently
    // stale relay session never gets ANY reply — nothing else would ever notice or recover from that.
    _resyncTimer?.cancel();
    _resyncTimer = Timer(
      resyncTimeout,
      () => unawaited(_handleOpenTimeout(openPayload, generation)),
    );
  }

  /// The armed-on-every-open watchdog fired: no `terminal_ready` arrived in time even though the send
  /// itself succeeded — the relay session was silently stale (ciphertext for a dead E2EE session gets
  /// dropped, not rejected). Force a fresh dial and resend the SAME open request (same `requestId`, so
  /// a late reply for the original still matches) before giving up.
  ///
  /// Unless the machine is only SLOW — see [_openPatience], which this waits out first.
  Future<void> _handleOpenTimeout(
    Map<String, dynamic> openPayload,
    int generation,
  ) async {
    if (!_isCurrent(generation) ||
        status != TerminalSessionStatus.opening ||
        streamId != null) {
      return;
    }
    final patience = _openPatience();
    if (patience != null) {
      _resyncTimer?.cancel();
      _resyncTimer = Timer(
        patience,
        () => unawaited(_handleOpenTimeout(openPayload, generation)),
      );
      return;
    }
    final sent = await _recoverAndResend(openPayload, generation);
    if (!_isCurrent(generation) ||
        status != TerminalSessionStatus.opening ||
        streamId != null) {
      return;
    }
    if (sent) {
      _resyncTimer?.cancel();
      _resyncTimer = Timer(
        resyncTimeout,
        () => unawaited(_handleOpenTimeout(openPayload, generation)),
      );
      return;
    }
    _fail(
      'TERMINAL_RESYNC_TIMEOUT',
      _autoReopenAttempts > 0
          ? 'Terminal did not reopen after resync failed.'
          : 'Harness did not respond — check your connection.',
    );
  }

  /// How much longer the open in flight may go unanswered before [_handleOpenTimeout] treats its
  /// session as stale and redials — null once it has waited long enough, or when there is no way to
  /// tell ([lastHeardFromMachine] absent, or the open not sent yet): the old rule, no patience.
  ///
  /// ⚠️ **Why the watchdog waits now (owner, 2026-10-01).** It redialled four seconds after any
  /// unanswered open, on the theory that only a session that went stale behind a live relay stays
  /// that quiet. A launch measured on a busy machine said otherwise: the relay was slow — 5 to 7
  /// seconds each way while it carried the launch's other traffic — and the redial made it worse
  /// every time. It threw away every request in flight, started a fresh handshake and agent list
  /// on top of what was queued, and resent the open, which then reached the machine TWICE (the
  /// first copy had been on its way all along); the later copy took the terminal off the earlier
  /// one and the screen sat taken over by its own phone. The terminal that answered in about 8
  /// seconds was shown at 22, or not at all.
  ///
  /// So the redial waits for evidence: a machine that has sealed ANY frame to this connection since
  /// the open left is alive and only behind, and gets [_openSlowPatience]; one that has said
  /// nothing at all gets [_openSilentPatience] — still the stale session's cure, ten seconds in
  /// rather than four. Counted from the open's first send, so a resend does not start the clock
  /// again, and in steps no longer than [resyncTimeout].
  Duration? _openPatience() {
    final sentAt = _openSentAt;
    final heard = lastHeardFromMachine;
    if (sentAt == null || heard == null) return null;
    final lastHeard = heard();
    final answering = lastHeard != null && lastHeard.isAfter(sentAt);
    final limit = answering ? _openSlowPatience : _openSilentPatience;
    final left = limit - DateTime.now().difference(sentAt);
    if (left <= Duration.zero) return null;
    return left < resyncTimeout ? left : resyncTimeout;
  }

  /// Shared recovery for both open-failure paths (`send()` itself failing, and `terminal_ready` never
  /// arriving): force a fresh transport dial (see `WsConn.forceReconnect`), then poll-resend — a forced
  /// relay redial is a REAL network round trip (fresh E2EE handshake for a relayed machine), and
  /// `forceReconnect()` resolving only means the redial STARTED, not that the transport is ready again.
  /// Bounded by [_openStallRecovered] (one forced reconnect per open) and a fixed poll budget, so a
  /// persistently broken connection still fails closed instead of retrying forever.
  Future<bool> _recoverAndResend(
    Map<String, dynamic> openPayload,
    int generation,
  ) async {
    final recover = onOpenStalled;
    if (_openStallRecovered || recover == null) return false;
    var reconnected = false;
    try {
      reconnected = await recover();
    } catch (_) {
      // A forced reconnect that threw still started one; poll for readiness.
      reconnected = true;
    }
    // ⚠️ **The one forced reconnect per open is spent only if one happened.**
    // The hook declines while the transport is still connecting — there is
    // nothing to recover there, and redialling would destroy the dial in
    // progress (see `onOpenStalled` in `app_state.dart`). Marking the budget
    // spent on a decline would leave a stream that later stalls for real with no
    // recovery left, which is the failure this whole path exists to handle.
    if (!reconnected) return false;
    _openStallRecovered = true;
    for (var attempt = 0; attempt < 10; attempt++) {
      if (!_isCurrent(generation) ||
          status != TerminalSessionStatus.opening ||
          streamId != null) {
        return false;
      }
      if (await send('terminal_open', openPayload)) return true;
      await Future.delayed(const Duration(milliseconds: 300));
    }
    return false;
  }

  /// Returns true when [type] belongs to this session's protocol.
  Future<bool> handleFrame(String type, Map<String, dynamic> payload) async {
    if (_disposed) return false;
    switch (type) {
      case 'terminal_ready':
        // ⚠️ **A reply to the open this session gave up waiting for is still taken (owner,
        // 2026-10-01).** [_handleOpenTimeout] ends an open nobody answered in `error`, and the reply
        // used to be dropped when it came after all — on a slow relay it does, seconds later — so
        // the stream the machine had just opened was left running for nobody while this session
        // asked for another. Only for THAT open ([_openRequestId] is the last one sent) and only
        // while nothing has replaced it: a reopen since has a new request id, and the reply to the
        // old one is then rightly ignored.
        final lateReply =
            status == TerminalSessionStatus.error &&
            errorCode == 'TERMINAL_RESYNC_TIMEOUT' &&
            streamId == null;
        if ((status != TerminalSessionStatus.opening && !lateReply) ||
            payload['requestId'] != _openRequestId ||
            payload['agentId'] != agentId ||
            payload['protocolVersion'] != protocolVersion) {
          return true;
        }
        if (lateReply) {
          status = TerminalSessionStatus.opening;
          errorCode = null;
          errorMessage = null;
        }
        streamId = payload['streamId'] as String?;
        if (streamId == null || streamId!.isEmpty) {
          _fail('TERMINAL_READY_INVALID', 'Harness returned no stream id');
          return true;
        }
        // The daemon's answer to a polite open on a terminal somebody else holds: it opened, it
        // renders, and it may not type. See [watching].
        watching = payload['readOnly'] == true;
        heldBy = watching
            ? TerminalClientDescriptor.fromJson(payload['heldBy'])
            : null;
        // ⚠️ **The press is spent here.** A takeover was asked for and ANSWERED, so the claim it
        // was making is now a lease this session holds — and holding it is what later opens should
        // rest on, not the press that won it.
        //
        // Left standing, the flag outlived the moment: an app backgrounded for hours would come
        // back through a reconnect and take the terminal again, off whoever was working in it by
        // then, with nobody having asked for it since the morning. That is exactly the silent
        // takeover a press is supposed to be the only cause of. See [takeover].
        //
        // Nothing is lost by lowering it. A reconnect that finds the terminal still free opens
        // normally; one that finds it taken is refused and lands on [takenOver], where the button
        // is — a person asks again, which is the whole rule.
        if (!watching) takeover = false;
        _resyncTimer?.cancel();
        _resyncTimer = null;
        // ⚠️ Cancelled first: a second `terminal_ready` for this same open is
        // real — the open-timeout path resends the SAME request, so a reply
        // that was only slow and the reply to the resend both match while no
        // screen has landed yet. Overwritten, the first timer ran on unowned
        // for the life of the process, beating twice as often and still
        // beating after [dispose].
        _heartbeat?.cancel();
        _quietBeats = 0;
        _lastHeardOnStream = DateTime.now();
        _heartbeat = Timer.periodic(
          const Duration(seconds: 5),
          (_) => unawaited(_sendHeartbeat()),
        );
        _armInitialKeyframeWatchdog();
        return true;
      case 'terminal_keyframe':
      case 'terminal_output':
        _fail(
          'TERMINAL_BINARY_REQUIRED',
          'Harness sent terminal bulk data as JSON',
        );
        return true;
      case 'terminal_chunked_upload_begin_result':
        if (!_matchesStream(payload)) return true;
        final accepted = payload['accepted'] == true;
        if (_activeUpload?.beginAccepted.isCompleted == false) {
          _activeUpload!.refusal = accepted
              ? null
              : payload['reason']?.toString();
          _activeUpload!.beginAccepted.complete(accepted);
        }
        // A stream the daemon no longer has takes no input and no upload, and nothing else says
        // so: the picture fails, and the terminal sat on as if live. Its screen is kept and it is
        // opened once more — the desktop's recovery — without sending the picture again. Older
        // daemons give only the reason's words.
        if (!accepted &&
            (payload['code'] == 'TERMINAL_STREAM_NOT_FOUND' ||
                payload['reason'] ==
                    'no live terminal stream for this pane (reopen it and try again)')) {
          await _recoverByReopen(reason: 'TERMINAL_STREAM_NOT_FOUND');
        }
        return true;
      case 'terminal_chunked_upload_progress':
        if (!_matchesStream(payload)) return true;
        final bytesWritten = (payload['bytesWritten'] as num?)?.toInt();
        final totalBytes = (payload['totalBytes'] as num?)?.toInt();
        if (bytesWritten != null) _activeUpload?.ack(bytesWritten);
        if (bytesWritten != null &&
            totalBytes != null &&
            uploadProgress != null) {
          uploadProgress = uploadProgress!.copyWith(
            bytesWritten: bytesWritten,
            totalBytes: totalBytes,
          );
          notifyListeners();
        }
        return true;
      case 'terminal_paste_image_result':
      case 'terminal_paste_file_result':
        if (!_matchesStream(payload)) return true;
        if (_activeUpload?.finished.isCompleted == false) {
          _activeUpload!.finished.complete(true);
        }
        return true;
      case 'terminal_link_mode':
        if (!_matchesStream(payload)) return true;
        final mode = payload['mode']?.toString();
        // Allow-list, not a blind assign: an older CLI knows only 'p2p'/'relay', a newer one may learn
        // values this build cannot draw, and either way linkMode must stay something the header has an
        // icon for. An unknown value leaves the previous state alone rather than blanking it.
        if (mode == 'p2p' || mode == 'turn' || mode == 'relay') {
          linkMode = mode;
          notifyListeners();
        }
        return true;
      case 'terminal_closed':
        if (!_matchesStream(payload)) return true;
        _generation++;
        _cancelTimers();
        final code = payload['code']?.toString();
        final takenOver = code == 'TERMINAL_TAKEN_OVER';
        status = takenOver
            ? TerminalSessionStatus.takenOver
            : TerminalSessionStatus.closed;
        errorCode = takenOver ? code : null;
        takenOverBy = takenOver
            ? TerminalClientDescriptor.fromJson(payload['takenBy'])
            : null;
        heldBy = null;
        errorMessage = takenOver
            ? (takenOverBy == null
                  ? 'Another client connected to this terminal.'
                  : '${takenOverBy!.name} connected to this terminal.')
            : payload['reason']?.toString();
        streamId = null;
        linkMode = null;
        _abortActiveUpload();
        notifyListeners();
        if (takenOver && _takenBySelf(takenOverBy)) _reopenAfterOwnTakeover();
        return true;
      case 'terminal_error':
        final errorStream = payload['streamId'];
        final errorRequest = payload['requestId'];
        if (errorStream != null && errorStream != streamId) return true;
        if (errorRequest != null && errorRequest != _openRequestId) return true;
        final errorCode = payload['code']?.toString() ?? 'TERMINAL_ERROR';
        // A rejected paste (empty, or over the daemon's sanity ceiling) never touched tmux — the
        // stream itself is completely fine, so this must not freeze it the way a real transport/
        // protocol failure does. `debugPrint` only: there is no dedicated per-action failure surface
        // to show the user something better than silence, and silence beats losing the terminal.
        // A malformed upload chunk (bad seq/size) is the same shape of non-event for the same
        // reason — nothing it describes ever reached tmux either.
        if (errorCode == 'TERMINAL_PASTE_INVALID' ||
            errorCode == 'TERMINAL_CHUNKED_UPLOAD_INVALID') {
          _abortActiveUpload();
          notifyListeners();
          debugPrint(
            'TerminalSession: paste rejected: ${payload['message'] ?? errorCode}',
          );
          return true;
        }
        // A refused INPUT frame never reached tmux either: the stream is fine, only our counter
        // disagrees with the daemon's (a frame dropped on this side while resyncing, say). A daemon
        // that says what it expects gets realigned in place — the refused keystroke is gone either
        // way, and the person retypes it — and an older one that does not gets a fresh stream. What
        // it must NOT get is the frozen pane this used to be: every later keystroke was refused too,
        // and a working terminal read as a dead one.
        if (errorCode == 'TERMINAL_INPUT_INVALID') {
          final expected = payload['expectedSeq'];
          if (expected is int && expected >= 0) {
            // A stale duplicate: the daemon refused several in-flight frames
            // at once, each naming this same seq, and the counter has since
            // moved on from it and been accepted. Rewinding again would put the
            // next keystroke under a number the daemon has already taken.
            // Safe because its expectation only ever grows and its errors
            // arrive in order — a NEW gap always names a larger seq.
            if (expected == _lastRealignedTo) return true;
            _lastRealignedTo = expected;
            _inputSeq = expected;
            // Bytes still waiting in the coalescer are kept: they are numbered
            // on the way out, after this, so they go under the right seq.
            debugPrint(
              'TerminalSession: input seq realigned to $expected '
              '(${payload['reason'] ?? payload['message'] ?? 'no reason given'})',
            );
            notifyListeners();
          } else {
            _inputBytes.clear();
            unawaited(_recoverByReopen(reason: 'TERMINAL_INPUT_INVALID'));
          }
          return true;
        }
        // A polite open, refused: another app is driving this terminal and this session asked not
        // to take it from them — see [takeover]. Not a failure, and it must not read as one:
        // `error` is what the notifier's reattach sweep retries, which would ask again for as long
        // as the other app stayed. `takenOver` is the state that already means "someone else has
        // it, and only a person gets it back".
        //
        // Only for an open that ASKED to be polite. The daemon also answers this code to an
        // ordinary open that lost a race for the placement, and that one keeps the retry it has
        // always had, below.
        if (errorCode == 'CONTROL_LEASE_HELD' && !_openAskedTakeover) {
          if (takeover) {
            // Landed on while that open was still out: somebody is looking at this page now, so
            // it asks again the way a page being read always has.
            unawaited(
              _open(
                initialCols: _measuredViewport?.cols ?? cols,
                initialRows: _measuredViewport?.rows ?? rows,
                waitForViewportSize: false,
                resetRecovery: true,
                preserveTerminal: true,
              ),
            );
          } else {
            _heldElsewhere(errorCode);
          }
          return true;
        }
        // A genuine mid-transfer failure (the daemon couldn't write the clipboard/disk, or the
        // pty write itself failed) IS treated like a real transport/protocol failure — same as
        // TERMINAL_PASTE_FAILED already is, since it may mean the pty is in an unknown state.
        // `_fail` itself resolves any in-flight upload (see `_abortActiveUpload`), so there is
        // nothing extra to do here for TERMINAL_PASTE_IMAGE_FAILED/TERMINAL_PASTE_FILE_FAILED.
        //
        // The daemon no longer holds this stream (it closed it while its link to the backend was
        // down, say) and said so because this session asked (`reportMissing`). Reopen in place now
        // rather than waiting out the heartbeat silence and three resyncs (2026-10-16).
        if (errorCode == 'TERMINAL_STREAM_NOT_FOUND') {
          unawaited(_recoverByReopen(reason: 'TERMINAL_STREAM_NOT_FOUND'));
          return true;
        }
        _fail(errorCode, payload['message']?.toString());
        return true;
      case 'terminal_transport_error':
        transportLost(
          payload['code']?.toString() ?? 'Terminal relay rejected the frame',
        );
        return true;
      default:
        return false;
    }
  }

  Future<void> handleBinary(TerminalBinaryFrame frame) async {
    if (_disposed || frame.streamId != streamId) return;
    // Heard from: whatever the frame turns out to be, the stream is alive — see [_sendHeartbeat].
    _quietBeats = 0;
    _lastHeardOnStream = DateTime.now();
    final generation = _generation;
    // How long the frame waited behind the ones before it to be drawn: a keyframe that reached this
    // session 0.64 s late was drawn 0.37 s later still (iPhone 14, 2026-10-19).
    final queuedMs = kTypingTrace ? typingNowMs() : 0;
    _renderTail = _renderTail
        .then((_) async {
          if (!_isCurrent(generation) || frame.streamId != streamId) return;
          if (kTypingTrace) {
            final waited = typingNowMs() - queuedMs;
            final line =
                'render ${frame.kind.name} seq=${frame.seq} waited ${waited}ms behind earlier frames';
            if (frame.kind == TerminalBinaryKind.keyframe) {
              typingEvent(line);
            } else if (waited >= 10) {
              typingNote(line);
            }
          }
          final bytes = _decodeBinaryBytes(frame);
          if (bytes == null) {
            await _requestResync('TERMINAL_BINARY_DECODE_FAILED');
            return;
          }
          if (frame.kind == TerminalBinaryKind.keyframe) {
            if (kTypingTrace) {
              typingEvent(
                'out KEYFRAME ${agentId.length > 8 ? agentId.substring(0, 8) : agentId}'
                ' seq=${frame.seq} ${frame.cols}×${frame.rows}'
                ' ${bytes.length}B (status=${status.name}) — replaces the terminal',
              );
            }
            await _applyKeyframe(frame, bytes, generation);
            return;
          }
          if (frame.kind == TerminalBinaryKind.sync) {
            if (status == TerminalSessionStatus.resyncing) return;
            if (_alreadyDrawn(frame)) return;
            if (_expectedSeq == null || frame.seq != _expectedSeq) {
              await _requestResync('TERMINAL_SEQUENCE_GAP');
              return;
            }
            _expectedSeq = frame.seq + 1;
            _lastRenderedSeq = frame.seq;
            _markForAck(0);
            return;
          }
          if (frame.kind != TerminalBinaryKind.output ||
              status == TerminalSessionStatus.resyncing) {
            if (kTypingTrace && frame.kind == TerminalBinaryKind.output) {
              typingEvent(
                'out seq=${frame.seq} ${bytes.length}B DROPPED — resyncing',
              );
            }
            return;
          }
          if (_alreadyDrawn(frame)) {
            if (kTypingTrace) {
              typingEvent(
                'out seq=${frame.seq} ${bytes.length}B DROPPED — already drawn'
                ' (expected $_expectedSeq)',
              );
            }
            return;
          }
          if (_expectedSeq == null || frame.seq != _expectedSeq) {
            if (kTypingTrace) {
              typingEvent(
                'out seq=${frame.seq} GAP (expected $_expectedSeq) → resync',
              );
            }
            await _requestResync('TERMINAL_SEQUENCE_GAP');
            return;
          }
          if (kTypingTrace) {
            final since = typingNowMs() - _lastInputSentMs;
            typingNote(
              'out seq=${frame.seq} ${bytes.length}B'
              '${since < 5000 ? ' +${since}ms after the last send' : ''}',
            );
          }
          if (!_writeBytes(bytes)) {
            await _requestResync('TERMINAL_OUTPUT_DECODE_FAILED');
            return;
          }
          _expectedSeq = frame.seq + 1;
          _lastRenderedSeq = frame.seq;
          _markForAck(bytes.length);
        })
        .catchError((Object error, StackTrace stackTrace) async {
          if (!_isCurrent(generation)) return;
          debugPrint(
            '[terminal-session] renderer failed for '
            '$machineId/$agentId: $error\n$stackTrace',
          );
          CrashLog.record(error, stackTrace, context: 'renderer');
          await onRendererFailure();
        });
    await _renderTail;
  }

  /// Recover from an exception thrown while drawing a frame.
  ///
  /// A renderer fault is LOCAL, and calling it a lost transport was the wrong
  /// diagnosis: the bytes arrived intact and something in drawing them threw.
  /// That froze the tile behind a manual "attach new stream" for a fault the
  /// ordinary resync ladder already clears — it is what the decode failures in
  /// [handleBinary] do — and the ladder is bounded (resync x3, reopen x1, then
  /// a real failure), so a renderer that throws every time still ends up
  /// reporting itself rather than retrying for ever.
  ///
  /// A parser exception can leave the current buffer partially mutated, so the
  /// emulator is not reused: the resync's keyframe is authoritative and
  /// [handleBinary] builds a fresh Terminal for it. Nothing more is written to
  /// the damaged one in the meantime, because the output branch drops frames
  /// while the status is `resyncing`.
  @visibleForTesting
  Future<void> onRendererFailure() =>
      _requestResync('TERMINAL_RENDERER_FAILED');

  /// Whether [frame] is numbered below the next one expected — already part of the screen, since
  /// the keyframe that moved [_expectedSeq] past it was drawn after it was sent.
  ///
  /// ⚠️ **Not a gap, and not worth a redraw.** It is what the relay delivers late once a stream has
  /// moved onto the data channel: output the machine put on the relay before it flipped, landing
  /// after the channel's keyframe (`TerminalP2pPlugin._lateOnRelay`). Read as a sequence gap, each
  /// one cost a resync — a fresh keyframe and the whole screen drawn again, right as the stream had
  /// just been moved for speed.
  ///
  /// Bounded ([_maxStaleInARow]): a run of them longer than any migration leaves is taken for
  /// numbering gone wrong, and falls through to the gap check's resync.
  bool _alreadyDrawn(TerminalBinaryFrame frame) {
    final expected = _expectedSeq;
    if (expected == null || frame.seq >= expected) {
      _staleInARow = 0;
      return false;
    }
    return ++_staleInARow <= _maxStaleInARow;
  }

  Uint8List? _decodeBinaryBytes(TerminalBinaryFrame frame) {
    try {
      return frame.compressed
          ? Uint8List.fromList(ZLibDecoder().convert(frame.bytes))
          : frame.bytes;
    } catch (_) {
      return null;
    }
  }

  void attachViewport(TerminalViewport viewport) {
    _viewport = viewport;
  }

  /// Reports the first grid measured from the actual Flutter terminal render
  /// object. This is deliberately separate from [Terminal.onResize]: creating
  /// a terminal at the conservative 80x24 fallback also fires onResize and
  /// must not be mistaken for a measured viewport.
  void reportViewport(int width, int height) {
    final measured = (cols: _clampCols(width), rows: _clampRows(height));
    _measuredViewport = measured;
    if (_viewportSize.isCompleted) return;
    _viewportSize.complete(measured);
  }

  void detachViewport(TerminalViewport viewport) {
    if (identical(_viewport, viewport)) _viewport = null;
  }

  /// Empties the prompt being typed into, all of it: Ctrl+K until nothing is
  /// after the cursor, then Ctrl+U until nothing is before it — what a shell
  /// and both agents' prompts read as "kill the line" — and the keyboard's own
  /// buffer with it (see [TerminalViewport.clearInputBuffer]).
  ///
  /// ⚠️ **One kill is one ROW, not the prompt.** Claude Code's Ctrl+U deletes
  /// back to the start of the row as WRAPPED, and at a row's start only the
  /// newline before it; Ctrl+K likewise forwards. A phone's pane is about
  /// forty columns wide, so two pastes already wrap, and a single Ctrl+E,
  /// Ctrl+U left all but the last row behind. So each is sent twice per row
  /// the prompt can take on screen ([promptRowsBound]): a kill past the
  /// prompt's ends does nothing.
  ///
  /// ⚠️ Not Ctrl+C: to Claude Code an empty prompt's Ctrl+C is the first half
  /// of quitting.
  void clearPrompt() {
    if (!acceptsInput) return;
    final kills = 2 * promptRowsBound(terminal.buffer);
    for (var i = 0; i < kills; i++) {
      terminal.keyInput(TerminalKey.keyK, ctrl: true);
    }
    for (var i = 0; i < kills; i++) {
      terminal.keyInput(TerminalKey.keyU, ctrl: true);
    }
    resetInputBuffer();
  }

  /// Empties the keyboard's own buffer after a key sent from outside it — Tab
  /// completing a word, a `/` typed from the key strip — changed the prompt
  /// behind its back. See [TerminalViewport.clearInputBuffer].
  void resetInputBuffer() => _viewport?.clearInputBuffer();

  /// Changes only the local paint phase of the cursor. Incoming terminal data
  /// is always parsed against [_remoteCursorVisible], so blinking cannot turn
  /// a remote DECTCEM hide/show command into terminal input or corrupt its
  /// authoritative cursor state.
  void setCursorBlinkPhase(bool visible) {
    if (_cursorBlinkPhaseVisible == visible) return;
    _cursorBlinkPhaseVisible = visible;
    _applyCursorVisibility();
  }

  /// Bumped once per chunk of output written — what a reader scrolled up in the history watches to
  /// know there is something newer below. Its own notifier, not this session's: output is the most
  /// frequent event there is, and nothing else here should rebuild for it.
  final ValueNotifier<int> outputTicks = ValueNotifier(0);

  void _writeTerminalText(String text) {
    outputTicks.value++;
    terminal.setCursorVisibleMode(_remoteCursorVisible);
    terminal.write(text);
    _remoteCursorVisible = terminal.cursorVisibleMode;
    if (_cursorAwaitsProgram) {
      _cursorAwaitsProgram = false;
      if (kTypingTrace) typingEvent('cursor: shown — the program drew again');
    }
    _applyCursorVisibility();
  }

  void _applyCursorVisibility() {
    terminal.setCursorVisibleMode(
      _remoteCursorVisible && _cursorBlinkPhaseVisible && !_cursorAwaitsProgram,
    );
  }

  /// Notes whether making the pane [nextRows] high cuts rows drawn under the cursor, for the
  /// keyframe that answers it ([_cutUnderCursorFrom]). Read only while the emulator still has the
  /// pane's height — the emulator's own shrink deletes the same rows tmux will. Only ever set here,
  /// never cleared: a later step of the same shrink reads an emulator that has lost them already.
  void _noteCutUnderCursor(int nextRows) {
    if (nextRows < rows &&
        terminal.viewHeight == rows &&
        !_showingKeptScreen &&
        !terminal.isUsingAltBuffer &&
        _drawnUnderCursor()) {
      _cutUnderCursorFrom = rows;
    }
  }

  /// Whether a row under the cursor has anything drawn on it — what tmux deletes first when the
  /// pane is made shorter. See [_cursorAwaitsProgram].
  bool _drawnUnderCursor() {
    final buffer = terminal.buffer;
    final top = buffer.scrollBack;
    for (var y = buffer.cursorY + 1; y < terminal.viewHeight; y++) {
      final index = top + y;
      if (index < 0 || index >= buffer.lines.length) break;
      if (buffer.lines[index].getText().trim().isNotEmpty) return true;
    }
    return false;
  }

  bool _writeBytes(List<int> bytes) {
    // Most packets end on a scalar boundary. Decode their existing byte view
    // directly; only a split UTF-8 scalar needs a joined buffer.
    final combined = _utf8Tail.isEmpty ? bytes : <int>[..._utf8Tail, ...bytes];
    final decoded = decodeUtf8Chunk(combined);
    if (kTypingTrace && decoded.text.contains('\x1b[?2026')) {
      // Whether the program brackets its frames for synchronized output — see
      // `Terminal.setSynchronizedOutputMode`. A mark split across two packets
      // goes uncounted; this is a trace.
      for (final mark in _synchronizedOutputMark.allMatches(decoded.text)) {
        typingCount(mark.group(1) == 'h' ? 'sync.begin' : 'sync.end');
      }
    }
    if (decoded.text.isNotEmpty) _writeTerminalText(decoded.text);
    _utf8Tail = decoded.tail;
    return true;
  }

  static final _synchronizedOutputMark = RegExp(r'\x1b\[\?2026([hl])');

  /// A keyframe: the stream's whole screen and its history, which replaces the emulator outright.
  /// Published whole and at once — see [writeKeyframeInSlices] for how a large one is parsed.
  Future<void> _applyKeyframe(
    TerminalBinaryFrame frame,
    Uint8List bytes,
    int generation,
  ) async {
    final nextCols = frame.cols;
    final nextRows = frame.rows;
    if (nextCols == null || nextRows == null) {
      await _requestResync('TERMINAL_KEYFRAME_INVALID');
      return;
    }
    // Publish a complete screen atomically. A damaged snapshot must
    // leave the retained screen available while resync recovers.
    final decoded = decodeUtf8Chunk(_prepareKeyframeBytes(bytes));
    final replacement = _newTerminal(bindCallbacks: false)
      ..resize(_clampCols(nextCols), _clampRows(nextRows));
    if (decoded.text.length <= keyframeSliceChars) {
      replacement.write(decoded.text);
    } else if (!await writeKeyframeInSlices(
      replacement,
      decoded.text,
      stillWanted: () => _isCurrent(generation) && frame.streamId == streamId,
    )) {
      // Closed, reopened or taken over while it parsed: whoever moved
      // the stream on owns what is shown now, and this screen is dropped.
      return;
    }
    final cutFrom = _cutUnderCursorFrom;
    if (cutFrom != null && _clampRows(nextRows) < cutFrom) {
      // The answer to the shrink that cut rows under the cursor. A keyframe at the old size, sent
      // before the resize landed, leaves it for the one that is.
      _cutUnderCursorFrom = null;
      if (!replacement.isUsingAltBuffer &&
          !_cursorAwaitsProgram &&
          !cursorInPrompt(replacement.buffer, engineId)) {
        _cursorAwaitsProgram = true;
        if (kTypingTrace) {
          typingEvent(
            'cursor: hidden — the pane shrank from $cutFrom rows through rows'
            ' drawn under it, so it waits for the program to draw again',
          );
        }
      }
    }
    _bindTerminal(replacement);
    terminal = replacement;
    _showingKeptScreen = false;
    _drewScreen = true;
    cols = _clampCols(nextCols);
    rows = _clampRows(nextRows);
    _utf8Tail = decoded.tail;
    _remoteCursorVisible = terminal.cursorVisibleMode;
    _cursorBlinkPhaseVisible = true;
    // A keyframe is the program's screen, not a redraw by it: a cursor held stays held through it.
    _applyCursorVisibility();
    _expectedSeq = frame.seq + 1;
    _staleInARow = 0;
    _lastRenderedSeq = frame.seq;
    _resyncRequested = false;
    _resyncAttempts = 0;
    _autoReopenAttempts = 0;
    errorCode = null;
    errorMessage = null;
    takenOverBy = null;
    _resyncTimer?.cancel();
    _resyncTimer = null;
    status = TerminalSessionStatus.controlling;
    _markForAck(bytes.length);
    notifyListeners();
    final measured = _measuredViewport;
    if (measured != null) {
      _pendingCols = measured.cols;
      _pendingRows = measured.rows;
    }
    // Asked first, and always: a keyframe that answers the resize out is what clears it.
    if (_answerOnItsWay()) return;
    if (_pendingCols != null && _pendingRows != null) {
      unawaited(_flushResize());
    }
  }

  /// Whether the keyframe just drawn predates the resize still out — the size it asked for is still
  /// the one wanted, and that resize's own keyframe is on its way ([_resizeStillComing]).
  ///
  /// ⚠️ **Not asked again, which is what this used to do.** The machine answers a resize with a
  /// keyframe, but one it had already put on the wire at the OLD size lands first. Read as the
  /// size having slipped, it sent the same resize again — and got a third keyframe for it. Every
  /// keyboard raised was measured at three keyframes and two resizes (2026-10-05): three times the
  /// emulator replaced and the screen parsed and drawn whole, the keyboard's buffer emptied each
  /// time, right as somebody starts typing.
  bool _answerOnItsWay() {
    final asked = _resizeAsked;
    if (asked == null) return false;
    if (asked.cols == cols && asked.rows == rows) {
      // This keyframe IS the answer.
      _resizeAsked = null;
      _resizeAnswerTimer?.cancel();
      _resizeAnswerTimer = null;
      return false;
    }
    final pendingCols = _pendingCols, pendingRows = _pendingRows;
    if (pendingCols == null ||
        pendingRows == null ||
        !_resizeStillComing(pendingCols, pendingRows)) {
      return false;
    }
    if (kTypingTrace) {
      typingEvent(
        'resize: keyframe ${cols}x$rows predates the ${asked.cols}x${asked.rows}'
        ' still coming — not asked again',
      );
    }
    _pendingCols = null;
    _pendingRows = null;
    return true;
  }

  /// Whether a resize to [nextCols]×[nextRows] is out already and its keyframe not overdue — and so
  /// not to be asked for again ([_answerOnItsWay]; and in [_flushResize], for the emulator laid out
  /// at a stale keyframe's size resizing itself back). Held for [_resizeAnswerWait] at most: an
  /// answer that never comes is asked for again then.
  bool _resizeStillComing(int nextCols, int nextRows) {
    final asked = _resizeAsked;
    if (asked == null || asked.cols != nextCols || asked.rows != nextRows) {
      return false;
    }
    final waited = DateTime.now().difference(asked.at);
    if (waited >= _resizeAnswerWait) return false;
    if (_resizeAnswerTimer == null) {
      final generation = _generation;
      _resizeAnswerTimer = Timer(_resizeAnswerWait - waited, () {
        _resizeAnswerTimer = null;
        if (!_isCurrent(generation) || _resizeAsked == null) return;
        _resizeAsked = null;
        final measured = _measuredViewport;
        if (measured == null) return;
        _pendingCols = measured.cols;
        _pendingRows = measured.rows;
        unawaited(_flushResize());
      });
    }
    return true;
  }

  List<int> _prepareKeyframeBytes(Uint8List bytes) {
    if (engineId != 'grok') return bytes;

    // Grok renders a full-screen TUI in tmux's normal buffer. Its tmux
    // scrollback therefore contains old full-screen repaint frames rather than
    // semantic history. Render Grok in the receiver's alternate buffer so the
    // stale frames cannot become local scrollback; wheel input is then routed
    // back to Grok, which owns and redraws its real transcript with ANSI style.
    const alternateBuffer = <int>[
      0x1b,
      0x5b,
      0x3f,
      0x31,
      0x30,
      0x34,
      0x39,
      0x68,
    ];
    if (bytes.length >= 2 && bytes[0] == 0x1b && bytes[1] == 0x63) {
      return <int>[bytes[0], bytes[1], ...alternateBuffer, ...bytes.sublist(2)];
    }
    return <int>[...alternateBuffer, ...bytes];
  }

  Terminal _newTerminal({bool bindCallbacks = true}) {
    final result = Terminal(
      maxLines: 10000,
      platform: TerminalTargetPlatform.macos,
      // ⌥⏎ has to become a Meta-prefixed Return before it reaches the pty, or the engine's prompt
      // reads it as the submit it is byte-identical to. See [MetaEnterInputHandler].
      inputHandler: harnessInputHandler,
      // The remote pane owns its grid and redraws after resize. Reflowing TUI
      // rows locally both changes their geometry and exercises an xterm.dart
      // circular-buffer bug when a remote/local switch changes viewport size.
      reflowEnabled: false,
    );
    if (bindCallbacks) _bindTerminal(result);
    return result;
  }

  void _bindTerminal(Terminal result) {
    result.onOutput = _onTerminalOutput;
    result.onResize = (width, height, _, _) => resize(width, height);
  }

  /// Whether the next character typed leaves as a control chord.
  ///
  /// The phone's key bar has a `ctrl` KEY where a desktop has a modifier to
  /// hold down. Nothing on a software keyboard can be held while another key is
  /// pressed, and the characters it produces arrive as TEXT rather than as key
  /// events, so the translation cannot live in a keymap. It happens here
  /// instead — the one point every keystroke crosses on its way to the pty.
  bool get controlArmed => _controlArmed;
  bool _controlArmed = false;

  /// Arms, or clears, the modifier described by [controlArmed].
  void armControl(bool armed) {
    if (_controlArmed == armed) return;
    _controlArmed = armed;
    notifyListeners();
  }

  /// Spends [controlArmed] on [data].
  ///
  /// One shot, and spent on whatever arrives next whether or not it has a chord:
  /// the alternative is a modifier that silently stays armed across a keystroke
  /// it could not translate, and then eats a later one.
  String _spendArmedControl(String data) {
    if (!_controlArmed) return data;
    _controlArmed = false;
    notifyListeners();
    return controlChordFor(data) ?? data;
  }

  /// Sends a composed message as one turn.
  ///
  /// This does NOT write bytes into the pane. It sends the same `message` frame the web client
  /// uses to drive a turn (`sendMessage` in web's `lib/ws.ts`), and the machine's own handler owns
  /// the injection from there: it adapts slash commands to the pane's engine and retries the
  /// submit Enter. A client typing bytes can do neither — which is exactly how Codex ended up
  /// holding a composed line unsent, its Enter arriving in the same read as the text.
  /// Where a finished voice take goes instead of [sendComposerText], while the page has a reason
  /// to route it — an agent's question dialog is open, and a paste-and-Return would answer it
  /// blind. Set and cleared by the page; null the rest of the time.
  Future<bool> Function(String text)? voiceDeliver;

  /// While this pane is the onboarding's first session, its mic's takes pretend: no microphone, no
  /// permission prompt, each heard as what this says when it ends — the task in the prompt
  /// (`VoiceInputController.startListening`). Null from it means an ordinary recording: the first send
  /// has gone, or a question is open that a spoken answer is for. Set and cleared by the page; read
  /// only by this pane's own mic (`voice_mic_action.dart`), never by Find's or New's.
  String? Function()? voicePretend;

  /// Called each time this pane sends a line on the person's behalf: a Return typed or pressed —
  /// it crosses [_onTerminalOutput] — or a composed message that went ([sendComposerText]). Set by
  /// the page showing the pane, which asks for notifications after the phone's first send
  /// (`phone/terminal_page.dart`); null the rest of the time.
  VoidCallback? onLineSent;

  Future<bool> sendComposerText(String text) async {
    if (!acceptsInput) return false;
    final content = text.trimRight();
    if (content.trim().isEmpty) return false;
    final sent = await send('message', {
      'content': content,
      'agentId': agentId,
      'mode': 'auto',
    });
    if (sent) onLineSent?.call();
    return sent;
  }

  /// First-task suggestions replace the prompt rather than appending to it.
  /// Wait for the clear's ordered input queue before the separate message frame:
  /// otherwise a fast message could arrive before its clear. These are the
  /// engines whose clear-prompt keys we support; never guess for another TUI.
  Future<bool> sendFirstTask(String text) async {
    if (!acceptsInput ||
        !const ['claude', 'codex', 'opencode'].contains(engineId)) {
      return false;
    }
    clearPrompt();
    await _flushInput();
    await _inputSendTail;
    if (!acceptsInput) return false;
    return sendComposerText(text);
  }

  /// A clipboard paste made directly into this pane, delivered as one atomic unit instead of going
  /// through the same chunked pipeline as ordinary typing ([_onTerminalOutput]/[_flushInput]).
  ///
  /// A big paste run through that pipeline gets sliced into ≤8 KiB binary frames client-side and then
  /// into 2 KiB `send-keys -H` bursts on the daemon — each burst arrives far enough apart that the
  /// engine's own paste-detector (readline/Ink) can register it as a SEPARATE paste, which is why a
  /// large paste read as dozens of `[Pasted text #N]` markers instead of one. A [TerminalBinaryKind.paste]
  /// frame routes through the daemon's `tmux paste-buffer` instead, the same single-shot mechanism
  /// composer messages already use — see `pasteRawIntoTmux` in the harness CLI.
  ///
  /// Binary, not JSON: unlike a JSON frame type, a new binary `kind` needs no entry in the E2EE
  /// allowlist (`ENCRYPTED_DOWN_TYPES`) three OTHER codebases also pin a hash of — the AEAD wrapping
  /// that already covers `input`/`output` covers this too, with nothing extra to keep in sync. That is
  /// what lets this work over a relayed machine, not just a local one.
  ///
  /// The caller must check [MachineState.terminalPasteRawAvailable] first: an older CLI does not know
  /// this binary kind at all, so sending it there would silently go nowhere.
  Future<bool> pasteText(String text) async {
    if (!acceptsInput) return false;
    // Forwarded verbatim, including a stray 0x03 — same as _onTerminalOutput/sendComposerText.
    if (text.isEmpty) return false;
    final currentStreamId = streamId;
    if (currentStreamId == null) return false;
    final generation = _generation;
    final frame = TerminalBinaryFrame(
      kind: TerminalBinaryKind.paste,
      streamId: currentStreamId,
      // Unused server-side (a paste is one self-contained unit, not part of the ordered keystroke
      // stream `input`'s seq guards) — kept at 0 rather than threading a second counter for a field
      // nothing reads.
      seq: 0,
      bytes: Uint8List.fromList(utf8.encode(text)),
      compressed: false,
    );
    final sent = await sendBinary(frame);
    if (!sent && _isCurrent(generation)) {
      transportLost('Terminal paste was not sent');
    }
    return sent;
  }

  /// A clipboard IMAGE paste (raw PNG bytes) made directly into this pane, sent as a chunked
  /// upload (see [_uploadBytes]) over [TerminalBinaryKind.imagePaste] frames — the daemon's
  /// text-paste handler requires valid UTF-8 and would reject PNG bytes outright, hence its own
  /// kind, same reason [pasteText] doesn't carry it.
  ///
  /// The caller must check [MachineState.terminalImagePasteAvailable] first, same reason
  /// [pasteText] checks `terminalPasteRawAvailable`: an older CLI does not know this binary kind
  /// at all, so sending it there would silently go nowhere.
  Future<bool> pasteImage(Uint8List pngBytes) async {
    if (pngBytes.isEmpty) return false;
    return _uploadBytes(
      uploadKind: 'image',
      filename: null,
      bytes: pngBytes,
      binaryKind: TerminalBinaryKind.imagePaste,
    );
  }

  /// A dropped (non-image) FILE — sent as a chunked upload (see [_uploadBytes]) so the daemon can
  /// write it to disk on its own (REMOTE) machine and paste that path as text. Only meaningful for
  /// a genuinely remote pane: a LOCAL file already has a valid path on this same machine, so
  /// callers should paste that path directly via [pasteText] instead and never reach this method
  /// at all. A phone has no local pane.
  ///
  /// The caller must check [MachineState.terminalPasteFileAvailable] first, same reason
  /// [pasteImage] checks `terminalImagePasteAvailable`: an older CLI does not know this binary kind
  /// at all, so sending it there would silently go nowhere.
  Future<bool> pasteFile(String filename, Uint8List content) async {
    if (filename.isEmpty || content.isEmpty) return false;
    return _uploadBytes(
      uploadKind: 'file',
      filename: filename,
      bytes: content,
      binaryKind: TerminalBinaryKind.pasteFile,
    );
  }

  /// Cancels whatever image/file upload is currently in flight on this pane, if any — the user's
  /// own Cancel affordance on the upload-progress overlay. A no-op if nothing is uploading.
  Future<void> cancelUpload() async {
    final upload = _activeUpload;
    final currentStreamId = streamId;
    if (upload == null) return;
    if (!upload.beginAccepted.isCompleted) upload.beginAccepted.complete(false);
    if (!upload.finished.isCompleted) upload.finished.complete(false);
    _clearUpload();
    if (currentStreamId != null) {
      await send('terminal_chunked_upload_cancel', {
        'streamId': currentStreamId,
      });
    }
  }

  /// Shared orchestration for [pasteImage]/[pasteFile]: announce the upload
  /// (`terminal_chunked_upload_begin`), wait to be accepted, send the bytes as a series of
  /// `binaryKind` frames — [TerminalBinaryFrame.seq] is the chunk index — each at most
  /// [terminalUploadChunkBytes], then wait for the daemon's completion/error frame. Chunked rather
  /// than sent whole because a single frame over 512 KiB never reaches a relayed or P2P-connected
  /// remote machine at all (both cap a binary message there); see the plan this shipped from.
  ///
  /// [uploadProgress] reflects the daemon's own per-chunk ACKs
  /// (`terminal_chunked_upload_progress`), not "chunks handed to the local socket" — that is what
  /// keeps the percentage honest on a slow link, mirroring the firmware pusher's `fw.progress`
  /// philosophy (`autonomous-harness/cli/src/cable/fwPush.ts`). Only one upload runs at a time per
  /// pane — a second call while one is active is refused immediately, matching the daemon's own
  /// "an upload is already in progress" rejection.
  ///
  /// The same ACKs pace the chunks: at most [terminalUploadWindowBytes] go out ahead of them. A
  /// chunk lost on the way (a P2P link dropped with chunks in its buffer, say) is never asked for
  /// again, and the daemon waits for it for as long as the stream lives; without an ACK for
  /// [uploadStallTimeout], the upload is given up rather than left showing its last percentage.
  /// Every upload given up is cancelled on the daemon too: one it still held refused every later
  /// upload on the pane.
  Future<bool> _uploadBytes({
    required String uploadKind,
    required String? filename,
    required Uint8List bytes,
    required TerminalBinaryKind binaryKind,
  }) async {
    if (!acceptsInput) return false;
    if (_activeUpload != null) return false;
    final currentStreamId = streamId;
    if (currentStreamId == null) return false;

    final upload = _ActiveUpload();
    final generation = _generation;
    bool current() =>
        _isCurrent(generation) && identical(_activeUpload, upload);
    _activeUpload = upload;
    lastStalledUpload = null;
    uploadProgress = UploadProgress(
      label: filename ?? 'image',
      bytesWritten: 0,
      totalBytes: bytes.length,
    );
    notifyListeners();

    var accepted = false;
    // A daemon may still hold an upload an older build gave up on without cancelling it. Cancel
    // that one and ask once more.
    for (var attempt = 0; attempt < 2 && !accepted; attempt++) {
      if (attempt > 0) {
        upload.beginAccepted = Completer<bool>();
        await send('terminal_chunked_upload_cancel', {
          'streamId': currentStreamId,
        });
        if (!current()) return false;
      }
      final sentBegin = await send('terminal_chunked_upload_begin', {
        'streamId': currentStreamId,
        'uploadKind': uploadKind,
        'totalBytes': bytes.length,
        'filename': ?filename,
      });
      if (!current()) return false;
      if (!sentBegin) {
        transportLost('Terminal upload request was not sent');
        _clearUpload();
        return false;
      }
      accepted = await upload.beginAccepted.future.timeout(
        const Duration(seconds: 10),
        onTimeout: () => false,
      );
      if (!current()) return false;
      // An unanswered begin may still have been accepted.
      if (!accepted && !upload.beginAccepted.isCompleted) {
        return _abandonUpload(currentStreamId);
      }
      if (upload.refusal != _uploadAlreadyInProgress) break;
    }
    if (!accepted) {
      _clearUpload();
      return false;
    }

    var offset = 0;
    var seq = 0;
    while (offset < bytes.length && !upload.finished.isCompleted) {
      while (offset - upload.acked >= terminalUploadWindowBytes &&
          !upload.finished.isCompleted) {
        final moved = await _awaitUploadAck(upload);
        if (!current()) return false;
        if (!moved) return _abandonUpload(currentStreamId, stalled: true);
      }
      if (upload.finished.isCompleted) break;
      final end = min(offset + terminalUploadChunkBytes, bytes.length);
      final frame = TerminalBinaryFrame(
        kind: binaryKind,
        streamId: currentStreamId,
        seq: seq,
        bytes: Uint8List.sublistView(bytes, offset, end),
        compressed: false,
      );
      final sentChunk = await sendBinary(frame);
      if (!current()) return false;
      if (!sentChunk) {
        transportLost('Terminal upload chunk was not sent');
        _clearUpload();
        return false;
      }
      offset = end;
      seq++;
    }

    while (upload.acked < bytes.length && !upload.finished.isCompleted) {
      final moved = await _awaitUploadAck(upload);
      if (!current()) return false;
      if (!moved) return _abandonUpload(currentStreamId, stalled: true);
    }
    // Every byte is there: what remains is the daemon's own paste (a clipboard write, a file).
    final finished = await upload.finished.future.timeout(
      const Duration(minutes: 2),
      onTimeout: () => false,
    );
    if (!current()) return false;
    if (!finished) return _abandonUpload(currentStreamId);
    _clearUpload();
    return true;
  }

  /// True once the daemon confirms more of [upload] or it ends; false after [uploadStallTimeout]
  /// with neither.
  Future<bool> _awaitUploadAck(_ActiveUpload upload) async {
    try {
      await Future.any([upload.nextAck(), upload.finished.future])
          .timeout(uploadStallTimeout);
      return true;
    } on TimeoutException {
      return false;
    }
  }

  /// Gives up the active upload here and on the daemon. The cancel is queued before the upload is
  /// cleared, so it reaches the daemon ahead of any upload this pane starts next.
  Future<bool> _abandonUpload(
    String uploadStreamId, {
    bool stalled = false,
  }) async {
    final progress = uploadProgress;
    if (stalled) {
      lastStalledUpload = progress;
      debugPrint(
        'TerminalSession: upload stalled agent=$agentId '
        'confirmed=${progress?.bytesWritten}/${progress?.totalBytes}',
      );
    }
    final cancelled = send('terminal_chunked_upload_cancel', {
      'streamId': uploadStreamId,
    });
    _clearUpload();
    await cancelled;
    return false;
  }

  void _clearUpload() {
    _activeUpload = null;
    uploadProgress = null;
    notifyListeners();
  }

  void _onTerminalOutput(String data) {
    if (kTypingTrace && data.isNotEmpty) {
      typingTrace(
        acceptsInput
            ? 'pty in "${traceText(data)}"'
            : 'pty in DROPPED — not taking input (status=${status.name}'
                  ' stream=${streamId != null} watching=$watching) "${traceText(data)}"',
      );
    }
    if (!acceptsInput || data.isEmpty) return;
    if (data.contains('\r')) onLineSent?.call();
    data = _spendArmedControl(data);
    final bytes = utf8.encode(data);
    final isBoundary =
        data.contains('\r') ||
        data.contains('\x1b[200~') ||
        data.contains('\x1b[201~');
    if (isBoundary) unawaited(_flushInput());
    var offset = 0;
    while (offset < bytes.length) {
      final available = 8 * 1024 - _inputBytes.length;
      final take = min(available, bytes.length - offset);
      _inputBytes.addAll(bytes.sublist(offset, offset + take));
      offset += take;
      if (_inputBytes.length == 8 * 1024) unawaited(_flushInput());
    }
    if (isBoundary) {
      unawaited(_flushInput());
    } else if (_inputBytes.isNotEmpty) {
      // Leading edge: the first keystroke after a pause goes out at once. The window exists to
      // batch key-repeat, and a lone keypress has nothing to batch with — making it wait was
      // 4ms of pure latency on every character typed at human speed. Anything arriving inside
      // the window still rides the trailing timer, so the frame rate stays bounded.
      final last = _lastInputFlushAt;
      final idle =
          last == null ||
          DateTime.now().difference(last) >= _inputCoalesceWindow;
      if (_inputTimer == null && idle) {
        unawaited(_flushInput());
      } else {
        _inputTimer ??= Timer(
          _inputCoalesceWindow,
          () => unawaited(_flushInput()),
        );
      }
    }
  }

  Future<void> _flushInput() async {
    _inputTimer?.cancel();
    _inputTimer = null;
    if (!acceptsInput || _inputBytes.isEmpty) {
      if (kTypingTrace && _inputBytes.isNotEmpty) {
        typingTrace(
          'pty flush DROPPED ${_inputBytes.length}B — not taking input'
          ' (status=${status.name})',
        );
      }
      _inputBytes.clear();
      return;
    }
    final bytes = List<int>.from(_inputBytes);
    _inputBytes.clear();
    _lastInputFlushAt = DateTime.now();
    final currentStreamId = streamId;
    if (currentStreamId == null) {
      if (kTypingTrace) {
        typingTrace('pty flush DROPPED ${bytes.length}B — no stream');
      }
      return;
    }
    final generation = _generation;
    final flushedAt = kTypingTrace ? typingNowMs() : 0;
    final queuedBehind = _sendsInFlight;
    final idleFor = typingNowMs() - _sendsIdleSinceMs;
    if (kTypingTrace) _sendsInFlight++;
    final queued = _inputSendTail.then((_) async {
      if (!_isCurrent(generation) ||
          !acceptsInput ||
          streamId != currentStreamId) {
        if (kTypingTrace) {
          typingTrace(
            'pty send DROPPED ${bytes.length}B — the stream moved on while it'
            ' queued (status=${status.name})',
          );
        }
        return;
      }
      if (kTypingTrace && typingNowMs() - flushedAt >= 3) {
        typingTrace(
          'pty send waited ${typingNowMs() - flushedAt}ms — $queuedBehind send(s)'
          ' were in flight when it was queued'
          '${queuedBehind == 0 ? ', the line idle for ${idleFor}ms' : ''}',
        );
      }
      // Numbered HERE, on the tail, not when the flush was asked for. A frame
      // the guard above drops — the session went `resyncing` while an earlier
      // send was still in flight — must not consume a seq: the daemon wants
      // them contiguous and never re-syncs its counter, so one skipped number
      // had the very next keystroke refused and the whole pane frozen. The
      // tail runs one closure at a time, which is what keeps the numbers in
      // order.
      //
      // Never larger than the daemon accepts, either — split rather than let
      // one oversized frame be refused with the counter intact behind it.
      for (
        var offset = 0;
        offset < bytes.length;
        offset += kInputFrameMaxBytes
      ) {
        if (!_isCurrent(generation) ||
            !acceptsInput ||
            streamId != currentStreamId) {
          return;
        }
        final end = min(offset + kInputFrameMaxBytes, bytes.length);
        final frame = TerminalBinaryFrame(
          kind: TerminalBinaryKind.input,
          streamId: currentStreamId,
          seq: _inputSeq++,
          bytes: Uint8List.fromList(bytes.sublist(offset, end)),
          compressed: false,
        );
        final sendStarted = kTypingTrace ? typingNowMs() : 0;
        final sent = await sendBinary(frame);
        if (kTypingTrace) {
          _lastInputSentMs = typingNowMs();
          typingTrace(
            'pty sent seq=${frame.seq} ${frame.bytes.length}B ok=$sent'
            ' in ${typingNowMs() - sendStarted}ms via=${linkMode ?? '?'}',
          );
        }
        if (!_isCurrent(generation)) return;
        if (!sent) {
          transportLost('Terminal input was not sent');
          return;
        }
      }
    });
    _inputSendTail = queued
        .catchError((_) {
          if (_isCurrent(generation)) {
            transportLost('Terminal input was not sent');
          }
        })
        .whenComplete(() {
          if (!kTypingTrace) return;
          _sendsInFlight--;
          _sendsIdleSinceMs = typingNowMs();
        });
    await _inputSendTail;
  }

  /// A finger on the dial moved — scroll whatever this session is showing.
  ///
  /// Goes STRAIGHT to the renderer rather than through the machine: the scrollback being moved is the copy
  /// in this window, and the agent on the other end has no idea the view scrolled. Nothing is sent over
  /// the wire and nothing is echoed back.
  void scroll(int phase, int dy, int velocity) {
    _viewport?.scroll(phase, dy, velocity);
  }

  bool focusInput() => _viewport?.focusInput() ?? false;

  /// Coalescing windows for the two things the user drives directly.
  ///
  /// Both are leading + trailing: act on the first event, batch the rest. A flat trailing debounce
  /// charged its full window to every single keystroke and to the start of every drag, which is
  /// latency paid for a batch that mostly never materializes.
  static const _inputCoalesceWindow = Duration(milliseconds: 4);

  /// The daemon's ceiling on one input frame (`INPUT_MAX_BYTES` in
  /// `cli/src/lib/terminalStreamManager.ts`). Larger is refused, not split.
  static const kInputFrameMaxBytes = 64 * 1024;
  static const _resizeCoalesceWindow = Duration(milliseconds: 50);

  void resize(int width, int height) {
    // [Terminal.resize] asks here before it shrinks itself, so this still reads the pane's height.
    _noteCutUnderCursor(_clampRows(height));
    _pendingCols = _clampCols(width);
    _pendingRows = _clampRows(height);
    final last = _lastResizeFlushAt;
    final idle =
        last == null ||
        DateTime.now().difference(last) >= _resizeCoalesceWindow;
    if (_resizeTimer == null && idle) {
      unawaited(_flushResize());
      return;
    }
    // Mid-drag: keep resetting so tmux is asked once, for the size the drag settles on.
    _resizeTimer?.cancel();
    _resizeTimer = Timer(
      _resizeCoalesceWindow,
      () => unawaited(_flushResize()),
    );
  }

  Future<void> _flushResize() async {
    // A keyframe can flush the measured viewport before the debounce fires.
    // Cancel that callback before releasing its handle.
    _resizeTimer?.cancel();
    _resizeTimer = null;
    if (!acceptsInput || _pendingCols == null || _pendingRows == null) return;
    final nextCols = _pendingCols!;
    final nextRows = _pendingRows!;
    _pendingCols = null;
    _pendingRows = null;
    final cutFrom = _cutUnderCursorFrom;
    if (cutFrom != null && nextRows >= cutFrom) {
      // The shrink was taken back before it was asked for — the keyboard went down again.
      _cutUnderCursorFrom = null;
    }
    if (nextCols == cols && nextRows == rows) return;
    if (_resizeStillComing(nextCols, nextRows)) return;
    // A keyframe's own resize to the measured size comes straight here, not through [resize].
    _noteCutUnderCursor(nextRows);
    cols = nextCols;
    rows = nextRows;
    _lastResizeFlushAt = DateTime.now();
    _resizeAsked = (cols: cols, rows: rows, at: _lastResizeFlushAt!);
    final generation = _generation;
    if (kTypingTrace) typingEvent('resize → $cols×$rows');
    final sent = await send('terminal_resize', {
      'streamId': streamId,
      'resizeSeq': _resizeSeq++,
      'cols': cols,
      'rows': rows,
    });
    if (!_isCurrent(generation)) return;
    if (!sent) transportLost('Terminal resize was not sent');
    notifyListeners();
  }

  static const _scrollCoalesceWindow = Duration(milliseconds: 16);

  /// Alt-buffer scroll gesture for a [scrollViaTmuxCopyMode] session — see that getter's doc.
  /// Coalesces rapid deltas (a fast trackpad swipe can emit dozens a second) into one
  /// `terminal_scroll` frame per short burst, mirroring `resize()`'s own debounce. Fire-and-forget
  /// like resize, but a dropped frame here is just a missed scroll, not a transport-health signal —
  /// unlike resize, it never calls `transportLost`.
  void sendScrollCommand(bool up, int lines) {
    if (!scrollViaTmuxCopyMode || lines <= 0) return;
    if (_pendingScrollUp != null && _pendingScrollUp != up) {
      // Direction reversed mid-burst — flush what's accumulated before starting the new direction,
      // rather than let it cancel out into a smaller net scroll the user never asked for.
      unawaited(_flushScrollCommand());
    }
    _pendingScrollUp = up;
    _pendingScrollLines += lines;
    _scrollTimer?.cancel();
    _scrollTimer = Timer(
      _scrollCoalesceWindow,
      () => unawaited(_flushScrollCommand()),
    );
  }

  Future<void> _flushScrollCommand() async {
    _scrollTimer?.cancel();
    _scrollTimer = null;
    final up = _pendingScrollUp;
    final lines = _pendingScrollLines;
    _pendingScrollUp = null;
    _pendingScrollLines = 0;
    if (!acceptsInput || up == null || lines <= 0) return;
    await send('terminal_scroll', {
      'streamId': streamId,
      'direction': up ? 'up' : 'down',
      'lines': lines,
    });
  }

  void _markForAck(int renderedBytes) {
    _framesSinceAck++;
    _renderedSinceAckBytes += renderedBytes;
    if (_renderedSinceAckBytes >= 64 * 1024) {
      unawaited(_flushAck());
      return;
    }
    _ackTimer ??= Timer(
      const Duration(milliseconds: 16),
      () => unawaited(_flushAck()),
    );
  }

  Future<void> _flushAck() async {
    _ackTimer?.cancel();
    _ackTimer = null;
    if (streamId == null || _lastRenderedSeq < 0 || _framesSinceAck == 0) {
      return;
    }
    _framesSinceAck = 0;
    _renderedSinceAckBytes = 0;
    final generation = _generation;
    final sent = await send('terminal_ack', {
      'streamId': streamId,
      'lastSeq': _lastRenderedSeq,
    });
    if (!sent && _isCurrent(generation)) {
      transportLost('Terminal ACK was not sent');
    }
  }

  /// Keeps the lease, and notices a stream that went quiet without a word.
  ///
  /// ⚠️ **A send that succeeds proves only that the socket takes bytes, not that THIS stream is
  /// still there.** The daemon sends a sync frame every five seconds even while the terminal is idle
  /// (`SYNC_INTERVAL_MS`, `cli/src/lib/terminalStreamManager.ts`), so a stream that hears nothing for
  /// [_quietBeatsBeforeResync] beats is gone: a socket left half-open by Wi-Fi giving way to 4G
  /// while the app was away, a stale relay session, a stream the daemon dropped and never said.
  /// Until this, such a terminal looked live and took no input until the account's two-minute agent
  /// poll gave up on the machine — about four minutes. It resyncs, then reopens, as the desktop does
  /// (#432).
  ///
  /// Counted in beats, not by the clock, on purpose: an app the OS suspended runs no timers, so
  /// the gap it was away is no beat at all, and coming back is not taken for a silence.
  ///
  /// Which repair, once the stream has gone quiet that long:
  /// - **The socket heard nothing from the machine either** ([_transportSilentToo]): the socket is
  ///   what died, and every stream on it with it. It is redialled at once ([onTransportSilent]),
  ///   skipping the resync tries and the open's patience that only a live socket could answer.
  /// - **The socket still hears the machine** (another agent's output, its sync frames, a reply):
  ///   only this stream is gone, and the daemon can repair it — the resync, then a reopen.
  Future<void> _sendHeartbeat() async {
    if (!acceptsInput) return;
    final generation = _generation;
    final sent = await send('terminal_alive', {
      'streamId': streamId,
      // Ask the daemon to say so if it no longer holds this stream (CLI `reportMissing`).
      'reportMissing': true,
    });
    if (!sent && _isCurrent(generation)) {
      transportLost('Terminal heartbeat was not sent');
      return;
    }
    if (!_isCurrent(generation) || !acceptsInput) return;
    if (++_quietBeats < _quietBeatsBeforeResync) return;
    _quietBeats = 0;
    if (_transportSilentToo() && (onTransportSilent?.call() ?? false)) return;
    // Read again: a redial the hook declined may still have taken this session down meanwhile —
    // another stream of the machine got there first — and a resync now would overwrite its
    // "Connection lost" with a timeout for a stream that is already being put back.
    if (!_isCurrent(generation) || !acceptsInput) return;
    await _requestResync('TERMINAL_STREAM_TIMEOUT');
  }

  /// Whether the machine's socket has heard nothing from the machine since this stream was last
  /// heard from — so the silence is the socket's, not this stream's alone.
  ///
  /// Both times are moments, compared with each other, never a duration on a clock: an app the OS
  /// suspended keeps both where they were, and the comparison stays true across the gap. A socket
  /// carries every frame its machine seals — this stream's sync frames among them, every five
  /// seconds — so on a live socket the machine is heard from after this stream's last frame as
  /// soon as anything else of it arrives. False when there is no hook to ask, or the socket has
  /// never heard the machine at all: the resync stays the repair, as it was before this check.
  bool _transportSilentToo() {
    final heard = lastHeardFromMachine?.call();
    final streamHeard = _lastHeardOnStream;
    if (heard == null || streamHeard == null) return false;
    return !heard.isAfter(streamHeard);
  }

  Future<void> _requestResync(String reason) async {
    if (kTypingTrace) {
      typingEvent(
        'RESYNC asked: $reason (status=${status.name}'
        ' pending input ${_inputBytes.length}B dropped)',
      );
    }
    if (streamId == null) {
      _fail(reason, null);
      return;
    }
    if (!_resyncRequested) {
      _resyncRequested = true;
      _resyncAttempts = 0;
      status = TerminalSessionStatus.resyncing;
      errorCode = reason;
      _inputBytes.clear();
      notifyListeners();
    }
    if (_resyncAttempts > 0) return;
    await _sendResyncAttempt();
  }

  void _armInitialKeyframeWatchdog() {
    _resyncTimer?.cancel();
    _resyncTimer = Timer(resyncTimeout, () {
      if (streamId != null && _expectedSeq == null) {
        unawaited(_requestResync('TERMINAL_KEYFRAME_TIMEOUT'));
      }
    });
  }

  Future<void> _sendResyncAttempt() async {
    final currentStream = streamId;
    final generation = _generation;
    if (!_resyncRequested || currentStream == null) return;
    if (_resyncAttempts >= 3) {
      await _recoverByReopen();
      return;
    }
    _resyncAttempts++;
    debugPrint(
      '[terminal-session] resync_request agent=$agentId stream=$currentStream '
      'attempt=$_resyncAttempts code=$errorCode',
    );
    final sent = await send('terminal_resync', {
      'streamId': currentStream,
      'attempt': _resyncAttempts,
      'reason': errorCode,
      'reportMissing': true,
    });
    if (!_isCurrent(generation) ||
        streamId != currentStream ||
        !_resyncRequested) {
      return;
    }
    if (!sent) {
      transportLost('Could not request terminal resync');
      return;
    }
    _resyncTimer?.cancel();
    _resyncTimer = Timer(resyncTimeout, () {
      if (_resyncRequested && streamId == currentStream) {
        unawaited(_sendResyncAttempt());
      }
    });
  }

  Future<void> _recoverByReopen({
    String reason = 'TERMINAL_RESYNC_TIMEOUT',
  }) async {
    final previousStream = streamId;
    if (_autoReopenAttempts >= 1) {
      debugPrint(
        '[terminal-session] recovery_failed agent=$agentId '
        'stream=$previousStream reason=$reason attempts=$_resyncAttempts',
      );
      _fail(
        reason,
        reason == 'TERMINAL_RESYNC_TIMEOUT'
            ? 'Terminal did not recover after resync and reopen.'
            : 'Terminal did not recover after reopening the stream.',
      );
      return;
    }
    _autoReopenAttempts++;
    debugPrint(
      '[terminal-session] recovery_reopen agent=$agentId stream=$previousStream',
    );
    if (previousStream != null) {
      unawaited(send('terminal_close', {'streamId': previousStream}));
    }
    await _open(
      initialCols: cols,
      initialRows: rows,
      waitForViewportSize: false,
      resetRecovery: false,
      preserveTerminal: true,
    );
  }

  Future<void> close() async {
    _generation++;
    final closingStream = streamId;
    _cancelTimers();
    _inputBytes.clear();
    streamId = null;
    linkMode = null;
    status = TerminalSessionStatus.closed;
    _abortActiveUpload();
    notifyListeners();
    if (closingStream != null) {
      await send('terminal_close', {'streamId': closingStream});
    }
  }

  void transportLost([
    String message = 'Connection lost. Select the harness to reconnect.',
  ]) {
    // `takenOver` is a deliberate dead end (see `_paneNeedsAttach`): only the user's own retry
    // may reopen a stream someone else claimed. A WS hiccup must not quietly overwrite that into
    // `error`, which auto-reattach WOULD pick back up — that is exactly the two-machine tug-of-war
    // this status exists to prevent.
    if (_disposed ||
        status == TerminalSessionStatus.closed ||
        status == TerminalSessionStatus.takenOver) {
      return;
    }
    _generation++;
    _cancelTimers();
    _inputBytes.clear();
    streamId = null;
    linkMode = null;
    status = TerminalSessionStatus.error;
    errorCode = transportLostCode;
    errorMessage = message;
    _abortActiveUpload();
    notifyListeners();
  }

  /// Whether [by] — who took this stream — is this very device: the introduction it sends with
  /// every open ([client]), by kind and name, and by machine where both name one.
  bool _takenBySelf(TerminalClientDescriptor? by) {
    final me = client;
    if (me == null || by == null) return false;
    if (by.kind != me.kind || by.name != me.name) return false;
    final mine = me.machineId;
    final theirs = by.machineId;
    return mine == null || theirs == null || mine == theirs;
  }

  /// Taken over by an open of this same device: open again, politely, once.
  ///
  /// ⚠️ **A takeover is a person's to answer — except one this phone did to itself (owner,
  /// 2026-10-01).** [takenOver] is a dead end on purpose (see `_paneNeedsAttach`): reopening it
  /// automatically would have two apps trading one terminal back and forth. But an open of THIS
  /// device can reach the machine after the one now showing — a copy of a resent open, delivered
  /// late from a connection the phone had already dropped. It takes the terminal, its own
  /// connection is gone a moment later, and the screen sat on "iPhone 16 Pro connected to this
  /// terminal", taken by itself, with nobody holding the terminal at all. Measured at launch on a
  /// slow relay, where it left the first screen on its skeleton until it was tapped.
  ///
  /// Polite ([takeover] false), so it never takes the terminal from anybody: free, it opens as
  /// usual; held, it watches, with the band offering it back. And at most once per
  /// [_ownTakeoverCooldown], because two phones can share a name, and against a daemon that
  /// ignores the polite flag the two would otherwise take the terminal from each other for ever.
  void _reopenAfterOwnTakeover() {
    final now = DateTime.now();
    final last = _ownTakeoverReopenedAt;
    if (last != null && now.difference(last) < _ownTakeoverCooldown) return;
    _ownTakeoverReopenedAt = now;
    takeover = false;
    unawaited(reopen());
  }

  /// A polite open was refused — see [takeover]. The same dead end as a stream that was taken
  /// over, for the same reason: reopening is a person's call, never this session's.
  void _heldElsewhere(String code) {
    if (_disposed) return;
    _generation++;
    _cancelTimers();
    _inputBytes.clear();
    streamId = null;
    linkMode = null;
    status = TerminalSessionStatus.takenOver;
    errorCode = code;
    errorMessage = 'Another client controls this terminal.';
    _abortActiveUpload();
    notifyListeners();
  }

  void _fail(String code, String? message) {
    if (_disposed) return;
    _generation++;
    _cancelTimers();
    _inputBytes.clear();
    streamId = null;
    linkMode = null;
    status = TerminalSessionStatus.error;
    errorCode = code;
    errorMessage = message;
    _abortActiveUpload();
    notifyListeners();
  }

  /// A safety net for any path that resets the stream (transport loss, a real failure) while an
  /// image/file upload happens to be in flight — resolves its awaiting Future rather than leaving
  /// it to hang until [_uploadBytes]'s own 2-minute timeout. The specific error codes that mean
  /// "the upload itself failed" already call this via [transportLost]/[_fail]; this also covers
  /// every OTHER way the stream can go away mid-upload.
  void _abortActiveUpload() {
    if (_activeUpload?.beginAccepted.isCompleted == false) {
      _activeUpload!.beginAccepted.complete(false);
    }
    if (_activeUpload?.finished.isCompleted == false) {
      _activeUpload!.finished.complete(false);
    }
    _activeUpload = null;
    uploadProgress = null;
  }

  bool _matchesStream(Map<String, dynamic> payload) =>
      streamId != null && payload['streamId'] == streamId;

  int _clampCols(int value) => value.clamp(minCols, maxCols);
  int _clampRows(int value) => value.clamp(minRows, maxRows);

  void _cancelTimers() {
    _heartbeat?.cancel();
    _heartbeat = null;
    _ackTimer?.cancel();
    _ackTimer = null;
    _inputTimer?.cancel();
    _inputTimer = null;
    _resizeTimer?.cancel();
    _resizeTimer = null;
    _resizeAnswerTimer?.cancel();
    _resizeAnswerTimer = null;
    _resyncTimer?.cancel();
    _resyncTimer = null;
    _scrollTimer?.cancel();
    _scrollTimer = null;
  }

  @override
  void dispose() {
    _disposed = true;
    _generation++;
    _cancelTimers();
    outputTicks.dispose();
    super.dispose();
  }
}