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.

56.0 KB
Raw Blame
import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
import { patientDeadline } from './patientExec.js'
import { SgrCarry } from './sgrCarry.js'
import { REWRAP_MIN_WIDTH, rewrapTmuxHistory } from './historyRewrap.js'
import { pasteRawIntoTmux } from './tmux.js'
import { enterTmuxRoom, inTmuxRoom, needsControlGate } from './tmuxControlGate.js'
import { tmuxFeatures, tmuxFeaturesOf, type TmuxFeatures } from './tmuxVersion.js'
import {
  KEYFRAME_MAX_BYTES,
  TERMINAL_ACTION_SUCCEEDED,
  terminalActionNotStarted,
  terminalActionPossiblyExecuted,
  type TerminalActionResult,
  type TerminalReadResult,
  type TerminalStreamHandle,
  type TerminalStreamSink,
  type TerminalStreamSize,
  type TerminalStreamSnapshot,
  type TmuxRuntimeRef,
} from './terminalTypes.js'

export type SnapshotOptions = NonNullable<Parameters<TerminalStreamHandle<TmuxRuntimeRef>['snapshot']>[0]>

const MIN_COLS = 1
const MAX_COLS = 300
const MIN_ROWS = 1
const MAX_ROWS = 120
// One `send-keys -H` line carries two hex characters plus a space per byte. tmux accepts a command
// line built from 8192 such bytes and rejects 16384 with `%error`, so this leaves a 4x margin.
const INPUT_CHUNK_BYTES = 2 * 1024
const CONTROL_COMMAND_TIMEOUT_MS = 3_000
/** The longest a control client keeps every other one and every paste waiting while it attaches, on a
 *  tmux before 3.7 (tmuxControlGate.ts): tmux answers an attach in milliseconds, and one that has not in
 *  this long has its first command time out and its stream closed anyway. */
const ATTACH_HOLD_MAX_MS = CONTROL_COMMAND_TIMEOUT_MS
/** How long a going control client gets to exit, after `detach-client` and again after SIGTERM. */
const CLOSE_EXIT_WAIT_MS = 500
/** The most output a snapshot holds back behind its gate: past it the stream is closed. */
export const SNAPSHOT_BUFFER_MAX_BYTES = 2 * 1024 * 1024
const SNAPSHOT_QUIET_MS = 8
const SNAPSHOT_QUIET_MAX_MS = 40
/** The longest a snapshot waits for an engine's print to end from the moment it saw the print begin: Codex's ended
 *  by 186 ms after the resize. Past it the keyframe is taken as it is, and the rest reaches the viewer as output. */
const REPAINT_MAX_MS = 400
export const SNAPSHOT_HISTORY_LINES = 500
/**
 * A conversation kept in the scrollback (facets/launch.ts `ScreenContract`) is seeded whole: tmux's own
 * history-limit, which Harness leaves at its default. Its last 500 rows were the last screens of a reply, and a
 * phone opened on "Test 100" at 544 began 44 rows into it (2026-10-13). As much as the keyframe's size allows:
 * Codex's styled rows ran 238 bytes each, 2000 of them most of KEYFRAME_MAX_BYTES (measured the same day).
 */
export const CONVERSATION_HISTORY_LINES = 2000
/** Grok only exposes PageUp/PageDown while the prompt is focused, so a wheel
 *  burst is one page, never a stack of them. The desktop may still emit
 *  several `terminal_scroll` frames per flick (16ms coalesce on shipped
 *  builds); the interval below drops the extras. */
export const TUI_SCROLL_MIN_INTERVAL_MS = 180

/** How many PageUp/PageDown keys a coalesced wheel burst should become. */
export function tuiScrollPageCount(lines: number): number {
  if (!Number.isFinite(lines) || lines <= 0) return 0
  return 1
}

/** Keystrokes as hex bytes (`send-keys -H`, tmux 3.0), [chunk] bytes to a command. */
function hexKeyCommands(paneId: string, bytes: Uint8Array, chunk = INPUT_CHUNK_BYTES): string[] {
  const commands: string[] = []
  for (let offset = 0; offset < bytes.length; offset += chunk) {
    const hex = [...bytes.subarray(offset, offset + chunk)].map((byte) => byte.toString(16).padStart(2, '0')).join(' ')
    commands.push(`send-keys -t ${paneId} -H ${hex}`)
  }
  return commands
}

/**
 * One argument for the command parser of tmux before 3.0 (`cmd-string.c`), holding [text] exactly.
 * Single quotes take every byte as it is but their own; a `'` goes in double quotes, which hold it
 * as it is too. An argument that ends in `;` would end the command there instead, unless it ends in
 * `\;`, which the parser gives back as `;` (`cmd_list_parse`).
 */
export function quoteForOldTmux(text: string): string {
  const quoted = text.split("'").map((part) => `'${part}'`).join(`"'"`)
  return text.endsWith(';') ? `${quoted.slice(0, -2)}\\;'` : quoted
}

/**
 * Keystrokes for a tmux before 3.0, which has no `send-keys -H`: the bytes as literal text,
 * `send-keys -l`, which tmux writes to the pane byte for byte. Two bytes cannot ride a control-mode
 * command line, and go as the keys that write them: LF ends the line (`C-j`), NUL ends the string
 * (`C-@`). Runs are cut at [chunk] bytes and never inside a UTF-8 sequence: tmux reads each argument as
 * UTF-8, and half a character would be written as two wrong ones. `--` before the text, or text that
 * starts with `-` would be read as a flag. One command per line: tmux answers each with its own
 * `%begin`/`%end`, which is what `ControlCommandQueue` counts.
 */
export function literalKeyCommands(paneId: string, bytes: Uint8Array, chunk = INPUT_CHUNK_BYTES): string[] {
  const commands: string[] = []
  const literal = (from: number, to: number): void => {
    for (let at = from; at < to;) {
      let cut = Math.min(to, at + chunk)
      while (cut < to && cut > at + 1 && (bytes[cut] & 0xc0) === 0x80) cut--
      commands.push(`send-keys -t ${paneId} -l -- ${quoteForOldTmux(Buffer.from(bytes.subarray(at, cut)).toString('utf8'))}`)
      at = cut
    }
  }
  let start = 0
  for (let index = 0; index < bytes.length; index++) {
    if (bytes[index] !== 0x0a && bytes[index] !== 0x00) continue
    literal(start, index)
    commands.push(`send-keys -t ${paneId} ${bytes[index] === 0x0a ? 'C-j' : 'C-@'}`)
    start = index + 1
  }
  literal(start, bytes.length)
  return commands
}
const PANE_META_FORMAT = [
  '#{session_id}', '#{window_id}', '#{window_panes}', '#{window_width}', '#{window_height}',
  '#{pane_width}', '#{pane_height}', '#{alternate_on}', '#{cursor_x}', '#{cursor_y}',
  '#{cursor_flag}',
  '#{mouse_standard_flag}', '#{mouse_button_flag}', '#{mouse_all_flag}', '#{mouse_utf8_flag}', '#{mouse_sgr_flag}',
].join('|')

/** A pane's metadata as a keyframe needs it: tmux's `display-message` fields (`PANE_META_FORMAT`). */
export interface PaneMeta {
  sessionId: string
  windowId: string
  windowPanes: number
  windowWidth: number
  windowHeight: number
  paneWidth: number
  paneHeight: number
  alternateOn: boolean
  cursorX: number
  cursorY: number
  cursorVisible: boolean
  mouseStandard: boolean
  mouseButton: boolean
  mouseAll: boolean
  mouseUtf8: boolean
  mouseSgr: boolean
}

/** The smallest size `refresh-client -C` takes before tmux 2.9 (its PANE_MINIMUM): asked for less, it
 *  refused, and the resize failed instead of drawing two columns. */
const OLD_TMUX_MIN_CLIENT_SIZE = 2

/** A stream's size within what a terminal stream accepts. */
export function boundedSize(size: TerminalStreamSize, min = { cols: MIN_COLS, rows: MIN_ROWS }): TerminalStreamSize {
  return {
    cols: Math.max(min.cols, Math.min(MAX_COLS, Math.floor(size.cols))),
    rows: Math.max(min.rows, Math.min(MAX_ROWS, Math.floor(size.rows))),
  }
}

/** Spawns a one-shot tmux client. Only the pre-open probe below may use it: once the control
 *  client is attached, every command goes down its stdin instead (see `ControlCommandQueue`). */
function execTmux(args: string[], timeout = 2_000): Promise<{ ok: boolean; stdout: Buffer }> {
  return new Promise((resolve) => {
    execFile('tmux', args, { timeout, encoding: 'buffer', maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => {
      resolve({ ok: !error, stdout: Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout ?? '') })
    })
  })
}

async function paneMeta(paneId: string): Promise<PaneMeta | null> {
  const result = await execTmux(['display-message', '-p', '-t', paneId, PANE_META_FORMAT])
  if (!result.ok) return null
  return parsePaneMeta(result.stdout)
}

function parsePaneMeta(bytes: Uint8Array): PaneMeta | null {
  const fields = Buffer.from(bytes).toString('utf8').trim().split('|')
  if (fields.length !== 16 || !/^\$\d+$/.test(fields[0]) || !/^@\d+$/.test(fields[1])) return null
  const nums = fields.slice(2).map(Number)
  if (nums.some((value) => !Number.isFinite(value))) return null
  return {
    sessionId: fields[0],
    windowId: fields[1],
    windowPanes: nums[0],
    windowWidth: nums[1],
    windowHeight: nums[2],
    paneWidth: nums[3],
    paneHeight: nums[4],
    alternateOn: nums[5] === 1,
    cursorX: nums[6],
    cursorY: nums[7],
    cursorVisible: nums[8] === 1,
    mouseStandard: nums[9] === 1,
    mouseButton: nums[10] === 1,
    mouseAll: nums[11] === 1,
    mouseUtf8: nums[12] === 1,
    mouseSgr: nums[13] === 1,
  }
}

/** Decode the octal escaping used by tmux control-mode `%output` notifications. */
export function decodeTmuxControlData(encoded: string): Uint8Array {
  return decodeTmuxControlBytes(Buffer.from(encoded, 'utf8'))
}

function octalEscapeAt(input: Uint8Array, offset: number): boolean {
  return input[offset] === 0x5c && offset + 3 < input.length
    && input[offset + 1] >= 0x30 && input[offset + 1] <= 0x37
    && input[offset + 2] >= 0x30 && input[offset + 2] <= 0x37
    && input[offset + 3] >= 0x30 && input[offset + 3] <= 0x37
}

/** Decode control-mode escaping without first interpreting payload bytes as
 * UTF-8. A Unicode scalar may be split across separate `%output` records; a
 * string decoder would permanently replace both halves with U+FFFD. */
export function decodeTmuxControlBytes(encoded: Uint8Array): Uint8Array {
  // Own the returned bytes without allocating a Buffer for every escaped byte.
  // Decoding only shortens the input, so unread bytes stay ahead of the write.
  const output = Buffer.from(encoded)
  let read = output.indexOf(0x5c)
  // Ordinary backslashes do not require a bytewise rewrite either.
  while (read >= 0 && !octalEscapeAt(output, read)) read = output.indexOf(0x5c, read + 1)
  if (read < 0) return output
  let write = read
  while (read < output.length) {
    if (octalEscapeAt(output, read)) {
      output[write++] = ((output[read + 1] - 0x30) << 6)
        | ((output[read + 2] - 0x30) << 3)
        | (output[read + 3] - 0x30)
      read += 4
    } else {
      output[write++] = output[read++]
    }
  }
  const decoded = output.subarray(0, write)
  // Escape-heavy output can shrink to one quarter of its wire size. Avoid
  // retaining that larger allocation when a consumer keeps the decoded frame.
  return write * 2 < output.length ? Buffer.from(decoded) : decoded
}

export function parseTmuxControlOutput(lineBytes: Uint8Array): { paneId: string; data: Uint8Array } | null {
  const line = Buffer.from(lineBytes)
  const plainPrefix = Buffer.from('%output ')
  if (line.subarray(0, plainPrefix.length).equals(plainPrefix)) {
    const separator = line.indexOf(0x20, plainPrefix.length)
    if (separator < 0) return null
    const paneId = line.subarray(plainPrefix.length, separator).toString('ascii')
    if (!/^%\d+$/.test(paneId)) return null
    return { paneId, data: decodeTmuxControlBytes(line.subarray(separator + 1)) }
  }

  const extendedPrefix = Buffer.from('%extended-output ')
  if (!line.subarray(0, extendedPrefix.length).equals(extendedPrefix)) return null
  // latin1 is deliberately used only to locate the ASCII protocol header;
  // each code unit still maps one-to-one to the original payload byte.
  const header = /^%extended-output\s+(%\d+)\s+\d+\s+:?\s?/.exec(line.toString('latin1'))
  if (!header) return null
  return { paneId: header[1], data: decodeTmuxControlBytes(line.subarray(header[0].length)) }
}

function mouseModes(meta: PaneMeta): string {
  let out = ''
  if (meta.mouseAll) out += '\u001b[?1003h'
  else if (meta.mouseButton) out += '\u001b[?1002h'
  else if (meta.mouseStandard) out += '\u001b[?1000h'
  if (meta.mouseUtf8) out += '\u001b[?1005h'
  if (meta.mouseSgr) out += '\u001b[?1006h'
  return out
}

/** `capture-pane -p` separates screen rows with a bare LF. A VT terminal's
 * LF moves down without returning to column zero, so replaying the capture as
 * received makes every row staircase to the right. tmux also encodes each
 * captured row independently: it may leave a background SGR active at EOL
 * while emitting the following default-style blank row as an empty string.
 * Reset SGR at every row boundary so styled trailing cells remain on their row
 * instead of bleeding into the next one when the snapshot is replayed. */
export function normalizeTmuxCaptureLines(capture: Uint8Array): Uint8Array {
  const raw = Buffer.from(capture)
  // `capture-pane -p` prints a line terminator after its final screen row.
  // Replaying that terminator in a terminal already containing paneHeight rows
  // scrolls the snapshot by one, while cursor metadata stays in tmux's original
  // coordinate space. Drop only this command-output delimiter; separators
  // between captured rows are still normalized below.
  let end = raw.length
  if (end > 0 && raw[end - 1] === 0x0a) {
    end--
    if (end > 0 && raw[end - 1] === 0x0d) end--
  }
  const input = raw.subarray(0, end)
  let loneLf = 0
  for (let index = 0; index < input.length; index++) {
    if (input[index] === 0x0a && (index === 0 || input[index - 1] !== 0x0d)) loneLf++
  }
  const sgrReset = Buffer.from('\u001b[0m')
  const output = Buffer.allocUnsafe(input.length + loneLf * (1 + sgrReset.length) + sgrReset.length)
  let write = 0
  for (let index = 0; index < input.length; index++) {
    if (input[index] === 0x0a && (index === 0 || input[index - 1] !== 0x0d)) {
      sgrReset.copy(output, write)
      write += sgrReset.length
      output[write++] = 0x0d
    }
    output[write++] = input[index]
  }
  sgrReset.copy(output, write)
  write += sgrReset.length
  return output.subarray(0, write)
}

export function normalizeTmuxHistoryLines(capture: Uint8Array): Uint8Array {
  const raw = Buffer.from(capture)
  if (raw.length === 0) return raw
  const end = raw.at(-1) === 0x0a ? raw.length - 1 : raw.length
  if (end <= 0) return Buffer.alloc(0)
  const rows = raw.subarray(0, end).toString('utf8').split('\n')
  // The reset keeps a row's trailing background out of the one that scrolls in after it; the carry
  // puts back what tmux left open across that boundary — see SgrCarry.
  const carry = new SgrCarry()
  return Buffer.from(rows.map((line) => {
    const row = line.replace(/\r$/, '')
    const restore = carry.restore
    carry.feed(row)
    return `${restore}${row}\u001b[0m\r\n`
  }).join(''), 'utf8')
}

/**
 * History rows as a keyframe writes them (each ending in CRLF, each restoring the style carried into it) without as
 * many of the oldest as it takes to shed `excess` bytes: any row can open the history.
 */
export function dropOldestHistoryRows(rows: Uint8Array, excess: number): Uint8Array {
  if (excess <= 0) return rows
  const buffer = Buffer.from(rows.buffer, rows.byteOffset, rows.byteLength)
  const end = buffer.indexOf('\r\n', Math.max(0, excess - 2))
  return end < 0 ? Buffer.alloc(0) : buffer.subarray(end + 2)
}

/**
 * Whether the output read before a capture's cut began an engine's print (facets/launch.ts
 * `ScreenContract.resizeRepaint`) and had not ended it there: the capture then holds a cleared or half-printed screen.
 */
export function printInProgress(chunks: readonly Uint8Array[], print: { clears: string; ends: string }): boolean {
  if (chunks.length === 0) return false
  const read = Buffer.concat(chunks)
  const clears = Buffer.from(print.clears, 'utf8')
  const at = read.lastIndexOf(clears)
  return at >= 0 && read.indexOf(Buffer.from(print.ends, 'utf8'), at + clears.length) < 0
}

export type SnapshotRepaint = NonNullable<SnapshotOptions['repaint']>

/**
 * What a snapshot's waits read of the stream taking it, each time they look: whether it is closed, whether its gate is
 * still up, the output held behind the gate since it rose or since the last cut, when that output last came, and when
 * the stream last changed the pane's size.
 */
export interface SnapshotGate {
  closed(): boolean
  gated(): boolean
  held(): readonly Uint8Array[]
  lastOutputAt(): number
  resizedAt(): number
}

/** Wait until the gated output has been quiet SNAPSHOT_QUIET_MS, at most SNAPSHOT_QUIET_MAX_MS. */
export async function waitForSnapshotQuiet(gate: SnapshotGate): Promise<void> {
  const deadline = Date.now() + SNAPSHOT_QUIET_MAX_MS
  while (!gate.closed()) {
    const now = Date.now()
    const remainingQuiet = SNAPSHOT_QUIET_MS - (now - gate.lastOutputAt())
    if (remainingQuiet <= 0 || now >= deadline) return
    await new Promise((resolve) => setTimeout(resolve, Math.min(remainingQuiet, deadline - now)))
  }
}

/**
 * Wait out an engine's print after a resize (facets/launch.ts `ScreenContract.resizeRepaint`): until the first `ends`
 * after `clears`, or, where `clears` has not come within `withinMs` of the resize, not at all. Every byte meanwhile
 * is held behind the snapshot gate, and what precedes the capture's cut is the capture's: the viewer gets the screen
 * after the print in the keyframe, and never the cleared one.
 */
export async function waitForRepaint(gate: SnapshotGate, repaint: SnapshotRepaint): Promise<void> {
  const clears = Buffer.from(repaint.clears, 'utf8')
  const ends = Buffer.from(repaint.ends, 'utf8')
  let scanned = 0
  // The end of what was read that may begin a sequence the next chunk completes.
  let carry = Buffer.alloc(0)
  // A clear already seen, as live output (the stream manager's guard) or before a capture's cut, is behind this
  // wait: only the end is read for.
  let clearedAt = repaint.cleared === true ? Date.now() : null
  while (!gate.closed() && gate.gated()) {
    for (; scanned < gate.held().length; scanned++) {
      let chunk = Buffer.concat([carry, gate.held()[scanned]])
      if (clearedAt == null) {
        const at = chunk.indexOf(clears)
        if (at < 0) {
          carry = chunk.subarray(Math.max(0, chunk.length - clears.length + 1))
          continue
        }
        // The print gets all of REPAINT_MAX_MS, however late in `withinMs` it began.
        clearedAt = Date.now()
        chunk = chunk.subarray(at + clears.length)
      }
      if (chunk.includes(ends)) return
      carry = chunk.subarray(Math.max(0, chunk.length - ends.length + 1))
    }
    const now = Date.now()
    if (clearedAt == null ? now - gate.resizedAt() >= repaint.withinMs : now - clearedAt >= REPAINT_MAX_MS) return
    await new Promise((resolve) => setTimeout(resolve, 5))
  }
}

/**
 * The keyframe for a pane read for one: its screen as `capture-pane -p -e -N` prints it, its metadata, and its history
 * as `capture-pane -p -e -N -S -<n> -E -1` prints it, or as historyRewrap.ts re-wrapped it (`historyRows`, null where
 * it was not). `conversation`: the history is a conversation's (`conversationHistory`), seeded as far back as fits.
 * `tuiOwnsScrollback`: labelled the alternate screen.
 */
export function tmuxKeyframe(
  capture: Uint8Array,
  meta: PaneMeta,
  history: Uint8Array,
  historyRows: Uint8Array | null,
  options: { conversation: boolean; tuiOwnsScrollback: boolean },
): Uint8Array {
  const screenMeta = options.tuiOwnsScrollback ? { ...meta, alternateOn: true } : meta
  let rows: Uint8Array | undefined = historyRows ?? (options.conversation ? normalizeTmuxHistoryLines(history) : undefined)
  let bytes = synthesizeTmuxSnapshot(capture, screenMeta, history, rows)
  // A conversation is seeded as far back as fits: past the limit the stream would be closed, so its oldest
  // rows go. Any other history is sent as it always was.
  if (options.conversation && rows && bytes.length > KEYFRAME_MAX_BYTES) {
    rows = dropOldestHistoryRows(rows, bytes.length - KEYFRAME_MAX_BYTES)
    bytes = synthesizeTmuxSnapshot(capture, screenMeta, history, rows)
  }
  return bytes
}

export function synthesizeTmuxSnapshot(
  capture: Uint8Array,
  meta: PaneMeta,
  history: Uint8Array = Buffer.alloc(0),
  /** The history's rows already written (historyRewrap.ts), in place of `history`'s. */
  historyRows?: Uint8Array,
): Uint8Array {
  const cursorRow = Math.max(1, Math.min(meta.paneHeight, meta.cursorY + 1))
  const cursorCol = Math.max(1, Math.min(meta.paneWidth, meta.cursorX + 1))
  // Say WHICH SCREEN this is, right after the reset that would otherwise decide it for us.
  //
  // `ESC c` resets to the normal buffer, so a keyframe of a pane running a full-screen TUI used to
  // arrive describing a normal screen. The receiver believed it, and that one missing fact closed both
  // ways of scrolling at once: the alternate screen has no scrollback to move through (tmux reports
  // history_size=0 for it), and the emulator's wheel-to-escape handler only runs while it believes it
  // is on the alternate buffer — so the wheel reached neither a local scrollback nor the remote
  // application. Scrolling worked in tmux and did nothing in the window, with no error either side.
  //
  // Sent explicitly in both directions rather than leaning on `ESC c` for the normal case: whether RIS
  // leaves the alternate buffer is emulator-dependent, and a pane that has just come OUT of a TUI must
  // not be left in it.
  const screen = meta.alternateOn ? '\u001b[?1049h' : '\u001b[?1049l'
  const prefix = Buffer.from(
    `\u001bc${screen}\u001b[?25l\u001b[?7l\u001b[H\u001b[2J`,
    'utf8',
  )
  const normalizedHistory = historyRows ?? normalizeTmuxHistoryLines(history)
  // Push every captured history row above the viewport before clearing the
  // visible grid. `capture-pane -e` serializes tmux's already-rendered cells:
  // it preserves SGR colours but contains none of the original TUI's cursor
  // movement/repaint stream. Extra blank rows move even the newest history
  // lines into local scrollback; ESC[2J clears only the viewport, not it.
  const historySuffix = Buffer.from(
    `${normalizedHistory.length === 0 ? '' : '\r\n'.repeat(meta.paneHeight)}\u001b[H\u001b[2J${mouseModes(meta)}`,
    'utf8',
  )
  const raw = Buffer.from(capture)
  const rows: Buffer[] = []
  const carry = new SgrCarry()
  let start = 0
  let rowIndex = 0
  for (let index = 0; index <= raw.length && rowIndex < meta.paneHeight; index++) {
    if (index !== raw.length && raw[index] !== 0x0a) continue
    let end = index
    if (end > start && raw[end - 1] === 0x0d) end--
    // Position every tmux row independently. tmux and the receiving emulator
    // can disagree on the display width of Unicode scalars; replaying rows via
    // CRLF lets that disagreement wrap one row into another. Absolute row
    // placement with autowrap disabled makes the captured grid authoritative.
    //
    // Each row ends reset and begins with whatever SGR tmux carried into it (see SgrCarry): a wrapped
    // dim line's second row has no SGR of its own in the capture.
    const row = raw.subarray(start, end)
    const restore = carry.restore
    carry.feed(row.toString('latin1'))
    rows.push(
      Buffer.from(`\u001b[${rowIndex + 1};1H${restore}`, 'utf8'),
      row,
      Buffer.from('\u001b[0m', 'utf8'),
    )
    rowIndex++
    start = index + 1
  }
  // tmux keeps visibility separately from the cursor coordinate. Full-screen
  // TUIs such as Command Code park the physical cursor below their own painted
  // input and hide it; restoring the coordinate with an unconditional ?25h
  // creates a stray block cursor in remote renderers.
  const cursorVisibility = meta.cursorVisible ? 'h' : 'l'
  const suffix = Buffer.from(`\u001b[${cursorRow};${cursorCol}H\u001b[?7h\u001b[?25${cursorVisibility}`, 'utf8')
  return Buffer.concat([prefix, normalizedHistory, historySuffix, ...rows, suffix])
}

export interface ControlCommandResult {
  ok: boolean
  stdout: Buffer
}

interface PendingControlCommand {
  command: string
  lines: Buffer[]
  commandNumber: string | null
  /** Cancels the head's deadline (`armHead`). */
  timer: (() => void) | null
  onEnd?: () => void
  resolve: (result: ControlCommandResult) => void
}

const CONTROL_COMMAND_FAILED: ControlCommandResult = { ok: false, stdout: Buffer.alloc(0) }

export interface ControlCommandQueueDeps {
  /** Write one command line to the control client's stdin. False means the pipe is gone. */
  write: (line: string) => boolean
  /** The channel is unusable and the owning stream must be torn down. */
  onFatal: (reason: string) => void
  timeoutMs?: number
}

/**
 * FIFO bookkeeping for `tmux -C` commands, kept free of the child process so it can be tested
 * directly — the same reason the octal/capture helpers above are exported as pure functions.
 *
 * tmux answers EVERY command with its own `%begin`/`%end` block, strictly in the order the commands
 * were written, with monotonically increasing command numbers. That holds even when several
 * commands are written back-to-back while an earlier one is still outstanding, which is what lets
 * keystrokes pipeline instead of waiting for whatever else is in flight.
 */
export class ControlCommandQueue {
  private readonly waiting: PendingControlCommand[] = []
  private readonly outstanding: PendingControlCommand[] = []
  private ready = false
  private readonly timeoutMs: number

  constructor(private readonly deps: ControlCommandQueueDeps) {
    this.timeoutMs = deps.timeoutMs ?? CONTROL_COMMAND_TIMEOUT_MS
  }

  /** No command of ours is in flight. Distinguishes tmux's own opening transaction from a reply. */
  get idle(): boolean {
    return this.outstanding.length === 0
  }

  get isReady(): boolean {
    return this.ready
  }

  /** `tmux -C attach-session` finishes its own initial transaction before ours may be written. */
  markReady(): void {
    if (this.ready) return
    this.ready = true
    this.pump()
  }

  run(command: string, onEnd?: () => void): Promise<ControlCommandResult> {
    return this.runTogether([{ command, onEnd }])[0]
  }

  /**
   * Commands that must read the pane as one moment, written to tmux in one write. tmux runs every line it read at once
   * before it reads the pane again; one line per write, a pane printing all it could had output read between three
   * captures in 28 of 500 tries, and 0 of 500 written together (tmux 3.7c, 2026-10-14). Not one line joined with `;`:
   * tmux answers each command of a list in its own `%begin`/`%end`, and none after one that fails, which the queue
   * could no longer pair with what it sent.
   */
  runTogether(commands: ReadonlyArray<{ command: string; onEnd?: () => void }>): Array<Promise<ControlCommandResult>> {
    const results = commands.map(({ command, onEnd }) => new Promise<ControlCommandResult>((resolve) => {
      this.waiting.push({ command, lines: [], commandNumber: null, timer: null, onEnd, resolve })
    }))
    this.pump()
    return results
  }

  handleBegin(commandNumber: string): void {
    const pending = this.outstanding.find((command) => command.commandNumber == null)
    if (pending) pending.commandNumber = commandNumber
  }

  /** Response lines belong to the head: tmux never interleaves two commands' output. */
  appendResponseLine(line: Buffer): void {
    const head = this.outstanding[0]
    if (head?.commandNumber != null) head.lines.push(Buffer.from(line))
  }

  handleCompleted(kind: 'end' | 'error', commandNumber: string): boolean {
    const head = this.outstanding[0]
    if (!head || head.commandNumber !== commandNumber) return false
    this.outstanding.shift()
    head.timer?.()
    head.timer = null
    if (kind === 'end') head.onEnd?.()
    head.resolve({ ok: kind === 'end', stdout: decodeControlResponse(head.lines) })
    this.armHead()
    return true
  }

  failAll(): void {
    const abandoned = [...this.outstanding.splice(0), ...this.waiting.splice(0)]
    for (const command of abandoned) {
      command.timer?.()
      command.timer = null
      command.resolve(CONTROL_COMMAND_FAILED)
    }
  }

  /** Everything waiting goes in one write: commands queued together (`runTogether`), or before the attach answered. */
  private pump(): void {
    if (!this.ready || this.waiting.length === 0) return
    const batch = this.waiting.splice(0)
    let written = false
    try {
      written = this.deps.write(batch.map(({ command }) => `${command}\n`).join(''))
    } catch {
      written = false
    }
    if (!written) {
      for (const next of batch) next.resolve(CONTROL_COMMAND_FAILED)
      return
    }
    this.outstanding.push(...batch)
    this.armHead()
  }

  /**
   * Only the head is timed. The timeout has to start when a command reaches the head rather than
   * when it was written: commands now pipeline, so anything queued behind a slow `capture-pane`
   * would otherwise expire while tmux was still legitimately busy and take the stream down with it.
   */
  private armHead(): void {
    const head = this.outstanding[0]
    if (!head || head.timer) return
    // Running time, not wall time: a daemon whose event loop was held wakes to this deadline before it
    // reads the reply tmux sent meanwhile, and took the stream down for a command that had answered
    // (patientExec.ts, e2e/stall.e2e.ts).
    head.timer = patientDeadline(this.timeoutMs, () => {
      if (this.outstanding[0] !== head) return
      this.deps.onFatal('tmux control command timed out')
    })
  }
}

/** tmux escapes a response line that starts with `%` as `%%`; the rest is octal-escaped as usual. */
function decodeControlResponse(lines: readonly Buffer[]): Buffer {
  const chunks: Buffer[] = []
  for (const line of lines) {
    const escaped = line.subarray(0, 2).equals(Buffer.from('%%')) ? line.subarray(1) : line
    chunks.push(Buffer.from(decodeTmuxControlBytes(escaped)), Buffer.from('\n'))
  }
  return Buffer.concat(chunks)
}

export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {
  readonly runtime: TmuxRuntimeRef
  private readonly child: ChildProcessWithoutNullStreams
  private lineBuffer = Buffer.alloc(0)
  private closed = false
  private closeNotified = false
  // `tmux -C attach-session` emits its own initial %begin/%end transaction.
  // Do not assign that command number to our first queued command.
  private readonly commands: ControlCommandQueue
  private operationTail: Promise<void> = Promise.resolve()
  private snapshotGated = false
  private snapshotPostCut: Buffer[] = []
  private snapshotPostCutBytes = 0
  private snapshotLastOutputAt = 0
  /** How many of the pane's output notifications have been read: one that moved between two command replies was read
   *  by tmux between the two commands. */
  private outputNotifications = 0
  /** When this stream last changed the pane's size (`resize`), which an engine may answer by printing again. */
  private resizedAt = Number.NEGATIVE_INFINITY
  private lastTuiScrollAt = 0
  /** What the snapshot's waits read (`waitForSnapshotQuiet`, `waitForRepaint`). */
  private readonly gate: SnapshotGate = {
    closed: () => this.closed,
    gated: () => this.snapshotGated,
    held: () => this.snapshotPostCut,
    lastOutputAt: () => this.snapshotLastOutputAt,
    resizedAt: () => this.resizedAt,
  }
  private settleAttach: () => void = () => {}
  /**
   * Settles once tmux has answered this client's attach (its first `%end`), or the client is gone. From
   * then on the server holds the state it writes this client's notifications into: on a tmux before 3.7
   * one sent before then crashed the server (tmuxControlGate.ts).
   */
  readonly attached: Promise<void> = new Promise((resolve) => { this.settleAttach = resolve })

  private constructor(
    paneId: string,
    child: ChildProcessWithoutNullStreams,
    private readonly sink: TerminalStreamSink,
    private readonly readOnly = false,
    /** What this tmux can do: read once, at open, so a keystroke never waits on it (see `writeRaw`). */
    private readonly features: TmuxFeatures = tmuxFeaturesOf(null),
  ) {
    this.runtime = { backend: 'tmux', paneId }
    this.child = child
    this.commands = new ControlCommandQueue({
      write: (line) => {
        if (this.closed || !child.stdin.writable) return false
        // A large paste can outrun the pipe. Node buffers what does not fit and drains it in
        // order, so a false return here is backpressure, not loss — never a reason to drop input.
        child.stdin.write(line)
        return true
      },
      onFatal: (reason) => {
        this.notifyClose(reason)
        void this.close()
      },
    })
    child.stdout.on('data', (chunk: Buffer) => this.onStdout(chunk))
    // Pipe failures are emitted asynchronously by stdin, not by ChildProcess.
    // A control client that exits during a write must only end this stream.
    child.stdin.on('error', (error) => {
      this.notifyClose(this.closed ? 'closed' : `tmux control input failed: ${error.message}`)
      void this.close()
    })
    child.once('error', (error) => this.notifyClose(`tmux control client error: ${error.message}`))
    child.once('close', (code) => this.notifyClose(this.closed ? 'closed' : `tmux control client exited (${code ?? 'signal'})`))
  }

  static async open(paneId: string, size: TerminalStreamSize, sink: TerminalStreamSink, readOnly = false): Promise<TerminalReadResult<TmuxControlStream>> {
    const original = await paneMeta(paneId)
    if (!original) return { state: 'failed', reason: 'tmux pane metadata is unavailable' }
    if (original.windowPanes !== 1) return { state: 'failed', reason: 'TERMINAL_MULTI_PANE_UNSUPPORTED' }
    const features = await tmuxFeatures()
    // `ignore-size` keeps this client's size out of the window's. Client flags are tmux 3.2; before it
    // the flag was a usage error, the client exited at once, and no terminal opened on 3.1 or older.
    // Nothing is lost there: a control client that never sets its own size counts for none (`resize`).
    const flags = features.clientFlags ? ['-f', 'ignore-size'] : []
    // On a tmux before 3.7, nothing tmux tells every control client may happen while this one attaches:
    // it crashed the server, and every agent with it (tmuxControlGate.ts).
    const leave = await enterTmuxRoom('attach', features)
    const child = spawn('tmux', ['-C', 'attach-session', ...flags, '-t', paneId], {
      stdio: ['pipe', 'pipe', 'pipe'],
    })
    const spawned = await new Promise<boolean>((resolve) => {
      let settled = false
      child.once('spawn', () => { if (!settled) { settled = true; resolve(true) } })
      child.once('error', () => { if (!settled) { settled = true; resolve(false) } })
    })
    if (!spawned) {
      leave()
      return { state: 'failed', reason: 'tmux control client could not start' }
    }
    const stream = new TmuxControlStream(paneId, child, sink, readOnly, features)
    const held = setTimeout(leave, ATTACH_HOLD_MAX_MS)
    held.unref()
    void stream.attached.then(() => {
      clearTimeout(held)
      leave()
    })
    const resized = readOnly ? TERMINAL_ACTION_SUCCEEDED : await stream.resize(size)
    if (resized.state !== 'succeeded') {
      await stream.close()
      return { state: 'failed', reason: resized.reason }
    }
    return { state: 'succeeded', value: stream }
  }

  private onStdout(chunk: Buffer): void {
    this.lineBuffer = Buffer.concat([this.lineBuffer, chunk])
    while (true) {
      const newline = this.lineBuffer.indexOf(0x0a)
      if (newline < 0) break
      let line = this.lineBuffer.subarray(0, newline)
      if (line.at(-1) === 0x0d) line = line.subarray(0, line.length - 1)
      this.lineBuffer = this.lineBuffer.subarray(newline + 1)
      this.onControlLine(line)
    }
  }

  private onControlLine(line: Buffer): void {
    const output = parseTmuxControlOutput(line)
    if (output) {
      if (output.paneId === this.runtime.paneId) this.routeOutput(output.data)
      return
    }
    const text = line.toString('ascii')
    const begin = /^%begin\s+\d+\s+(\d+)\s+\d+$/.exec(text)
    if (begin) {
      this.commands.handleBegin(begin[1])
      return
    }
    const completed = /^%(end|error)\s+\d+\s+(\d+)\s+\d+$/.exec(text)
    if (completed) {
      if (!this.commands.isReady && this.commands.idle) {
        this.commands.markReady()
        this.settleAttach()
        return
      }
      this.commands.handleCompleted(completed[1] === 'end' ? 'end' : 'error', completed[2])
      return
    }
    const paused = /^%pause\s+(%\d+)$/.exec(text)
    if (paused?.[1] === this.runtime.paneId && !this.closed) {
      // Manual tmux pause drops pane bytes rather than replaying them. Never
      // use it for app backpressure; recover an unexpected pause immediately.
      void this.runControlCommand(`refresh-client -A '${this.runtime.paneId}:continue'`)
      return
    }
    if (text.startsWith('%exit')) {
      this.failControlCommands()
      this.notifyClose(this.closed ? 'closed' : 'tmux pane/control client closed')
      return
    }
    // tmux escapes command output that starts with `%` as `%%`. Every other
    // leading-percent line is an asynchronous control-mode notification and
    // must not be mixed into a command response.
    if (text.startsWith('%') && !text.startsWith('%%')) return
    this.commands.appendResponseLine(line)
  }

  private routeOutput(bytes: Uint8Array): void {
    this.outputNotifications++
    this.deliverOutput(bytes)
  }

  /** To the sink, or, while a snapshot is being taken, behind its gate. */
  private deliverOutput(bytes: Uint8Array): void {
    if (!this.snapshotGated) {
      this.sink.onData(bytes)
      return
    }
    const chunk = Buffer.from(bytes)
    this.snapshotPostCut.push(chunk)
    this.snapshotPostCutBytes += chunk.length
    this.snapshotLastOutputAt = Date.now()
    if (this.snapshotPostCutBytes > SNAPSHOT_BUFFER_MAX_BYTES) {
      this.failControlCommands()
      this.notifyClose('tmux snapshot output exceeded safe buffer limit')
      void this.close()
    }
  }

  private runControlCommand(command: string, onEnd?: () => void): Promise<ControlCommandResult> {
    if (this.closed || !this.child.stdin.writable) return Promise.resolve(CONTROL_COMMAND_FAILED)
    return this.commands.run(command, onEnd)
  }

  private runControlCommands(commands: ReadonlyArray<{ command: string; onEnd?: () => void }>): Array<Promise<ControlCommandResult>> {
    if (this.closed || !this.child.stdin.writable) return commands.map(() => Promise.resolve(CONTROL_COMMAND_FAILED))
    return this.commands.runTogether(commands)
  }

  private serializeOperation<T>(operation: () => Promise<T>): Promise<T> {
    const result = this.operationTail.then(operation, operation)
    this.operationTail = result.then(() => undefined, () => undefined)
    return result
  }

  private failControlCommands(): void {
    this.commands.failAll()
  }

  private notifyClose(reason: string): void {
    this.settleAttach()
    if (this.closeNotified) return
    this.closeNotified = true
    this.failControlCommands()
    this.sink.onClose(reason)
  }

  beginSnapshot(): void {
    if (this.snapshotGated) return
    this.snapshotGated = true
    this.snapshotPostCut = []
    this.snapshotPostCutBytes = 0
    this.snapshotLastOutputAt = Date.now()
  }

  private waitForSnapshotQuiet(): Promise<void> {
    return waitForSnapshotQuiet(this.gate)
  }

  private waitForRepaint(repaint: SnapshotRepaint): Promise<void> {
    return waitForRepaint(this.gate, repaint)
  }

  async snapshot(options?: SnapshotOptions): Promise<TerminalReadResult<TerminalStreamSnapshot>> {
    return this.serializeOperation(async () => {
      if (!this.snapshotGated) return { state: 'failed', reason: 'tmux snapshot gate is not active' }
      const repaint = options?.repaint
      if (!repaint) return this.capturePane(options)
      if (repaint.cleared || Date.now() - this.resizedAt < repaint.withinMs) await this.waitForRepaint(repaint)
      const taken = await this.capturePane(options, repaint)
      if (taken !== 'printing') return taken
      // The print began before the capture's cut and had not ended at it: after the wait above gave up, or where there
      // was none to make. The viewer would draw the cleared or half-printed screen that capture holds, and the live
      // output after it begins with no clear for the stream manager to see. It is taken again once the print ends.
      await this.waitForRepaint({ ...repaint, cleared: true })
      return this.capturePane(options)
    })
  }

  /**
   * The pane, read for a keyframe. With `print`, what the capture's cut discards is read for that print
   * (`printInProgress`), and a capture taken while it was under way comes back as `'printing'`.
   */
  private capturePane(options: SnapshotOptions | undefined): Promise<TerminalReadResult<TerminalStreamSnapshot>>
  private capturePane(
    options: SnapshotOptions | undefined, print: { clears: string; ends: string },
  ): Promise<TerminalReadResult<TerminalStreamSnapshot> | 'printing'>
  private async capturePane(
    options: SnapshotOptions | undefined, print?: { clears: string; ends: string },
  ): Promise<TerminalReadResult<TerminalStreamSnapshot> | 'printing'> {
    // -N is required for TUI fidelity: styled blank cells (for example the
    // Codex input box background) live in trailing spaces that tmux otherwise
    // trims from each captured row. Deliberately do not use capture-pane -S:
    // tmux scrollback contains old full-screen TUI repaint frames. Replaying
    // those frames into a fresh emulator corrupts the visible screen.
    // -N is tmux 3.1. Before it the flag failed the capture, and with it every
    // snapshot: the terminal never showed. Without it the screen is all there,
    // short only of the colour of a row's trailing blanks.
    const keepTrailing = this.features.captureTrailingSpaces ? ' -N' : ''
    const baseCapture = `capture-pane -p -e${keepTrailing} -t ${this.runtime.paneId}`
    // Attaching a control client can trigger an immediate TUI repaint. Wait
    // before reading both cursor metadata and the grid so the synthesized
    // keyframe cannot combine a post-repaint grid with pre-repaint cursor
    // coordinates.
    await this.waitForSnapshotQuiet()
    const metadata = await this.runControlCommand(
      `display-message -p -t ${this.runtime.paneId} '${PANE_META_FORMAT}'`,
    )
    if (!metadata.ok) return { state: 'failed', reason: 'tmux snapshot metadata is unavailable' }
    const meta = parsePaneMeta(metadata.stdout)
    if (!meta || meta.windowPanes !== 1) return { state: 'failed', reason: 'tmux snapshot metadata is invalid' }
    // History is a styled cell capture used only to seed the receiver's
    // local scrollback. It preserves SGR attributes without replaying old
    // TUI cursor movement. Read it before the authoritative visible-grid cut
    // so concurrent output is included there or in a post-cut delta.
    //
    // Grok (and any TUI that paints in the normal buffer) is the other
    // history trap: tmux reports alternate_on=0, so a naive capture would
    // seed hundreds of prior full-screen repaint frames. The window then
    // shows stacked empty chrome above the live header, and the wheel
    // scrolls that junk locally instead of the program.
    const tuiOwnsScrollback = options?.tuiOwnsScrollback === true
    const seedsHistory = !meta.alternateOn && !tuiOwnsScrollback
    const conversation = seedsHistory && options?.conversationHistory === true
    const historyRange = `-t ${this.runtime.paneId} -S -${conversation ? CONVERSATION_HISTORY_LINES : SNAPSHOT_HISTORY_LINES} -E -1`
    const plainHistory = `capture-pane -p -e${keepTrailing} ${historyRange}`
    const { history, rows: historyRows } = conversation && meta.paneWidth >= REWRAP_MIN_WIDTH
      ? await this.conversationHistory(plainHistory, historyRange, meta.paneWidth)
      : { history: seedsHistory ? (await this.runControlCommand(plainHistory)).stdout : Buffer.alloc(0), rows: null }
    let printing = false
    // The cursor is read again with the grid, in the same write: tmux answers both before it reads the pane
    // again (`runTogether`). Taken only from the read above, before the history captures, the cursor of a
    // pane that printed meanwhile was a step behind the grid it came with — the receiver then drew the next
    // output at the old place. A keystroke echoed while its own keyframe is taken is exactly that, and its
    // keyframe no longer holds the keystroke back (backendSocket.ts `enqueueTerminalBinary`).
    const [screenMetadata, capture] = await Promise.all(this.runControlCommands([
      { command: `display-message -p -t ${this.runtime.paneId} '${PANE_META_FORMAT}'` },
      {
        command: baseCapture,
        onEnd: () => {
          // `%end` is the ordered cut. Notifications observed before it are
          // represented by capture-pane; only later output may follow the keyframe.
          if (print) printing = printInProgress(this.snapshotPostCut, print)
          this.snapshotPostCut = []
          this.snapshotPostCutBytes = 0
        },
      },
    ]))
    if (!capture.ok) return { state: 'failed', reason: 'tmux snapshot failed' }
    if (printing) return 'printing'
    const screen = screenMetadata.ok ? parsePaneMeta(screenMetadata.stdout) : null
    if (!screen || screen.windowPanes !== 1) return { state: 'failed', reason: 'tmux snapshot metadata is invalid' }
    const bytes = tmuxKeyframe(capture.stdout, screen, history, historyRows, { conversation, tuiOwnsScrollback })
    return {
      state: 'succeeded',
      value: {
        bytes,
        cols: screen.paneWidth,
        rows: screen.paneHeight,
      },
    }
  }

  /**
   * A conversation's history as tmux has it, and re-wrapped by word (historyRewrap.ts) where a line of it is wider than
   * the pane: tmux re-wraps it by the cell whenever a takeover narrows the pane. That reads the same rows joined back
   * into the lines they were (-J), and whether the last of them runs on into the visible grid (one line from -1 to 0,
   * not two). The three must read one history, so they are written to tmux together (`runTogether`); should the
   * pane's output be read between them all the same, they are read again, and a second time the history goes as tmux
   * has it. The plain capture is the keyframe's whenever there is nothing to re-wrap or the re-wrap cannot be used.
   */
  private async conversationHistory(
    plainHistory: string, range: string, width: number,
  ): Promise<{ history: Uint8Array; rows: Uint8Array | null }> {
    let history: Uint8Array = Buffer.alloc(0)
    for (let attempt = 0; attempt < 2; attempt++) {
      let readAtFirst = -1
      let readAtLast = -2
      const [plain, joined, seam] = await Promise.all(this.runControlCommands([
        { command: plainHistory, onEnd: () => { readAtFirst = this.outputNotifications } },
        { command: `capture-pane -p -e -J ${range}` },
        { command: `capture-pane -p -J -t ${this.runtime.paneId} -S -1 -E 0`, onEnd: () => { readAtLast = this.outputNotifications } },
      ]))
      history = plain.stdout
      if (!plain.ok || !joined.ok || !seam.ok) return { history, rows: null }
      if (readAtFirst !== readAtLast) continue
      try {
        // One line, its newline the last byte: rows -1 and 0 are one line.
        const lastContinues = seam.stdout.indexOf(0x0a) === seam.stdout.length - 1
        return { history, rows: rewrapTmuxHistory(joined.stdout, width, { lastContinues }) }
      } catch {
        // A history the re-wrap cannot read is sent as tmux has it, as it always was.
        return { history, rows: null }
      }
    }
    return { history, rows: null }
  }

  endSnapshot(): void {
    if (!this.snapshotGated) return
    this.snapshotGated = false
    const postCut = this.snapshotPostCut
    this.snapshotPostCut = []
    this.snapshotPostCutBytes = 0
    // The sink can begin the next snapshot from what is released here: the stream manager reads it for an engine's
    // print as it reads live output (terminalStreamManager.ts `repaintBegan`), and Codex's clear could be in it. What
    // is left then comes before that snapshot's cut, and is held behind its gate like any output from then on.
    for (const chunk of postCut) this.deliverOutput(chunk)
  }

  /**
   * Keystrokes go down the control client that is already attached, never a fresh `tmux` process.
   * Spawning one cost 4.4ms at the median and 13ms at the tail — per keystroke — against 0.2ms
   * here, and an 8 KiB paste went from 184ms across 32 spawns to under a millisecond.
   *
   * Deliberately NOT wrapped in `serializeOperation`: input must not queue behind a `snapshot()`
   * or a `resize()`. Ordering against those still holds because tmux runs control commands in the
   * order they were written, which is also what keeps the snapshot's `%end` cut correct.
   *
   * ⚠️ Every `runControlCommand` below MUST stay before the first `await`. The caller
   * (TerminalStreamManager.input) no longer waits for this promise before handing over the next
   * keystroke, so the order keystrokes reach tmux is the order these calls run synchronously — an
   * `await` slipped in ahead of them would let a later keystroke overtake an earlier one.
   */
  async writeRaw(bytes: Uint8Array): Promise<TerminalActionResult> {
    if (this.readOnly) return terminalActionNotStarted('VIEW_ONLY')
    if (this.closed) return terminalActionNotStarted('terminal stream is closed')
    if (bytes.length === 0) return TERMINAL_ACTION_SUCCEEDED
    const sends: Array<Promise<ControlCommandResult>> = []
    // Every chunk is handed to the queue before any reply is awaited, so a paste costs one
    // round-trip rather than one per chunk. tmux applies them in the order they were written.
    // `send-keys -H` is tmux 3.0: before it, every keystroke was a usage error and nothing typed in
    // a terminal reached the engine. There the same bytes go as literal text (`literalKeyCommands`).
    const commands = this.features.sendKeysHex
      ? hexKeyCommands(this.runtime.paneId, bytes)
      : literalKeyCommands(this.runtime.paneId, bytes)
    for (const command of commands) sends.push(this.runControlCommand(command))
    const results = await Promise.all(sends)
    const failedAt = results.findIndex((result) => !result.ok)
    if (failedAt < 0) return TERMINAL_ACTION_SUCCEEDED
    return failedAt === 0
      ? terminalActionNotStarted('tmux raw input could not be sent')
      : terminalActionPossiblyExecuted('tmux raw input stopped after a partial write')
  }

  /**
   * A clipboard paste, delivered as one bracketed `paste-buffer` rather than chunked `send-keys -H`
   * bursts like `writeRaw` — see `pasteRawIntoTmux` for why a paste needs this instead of the
   * keystroke path (chunking there is fine for typing, but reads as several separate pastes to a
   * program's own paste-detector once split across multiple `send-keys` commands).
   */
  async pasteRaw(text: string, allowed?: () => boolean): Promise<TerminalActionResult> {
    if (this.readOnly) return terminalActionNotStarted('VIEW_ONLY')
    if (this.closed) return terminalActionNotStarted('terminal stream is closed')
    if (text.length === 0) return TERMINAL_ACTION_SUCCEEDED
    const pasted = await pasteRawIntoTmux(this.runtime.paneId, text, () => !this.closed && (allowed?.() ?? true))
    return pasted
      ? TERMINAL_ACTION_SUCCEEDED
      : terminalActionNotStarted('tmux paste-buffer could not be sent')
  }

  /** Scroll a full-screen TUI by sending PageUp/PageDown into the pty.
   *
   *  Grok declares mouse-tracking but echoes SGR wheel reports as literal
   *  characters, so the desktop does not send wheel bytes. tmux copy-mode is
   *  the wrong substitute: for an alt-screen TUI, tmux history is prior
   *  full-screen repaint frames, which stacked as empty Grok chrome above the
   *  live screen. Grok's own PageUp/PageDown scroll the conversation even
   *  while the prompt is focused. */
  async scroll(direction: 'up' | 'down', lines: number): Promise<TerminalActionResult> {
    if (this.readOnly) return terminalActionNotStarted('VIEW_ONLY')
    if (this.closed) return terminalActionNotStarted('terminal stream is closed')
    const pages = tuiScrollPageCount(lines)
    if (pages <= 0) return TERMINAL_ACTION_SUCCEEDED
    const now = Date.now()
    if (now - this.lastTuiScrollAt < TUI_SCROLL_MIN_INTERVAL_MS) return TERMINAL_ACTION_SUCCEEDED
    this.lastTuiScrollAt = now
    // Leave copy-mode if an older daemon (or a leftover gesture) parked there.
    // `send-keys -X` fails when the pane is not in a mode; that is the common
    // case and is ignored. Both commands are queued before either reply so
    // cancel still runs first (the queue is FIFO) without an extra round-trip.
    const key = direction === 'up' ? 'PageUp' : 'PageDown'
    const cancel = this.runControlCommand(`send-keys -X -t ${this.runtime.paneId} cancel`)
    const scrolled = this.runControlCommand(
      `send-keys -N ${pages} -t ${this.runtime.paneId} ${key}`,
    )
    await cancel
    if (!(await scrolled).ok) return terminalActionPossiblyExecuted('tmux TUI scroll did not complete')
    return TERMINAL_ACTION_SUCCEEDED
  }

  async resize(requested: TerminalStreamSize): Promise<TerminalActionResult> {
    if (this.readOnly) return terminalActionNotStarted('VIEW_ONLY')
    return this.serializeOperation(async () => {
      if (this.closed) return terminalActionNotStarted('terminal stream is closed')
      const metadata = await this.runControlCommand(
        `display-message -p -t ${this.runtime.paneId} '${PANE_META_FORMAT}'`,
      )
      if (!metadata.ok) return terminalActionNotStarted('tmux pane disappeared')
      const meta = parsePaneMeta(metadata.stdout)
      if (!meta) return terminalActionNotStarted('tmux pane disappeared')
      if (meta.windowPanes !== 1) return terminalActionNotStarted('TERMINAL_MULTI_PANE_UNSUPPORTED')
      const size = this.features.resizeWindow
        ? boundedSize(requested)
        : boundedSize(requested, { cols: OLD_TMUX_MIN_CLIENT_SIZE, rows: OLD_TMUX_MIN_CLIENT_SIZE })
      // A repeated open/focus can legitimately ask for the grid already in
      // use. Avoid a redundant resize-window because full-screen TUIs may
      // repaint on SIGWINCH even when the dimensions did not change.
      if (meta.windowWidth === size.cols && meta.windowHeight === size.rows) {
        return TERMINAL_ACTION_SUCCEEDED
      }
      // `resize-window` is tmux 2.9. Before it a control client gives its own size, and the window takes
      // the smallest of its session's clients: alone with the agent, this one.
      this.resizedAt = Date.now()
      const result = await this.runControlCommand(this.features.resizeWindow
        ? `resize-window -t ${meta.windowId} -x ${size.cols} -y ${size.rows}`
        : `refresh-client -C ${size.cols},${size.rows}`)
      if (!result.ok) return terminalActionPossiblyExecuted('tmux resize did not complete')
      return TERMINAL_ACTION_SUCCEEDED
    })
  }

  async pauseOutput(): Promise<TerminalActionResult> {
    if (this.closed || !this.child.stdin.writable) return terminalActionNotStarted('terminal stream is closed')
    // TerminalStreamManager pauses downstream delivery while continuing to
    // drain exact tmux bytes into its bounded FIFO. tmux's manual `pause`
    // state is deliberately not used because it does not replay missed bytes.
    return TERMINAL_ACTION_SUCCEEDED
  }

  async resumeOutput(): Promise<TerminalActionResult> {
    if (this.closed || !this.child.stdin.writable) return terminalActionNotStarted('terminal stream is closed')
    return TERMINAL_ACTION_SUCCEEDED
  }

  async close(): Promise<void> {
    if (this.closed) return
    this.closed = true
    // Keep the last applied grid. Restoring the headless tmux default here
    // makes agent switching shrink and immediately re-expand the pane; TUIs
    // such as Grok preserve those intermediate repaint fragments in the live
    // screen. The next controller will resize only if its grid truly differs.
    //
    // A control client going is a notification to every other (`%client-detached`), so on a tmux before
    // 3.7 it goes in the gate's other room from one that is attaching (tmuxControlGate.ts).
    await inTmuxRoom('notify', async () => {
      if (this.child.stdin.writable) {
        try { this.child.stdin.write('detach-client\n') } catch { /* ignore */ }
      }
      if (!(await this.exited())) {
        this.child.kill('SIGTERM')
        await this.exited()
      }
      // tmux tells the others when it reads this client's socket close, which comes after the client
      // has exited. A command another client sends after that is answered only once tmux has read it,
      // so the room is not left while that notification may still be on its way.
      if (needsControlGate(this.features)) await execTmux(['display-message', '-p', '#{pid}'])
    }, this.features)
  }

  private exited(): Promise<boolean> {
    return new Promise<boolean>((resolve) => {
      if (this.child.exitCode != null || this.child.signalCode != null) { resolve(true); return }
      const timer = setTimeout(() => resolve(false), CLOSE_EXIT_WAIT_MS)
      this.child.once('close', () => { clearTimeout(timer); resolve(true) })
    })
  }
}