Skip to content

AI, fully local on your computer.

58.7 KB
Raw Blame
import {
  LlamaServer,
  combineSignals,
  isBindRaceError,
  isStartAbortError,
  waitUnlessAborted,
  type LlamaServerOptions
} from '../runtime/sidecar'
import { isEngineCannotRunError, isEngineFilesUnreadableError } from '../runtime/engine-load'
import { RuntimeUnresponsiveError, isRuntimeUnresponsiveError } from '../runtime/llama'
import { createPlacementParser } from '../runtime/placement'
import { translationRanOnProcessor } from '../../../shared/runtime-status'
import { log } from '../logging'
import type { BoundModelStartCheck } from '../models'
import { readCompletionSSE, type CompletionFinal } from './completion'
import { buildTranslationPrompt, TRANSLATION_STOP_TOKEN, type TranslationLangCode } from './prompt'
import type { TranslationCpuCause, TranslationDeviceStatus } from '../../../shared/types'

// The lazily-started TranslateGemma sidecar (TG wave, plan §2 D1). It composes `LlamaServer`
// DIRECTLY — like the E5 embedder / reranker / vision, NOT the chat `RuntimeManager` — so it does
// NOT inherit the chat slot's `CHAT_SERVER_ARGS` (which hard-code `--jinja`). That matters here for
// a hard reason, not just cleanliness: the `--jinja` embedded-template path is REGRESSED for
// TranslateGemma (issue #20305, fix PR #20956 still open — re-verified 2026-07-05), so this sidecar
// launches WITHOUT `--jinja` and formats the trained prompt in app code (`prompt.ts`), calling the
// raw `/completion` endpoint (`completion.ts`). See docs/model-policy.md "The translation role".
//
// The lifecycle is a HYBRID of two established precedents:
//   • vision/runtime.ts — the SOFT idle-teardown interlock (a 12B model must not sit ~10 GB
//     co-resident with a resident chat model + embedder forever; plan §2 D9). Every use cancels
//     the idle timer; it re-arms only when the LAST in-flight translate settles, or when a start
//     lands after every translate waiting for it was cancelled (#637).
//   • reranker/llama.ts — `stop()` (permanent, quit) vs `suspend()` (soft, workspace lock →
//     lazy restart on next translate), the `tearingDown` latch that bars a racing start from
//     orphaning a child across a lock, and the bind-race-forgiving `startFailed` latch.
// This instance is held on `AppContext` for the whole session (unlike vision, whose orchestrator
// rebuilds the runtime), so it needs the reranker's suspend/restart distinction, not vision's
// discard-and-rebuild.

/**
 * Pin the translation sidecar to a SINGLE server slot (plan §2 D8/D9). Translation windows are run
 * STRICTLY SEQUENTIALLY (the doc-task FIFO at TG-3, one window at a time in the view at TG-4), so a
 * single slot is correct — and it contains the Windows-Vulkan hang under PARALLEL translation load
 * (#25142, seen 2026-06-29 on Intel Arc). It also avoids the default `n_slots = 4` + unified-KV
 * context split that starved the vision sidecar (RUNTIME-5): found on b9849, still the default on
 * b11146 (measured 2026-10-13, #660: `n_slots = 4, kv_unified = 'true'` without the flag,
 * `n_slots = 1, kv_unified = 'false'` with it) and on the b12110 pin (#729: the same `--help` defaults,
 * and `n_slots = 1, kv_unified = 'false'` with the flag).
 */
export const TRANSLATION_SLOT_ARGS = ['--parallel', '1'] as const

/**
 * Prefill in 512-token batches (#605, owner call). The server sends a prompt-progress frame after
 * each batch, and those frames are the only sign that a prefill is moving (`readCompletionSSE`'s
 * compute clock). At the server's default 2048-token batch a whole window (≤ ~1,950 prompt tokens)
 * is one batch, so nothing arrives between 0 % and 100 %. The physical batch is the server's
 * default 512 either way, so the compute is the same — measured on b11146 (the 4B, 1,263 tokens,
 * the CPU posture): 29.9 / 28.6 s at the default, 30.8 / 26.3 s at 512. It also bounds what a
 * cancelled request leaves for the next one to wait out: the server stops between batches.
 */
export const TRANSLATION_BATCH_ARGS = ['--batch-size', '512', '--ubatch-size', '512'] as const

/**
 * Force-CPU device args — the translation analogue of the chat ladder's rung 2 (`--device none` is
 * the ONLY CPU-forcing mechanism; NEVER pass `-ngl`). Used whenever GPU must not be attempted:
 * `gpuMode: 'off'`, a persisted `gpuAutoDisabled`, this runtime's own session fallback latch, or
 * the #473 headroom gate's processor verdict (`gpuHeadroom` below).
 *
 * History: TG-2 shipped the sidecar hard-pinned to these args (plan §2 D8) and TG-6 (2026-07-05)
 * kept the pin for v1 pending a GPU-drive re-smoke — GPU was deferred, NOT rejected. Issue #42
 * (2026-07-09) pulled it forward: the sidecar now honours the SAME Settings signals the chat ladder
 * reads (`gpuMode` + `gpuAutoDisabled`, injected via `TranslationGpuDeps`) and composes NO device
 * args on the GPU attempt (the pinned build's defaults `-ngl auto` + `--fit on` → VRAM-aware
 * offload; unchanged from b9849 to b11146, re-checked against `--help` 2026-10-13, #660; on a
 * GPU-less machine that IS CPU mode, though the load log still prints `offloaded N/N layers` there,
 * so the start's own GPU buffers say where it ran, #671). #25142 (the Windows-Vulkan hang under
 * PARALLEL translation load) stays contained by `--parallel 1` regardless of the device posture. See
 * model-benchmarks.md §11.4.
 */
export const TRANSLATION_CPU_DEVICE_ARGS = ['--device', 'none'] as const

/** The device posture of one sidecar launch: 'auto' = GPU auto-offload (no device args), 'cpu' = forced CPU. */
export type TranslationDevice = 'auto' | 'cpu'

/**
 * The observed outcome of ONE successful sidecar cold start (issue #42 reopen). The device
 * posture alone is NOT the story: under `--fit` (the 'auto' posture) llama.cpp silently squeezes
 * the 12B into whatever VRAM a resident chat model left over, and a partial offload decodes at
 * roughly CPU speed — indistinguishable from "GPU not working" without this record. The layer
 * split is parsed from the server's own load log (`load_tensors: offloaded X/Y layers to GPU`,
 * the only place the real fit outcome is reported — `/props` does not carry it); null when the
 * line wasn't seen. The line alone says nothing about a card (#671): a start with no usable
 * graphics device, and a forced-CPU one, print `offloaded 49/49 layers to GPU` too, so
 * `gpuBuffers` carries the evidence — the chat label's since #653. With liveness added this
 * becomes the wire shape `TranslationDeviceStatus` (shared/types.ts — the Translate screen's
 * #36-style device hint); last-known values survive the idle teardown (`live: false`) so a
 * finished run stays explainable, and reset only with the instance (app restart).
 */
export type TranslationStartInfo = Omit<TranslationDeviceStatus, 'live'>
export type { TranslationDeviceStatus }

/**
 * The Settings-driven GPU signals, injected exactly like the chat ladder's `GpuLadderDeps`
 * (read-callbacks, never the DB — keeps the runtime pure + unit-testable). Both optional; the
 * defaults ('auto', not disabled) mirror `createSelectingRuntimeFactory`.
 */
export interface TranslationGpuDeps {
  /** User intent from Settings ('auto' default). */
  getGpuMode?: () => 'auto' | 'off'
  /** The persisted auto-disable flag (a previously detected GPU problem — chat owns writing it). */
  getGpuAutoDisabled?: () => boolean
  /**
   * #473 ruling 1: the headroom gate, consulted per cold start AFTER the two signals above and the
   * session fallback latch — 'cpu' when this model would not fully fit on the card beside what the
   * app already holds there (`rag/device-posture.ts`, `resolveTranslationDevicePosture`). Omitted →
   * 'auto'. A processor answer carries its reason, recorded with the start for the Translate screen.
   */
  gpuHeadroom?: (modelId: string) => TranslationHeadroomVerdict
}

/** #473: the headroom gate's answer — the card ('auto'), or the processor for the reason named. */
export type TranslationHeadroomVerdict = 'auto' | TranslationCpuCause

/**
 * Override the model's embedded chat template with the built-in `gemma` one (TG-2 smoke finding,
 * 2026-07-05). This is NOT cosmetic — WITHOUT it the b9849 `llama-server` CRASHES AT STARTUP on
 * TranslateGemma (Windows exit 0xC0000409 / std::bad_alloc), even with NO `--jinja`: the server
 * VALIDATES the model's embedded chat template during init, and TranslateGemma's template requires
 * typed `{source_lang_code,target_lang_code}` content the probe can't render
 * ("render_message_to_json: Neither string content nor typed content is supported by the
 * template") → the #20305 minja crash, biting at init rather than per-request. Confirmed on the
 * real pin: with `--chat-template gemma` the server loads + serves cleanly and `/props` reports
 * `chat_template: "gemma"`.
 *
 * SAFE because the translation sidecar drives the RAW `/completion` endpoint with a fully-formed
 * prompt (`prompt.ts`) — the chat template is NEVER applied to our requests (only `/v1/chat/*` and
 * `/apply-template` use it, which we don't call). The built-in `gemma` name selects the LEGACY
 * (non-jinja) template path, so this stays consistent with the no-jinja design (D2): it sidesteps
 * the very minja parser that #20305 breaks. If a future pin lands the #20305 fix (PR #20956, V5),
 * this override can be dropped — the smoke re-decides.
 */
export const TRANSLATION_TEMPLATE_ARGS = ['--chat-template', 'gemma'] as const

/**
 * Log verbosity 4, the chat server's setting (`CHAT_SERVER_ARGS`), for the same reason: the pinned
 * build prints its `offloaded X/Y layers to GPU` load line only from verbosity 4 up. Without it the
 * offload parse below never matched, so the Translate screen fell back to "runs on the graphics
 * card" even when `--fit` gave translation no layers, and the Performance card could never count
 * it on the card (#629). Measured on b11146, 2026-10-07: the default start printed 9 log lines and
 * no offload line; `-lv 4` printed `offloaded 49/49 layers to GPU`. Verbosity 4 also adds
 * per-request DIAGNOSTIC lines (slot, token counts, timings); a real `/completion` request carrying
 * marker words left none of them, and none of the translated text, in the log — the same result
 * `security-model.md` records for chat (DR3).
 */
export const TRANSLATION_LOG_ARGS = ['-lv', '4'] as const

/**
 * The full extra-arg set the translation sidecar launches with for one device posture (composed
 * from the named constants above so the runtime AND the manual smoke stay byte-identical — no
 * drift). NO `--jinja`, NOT the chat `CHAT_SERVER_ARGS`. 'auto' composes NO device args — the
 * chat-rung-1 posture (the pin's defaults `-ngl auto` + `--fit on`); 'cpu' forces `--device none`.
 */
export function translationServerArgs(device: TranslationDevice): string[] {
  return [
    ...TRANSLATION_SLOT_ARGS,
    ...TRANSLATION_BATCH_ARGS,
    ...(device === 'cpu' ? TRANSLATION_CPU_DEVICE_ARGS : []),
    ...TRANSLATION_TEMPLATE_ARGS,
    ...TRANSLATION_LOG_ARGS
  ]
}

/** Launch context window (plan §2 D4). Overridden by the manifest's `recommendedContextTokens`
 *  (4096: the model card's 2K input budget + output headroom). Read back via `contextWindow()`. */
const DEFAULT_TRANSLATION_CONTEXT_TOKENS = 4096

/**
 * Per-window bound so a WEDGED sidecar fails the window instead of hanging the job — sized
 * for the real CPU decode. TG-6 re-measured the Gemma tokenizer: a near-budget window at the
 * launched 4096 ctx carries a ~2,000-token output cap (`windowMaxTokens`; 1,998 since #512),
 * and CPU decode ran 1.1–4.4 tok/s across the TG-6 run (the low end under memory pressure) — so a full window can
 * be ~30 min at ~1.1 tok/s before prefill. 45 min never kills such a live slow decode (the old
 * 300 s did — every full window timed out twice into a failed-window notice; the interim TG-3
 * 30 min would clip a ~1.1 tok/s full window) while still bounding a true hang; user cancel stays
 * instant via the task's own abort signal.
 *
 * #605: a HUNG sidecar now ends much sooner — at the header wait below or at `readCompletionSSE`'s
 * liveness clocks — so this cap only bounds a decode that is alive but slower than ~0.74 tok/s on
 * average (the #160 "timed out mid-decode" class, which is not retried).
 */
const DEFAULT_REQUEST_TIMEOUT_MS = 2_700_000

/**
 * #605: the wait for the `/completion` response headers, 180 s — the same value as the chat
 * request's (#594, #598), calibrated for this sidecar. Both pins send the headers when the slot
 * starts, before prefill. Requests take the one slot in turn (`takeSlot`), so the server's slot is
 * busy only behind a cancelled request, which it stops after its current 512-token batch
 * (`TRANSLATION_BATCH_ARGS`), or behind a hung one. A batch slower than this restarts a healthy
 * sidecar (accepted). It must stay under Electron's own 300 s header limit, which would end the
 * request as a plain "fetch failed" and restart nothing. Before #605 the headers had only the
 * 45-min cap.
 */
const HEADER_WAIT_MS = 180_000

/**
 * #473 ruling 2: how long a chat start waits for a GPU-posture translation cold start already in
 * flight before taking it off the card (`yieldGpu`). A 12B loads in ~5 s from an SSD; a slow
 * drive can take longer, and past this bound the chat start goes ahead and the translation start
 * keeps its place until its idle teardown. The race needs both starts within the same seconds.
 */
const YIELD_START_WAIT_MS = 30_000

/** Settle when `p` does or after `ms`, whichever comes first; the timer never holds the process. */
function waitAtMost(p: Promise<unknown>, ms: number): Promise<void> {
  return new Promise((resolve) => {
    const timer = setTimeout(resolve, ms)
    timer.unref?.()
    const done = (): void => {
      clearTimeout(timer)
      resolve()
    }
    p.then(done, done)
  })
}

/**
 * Idle-teardown timeout default (plan §2 D1, the vision §19.13 precedent). The window the 12B
 * sidecar may sit idle — co-resident with the chat + embedder sidecars — before it is torn down to
 * give the RAM back. 120 000 ms (2 min) mirrors vision's tuned value: it spans a burst of windows
 * for one document, then frees ~10 GB once the user moves on; the next translate cold-restarts
 * cleanly (a SOFT teardown). Env-overridable (`HILBERTRAUM_TRANSLATION_IDLE_MS`) for tuning/tests.
 */
const DEFAULT_TRANSLATION_IDLE_MS = 120_000

function readIdleTimeoutMs(): number {
  const raw = process.env.HILBERTRAUM_TRANSLATION_IDLE_MS?.trim()
  const n = raw ? Number(raw) : NaN
  return Number.isFinite(n) && n > 0 ? Math.floor(n) : DEFAULT_TRANSLATION_IDLE_MS
}

/** A scheduled idle-teardown timer handle (the global `setTimeout`'s, or a test's fake clock). */
export interface IdleTimerHandle {
  clear(): void
  /** Detach from the event loop so it can never block a clean quit (the real timer's `unref`). */
  unref?(): void
}

/**
 * The idle-teardown clock. Production uses the global timer; tests inject a controllable clock so
 * the teardown interleavings are DETERMINISTIC (fire on demand) rather than `sleep`-ordered (the
 * vision RUNTIME-4 / TEST-2 pattern).
 */
export interface IdleClock {
  set(cb: () => void, ms: number): IdleTimerHandle
}

/** The default clock — a real `setTimeout`, unref'd so it never keeps the process alive. */
const REAL_IDLE_CLOCK: IdleClock = {
  set(cb, ms) {
    const t = setTimeout(cb, ms)
    return { clear: () => clearTimeout(t), unref: () => void t.unref?.() }
  }
}

export type TranslationRuntimeDeps = Pick<LlamaServerOptions, 'spawn' | 'fetchImpl' | 'findPort' | 'healthIntervalMs'>

export interface TranslationRuntimeOptions extends TranslationRuntimeDeps {
  /** The translation model id (the manifest id). */
  modelId: string
  binPath: string
  /** Absolute path to the GGUF weight. */
  modelPath: string
  contextTokens?: number
  /** Idle-teardown clock (default: the global `setTimeout`). Tests inject a controllable clock. */
  idleClock?: IdleClock
  /**
   * GPU signals (issue #42). Read PER COLD START (the idle teardown means cold starts are routine),
   * so a Settings flip takes effect on the next launch without an app restart. Omitted → chat-ladder
   * defaults (gpuMode 'auto', not auto-disabled) — i.e. GPU auto-offload where chat also uses it.
   */
  gpu?: TranslationGpuDeps
  /**
   * Fired when the runtime abandons the GPU posture for the rest of the session (a failed GPU-attempt
   * start, or a mid-session crash of a GPU-composed sidecar). Observability only; must never throw.
   */
  onDeviceFallback?: (reason: string) => void
  /**
   * Fired once per SUCCESSFUL cold start with the observed device outcome (issue #42 reopen) —
   * the caller logs it symmetrically with the chat ladder's "started via rung …" line, so a
   * silent `--fit` partial offload is at least visible in the log. Observability only; must
   * never throw.
   */
  onStarted?: (info: TranslationStartInfo) => void
  /**
   * Awaited before a cold start that will try the graphics card ('auto'), never before a forced-CPU
   * one (#473). The composition passes a hook that takes a GPU-resident reranker off the card, so
   * `--fit` sizes translation against memory the reranker no longer holds — the chat model switch
   * already does the same. A teardown that begins meanwhile aborts the start as usual. Must never
   * throw.
   */
  beforeGpuStart?: () => Promise<void>
  /**
   * #913: checks the translation model's file before each cold start, at the head of the start ladder (before the
   * reranker yields the card and before any rung spawns). The composition passes the cache-only check: a file a check
   * found damaged latches a `TranslationStartError` with `modelDamaged`, which the consumers show as their own copy;
   * the translator-slot refresh replaces the latched instance after a re-download or a clean check
   * (`rearmStartRefusals`). Absent ⇒ no check.
   */
  checkModel?: BoundModelStartCheck
}

export interface TranslateOptions {
  sourceLang: TranslationLangCode
  targetLang: TranslationLangCode
  /** The source text for ONE window. Translated as data, never obeyed (plan §2 D2). */
  text: string
  /** A user "Stop" — combined with the per-request timeout (M-C5 pattern); it also ends the wait
   *  for a cold start, without cancelling the start (#637). */
  signal?: AbortSignal
  /** Streamed translation-token sink. */
  onToken?: (delta: string) => void
  /** Optional `n_predict` cap. Omitted ⇒ generate until `<end_of_turn>` or the context fills. */
  maxTokens?: number
  /** Final-frame timings sink — the smoke's tokens/sec artifact (plan §7 → D10). */
  onFinal?: (info: CompletionFinal) => void
}

/**
 * The distinct code the latched start failure carries (F-7 / FA-4, option c). The UI turns it into
 * the actionable "restart the app / free memory" copy instead of a bare "runtime failed".
 *
 * WHY a code and not a smarter latch: for a ~10 GB model the likeliest start failure is transient
 * memory pressure from the co-resident chat model — which currently latches translation off for the
 * whole session. Option (a) "classify OOM-shaped failures as non-latching like bind races" was
 * REJECTED: no reliable transient/OOM signature exists across OSes. Verified against `LlamaServer`'s
 * real start surface — a start fault throws `llama-server exited before becoming healthy (code N)` /
 * `… failed to launch` / `… did not become healthy within Nms`, and the *exit code* is the only
 * machine-readable signal. On Windows the OOM / `std::bad_alloc` exit `0xC0000409` COLLIDES with the
 * PERMANENT #20305 minja template crash (see `TRANSLATION_TEMPLATE_ARGS`), and on Linux an OOM-kill
 * is `SIGKILL` — indistinguishable from our own `stop()`; `bad_alloc` is `SIGABRT`, not
 * memory-specific. Un-latching on that signature would therefore ALSO un-latch a genuinely permanent
 * fault sharing it → every subsequent window re-spawns and re-awaits the full health timeout, the
 * exact cost the latch exists to prevent (the reranker precedent). Option (b) time-bounding the
 * latch has the same reliance on the fault being transient and re-pays that cost on a timer. So the
 * latch STAYS (correct for the permanent case) and only its *presentation* improves: a distinct,
 * content-free code (never the underlying cause message — the security-model logging invariants are
 * untouched).
 */
export const TRANSLATION_START_FAILED_CODE = 'translationStartFailed'

/**
 * The latched translation start failure (F-7 option c). Its `code` lets the view job and the
 * document doc-task each surface the distinct "restart / free memory" copy instead of the generic
 * runtime-failure copy. The underlying cause message rides `message` for the LOCAL log only — it is
 * never forwarded to the renderer (both consumers map by `code`/predicate, never by message).
 */
export class TranslationStartError extends Error {
  readonly code = TRANSLATION_START_FAILED_CODE
  /**
   * #530: the cause was the OS refusing to start the engine program — the consumers show the
   * engine copy instead of the "free memory / restart" one, which would send the user the wrong way.
   */
  readonly engineCannotRun: boolean
  /**
   * #913: the start check found the model's file damaged, so nothing was started — the consumers show the
   * "download it again" copy, not the memory one.
   */
  readonly modelDamaged: boolean
  constructor(cause: Error, opts: { modelDamaged?: boolean } = {}) {
    super(cause.message)
    this.name = 'TranslationStartError'
    this.engineCannotRun = isEngineCannotRunError(cause)
    this.modelDamaged = opts.modelDamaged === true
  }
}

/** True for the latched start failure — the two consumers map it to distinct friendly copy (F-7). */
export function isTranslationStartError(err: unknown): err is TranslationStartError {
  return err instanceof TranslationStartError
}

/**
 * #160 (BE-2): the per-request timeout `combineSignals` aborts with (`TimeoutError`
 * DOMException — the fetch/SSE read rejects with the abort reason). Both retry loops use it,
 * together with a tokens-flowed flag, to tell "decode too slow" (tokens flowed steadily until
 * the bound — deterministic at temperature 0, retrying reproduces it and burns another full
 * timeout) from "server wedged" (no tokens flowed — a fresh request is a reasonable transient
 * bet, the class the retry exists for).
 */
export function isRequestTimeoutError(err: unknown): boolean {
  return err instanceof DOMException && err.name === 'TimeoutError'
}

/** Owns one lazily-started TranslateGemma `llama-server` and translates one window over loopback. */
export class TranslationRuntime {
  readonly modelId: string
  private readonly ctxTokens: number
  private server: LlamaServer | null = null
  private starting: Promise<void> | null = null
  /** Set by `stop()` (permanent, quit); a racing lazy start must not resurrect the sidecar. */
  private stopped = false
  /**
   * Set WHILE `suspend()`/`stop()` tear the child down (the lock/quit kill path), cleared in the
   * teardown's `finally` — the reranker's `tearingDown` analogue. `suspend()` (workspace lock) does
   * NOT arm the permanent `stopped` latch, so without this a racing `ensureStarted` could spawn a
   * fresh ~10 GB sidecar that outlives the lock, co-resident with the vault re-encrypt. A
   * translate() arriving after a suspend still lazily restarts (the flag is cleared).
   */
  private tearingDown = false
  /**
   * Failed-start latch (the reranker/embedder pattern): a permanent load fault (e.g. an
   * incompatible GGUF) must not re-spawn + re-await the full health timeout on every window. A
   * TRANSIENT port-bind race does NOT arm it (see `ensureStarted`'s `.catch`) — the latch SURVIVES
   * `suspend()`, so latching a race would silently disable translation for the whole session. When
   * it IS armed it holds a `TranslationStartError` (carrying `TRANSLATION_START_FAILED_CODE`) so the
   * consumers can surface the distinct "restart / free memory" copy (F-7 / FA-4 option c).
   */
  private startFailed: Error | null = null
  /**
   * Session-scoped GPU fallback latch (issue #42 — the chat §5.3 analogue, sized for a sidecar).
   * Armed when a GPU-attempt start fails (non-bind-race) or a GPU-composed sidecar dies mid-session;
   * every later cold start then pins CPU (`--device none`) — no repeated GPU health timeouts, no
   * crash loop across a doc-task's windows (each window retry would otherwise re-pay a ~10 GB GPU
   * load). Deliberately NOT persisted and NEVER writes the global `gpuAutoDisabled`: a 12B
   * translation model can fail on a GPU where the (smaller) chat model runs fine, so a
   * translation-only fault must not force chat into compatibility mode. Chat's own ladder owns the
   * persisted flag; this runtime only READS it (via `TranslationGpuDeps`). Survives `suspend()`
   * (same GPU after unlock), resets on app restart.
   */
  private gpuFellBack = false
  /**
   * The observed outcome of the LAST successful cold start (issue #42 reopen) — device posture +
   * the offload split parsed from the server's load log, and whether that log put a buffer on a
   * graphics device (#671). Kept across the idle teardown (the
   * Translate screen's hint must stay explainable after a run finishes); null until the first
   * successful start of this instance.
   */
  private lastStart: TranslationStartInfo | null = null
  /** Number of translate() calls currently using the sidecar. Guards the idle teardown. */
  private inFlight = 0
  /**
   * #605: the tail of the one-slot queue. The sidecar serves one request at a time (`--parallel 1`),
   * and two callers can overlap: a document translation can start while a Translate job runs
   * (jobs.ts D9). At the server the second request waited for its headers behind the first one's
   * whole window, which `HEADER_WAIT_MS` cannot tell from a hang. The requests queue here instead
   * (`takeSlot`), so the header wait and the liveness clocks only ever time the sidecar's own work.
   */
  private slotTail: Promise<void> = Promise.resolve()
  /** The pending idle-teardown timer handle (armed only when `inFlight === 0`), or null. */
  private idleHandle: IdleTimerHandle | null = null
  /**
   * An in-flight SOFT teardown — the idle timer's, or the stop of a hung sidecar (#605) — tracked so
   * `stop()` can await it (no orphan on quit) and a cold start waits for it (no double-load).
   */
  private idleTeardownPromise: Promise<void> | null = null
  /**
   * The in-flight HARD teardown (`suspend()`/`stop()`), held so overlapping calls SHARE one pass
   * (M5). Without it a second, overlapping teardown sees `this.server` already nulled by the first,
   * runs a no-op body, and its `finally` clears `tearingDown` while the first is STILL inside
   * `server.stop()`'s SIGTERM→2 s→SIGKILL window — a racing `translate()` then cold-starts during the
   * vault re-encrypt, and a quit can exit with the escalation pending (orphan on POSIX). `tearingDown`
   * clears — together with this promise — only when the shared pass has fully settled.
   */
  private teardownPromise: Promise<void> | null = null
  /**
   * Aborts the IN-FLIGHT start ladder (#159 / BE-1). Armed per `startLadder()` run; fired by
   * `doTeardown()` so a lock/quit no longer awaits the whole ~10 GB spawn + health window
   * (up to the 180 s default health timeout) while the plaintext DB stays open — the child
   * is killed inside the health wait and the start rejects with an AbortError instead.
   */
  private startAbort: AbortController | null = null
  /**
   * The posture of the cold start in flight, null when none is. Recorded once per attempt because
   * the headroom gate is not stable over a start (a chat start can begin meanwhile), so
   * `gpuOccupied()` must report what this start chose, not what a fresh resolve would say now.
   */
  private startingDevice: TranslationDevice | null = null
  private readonly idleTimeoutMs: number
  private readonly idleClock: IdleClock
  /** Residency listeners (`onResidencyChange`): fired after `deviceStatus().live` flips. */
  private readonly residencyListeners = new Set<() => void>()

  constructor(private readonly opts: TranslationRuntimeOptions) {
    this.modelId = opts.modelId
    this.ctxTokens = opts.contextTokens ?? DEFAULT_TRANSLATION_CONTEXT_TOKENS
    this.idleTimeoutMs = readIdleTimeoutMs()
    this.idleClock = opts.idleClock ?? REAL_IDLE_CLOCK
  }

  /** The launched context window (`--ctx-size`) — the budget TG-3's window planner clamps against. */
  contextWindow(): number {
    return this.ctxTokens
  }

  /**
   * Is the permanent failed-start latch armed? (BE-7, full-audit 2026-07-10.) A latched
   * instance is lazy/dead — no live child, every translate() fails fast — so the issue-#40
   * `onModelInstalled` refresh may safely REPLACE it after a delete-and-re-download repair;
   * a live sidecar is still never replaced.
   */
  isStartFailed(): boolean {
    return this.startFailed !== null
  }

  /** Lazily spawn the translation sidecar (once). Concurrent callers share one start (single-flight).
   *  `callerSignal` ends only this caller's waits — for a soft idle teardown and for the start
   *  (#637: before, a cancel during a start that hung waited out the 180 s health budget, two of
   *  them on the GPU→CPU ladder) — never the start: the next window or job may share it. */
  private async ensureStarted(callerSignal?: AbortSignal): Promise<LlamaServer> {
    // Any use of the sidecar resets the idle clock: a teardown must never fire out from under an
    // imminent request.
    this.cancelIdleTimer()
    if (this.stopped) throw new Error('Translation runtime is stopped (app is shutting down)')
    if (this.tearingDown) throw new Error('Translation runtime is suspending (workspace is locking)')
    if (this.startFailed) throw this.startFailed
    if (this.server) return this.server
    // A SOFT idle teardown may be mid-kill: `idleTeardown` nulled `this.server` SYNCHRONOUSLY and is
    // now awaiting the child's exit. Wait it out before cold-starting so a translate racing the soft
    // teardown never briefly holds TWO ~10 GB sidecars co-resident (the double-load — M5 improvement).
    // Re-check the latches after the await: a lock/quit may have begun, or another caller may have
    // already restarted the sidecar, while we waited.
    if (this.idleTeardownPromise) {
      await waitUnlessAborted(
        this.idleTeardownPromise.catch(() => undefined),
        callerSignal
      )
      if (this.stopped) throw new Error('Translation runtime is stopped (app is shutting down)')
      if (this.tearingDown) throw new Error('Translation runtime is suspending (workspace is locking)')
      if (this.server) return this.server
    }
    if (!this.starting) {
      this.starting = this.startLadder().finally(() => {
        this.starting = null
        // #637: when every translate that waited for this start was cancelled, each one's
        // `finally` found `starting` set and armed nothing. Arm the idle clock here, or a start
        // that lands keeps ~10 GB resident until lock or quit. A no-op while a translate waits.
        this.armIdleTimer()
      })
    }
    await waitUnlessAborted(this.starting, callerSignal)
    // A teardown (lock/quit) may have begun during the await above and nulled the server we'd
    // return — re-check rather than hand back a sidecar that's being / about to be stopped.
    if (this.stopped) throw new Error('Translation runtime is stopped (app is shutting down)')
    if (this.tearingDown) throw new Error('Translation runtime is suspending (workspace is locking)')
    if (!this.server) throw new Error('Translation server failed to start')
    return this.server
  }

  /**
   * The device posture for the NEXT launch — re-read per cold start so a Settings flip (or a
   * mid-session `gpuAutoDisabled` persisted by the chat ladder) takes effect on the next lazy
   * start without an app restart. `gpuMode: 'off'`, the persisted auto-disable flag, and this
   * runtime's own session fallback latch each force CPU (issue #42).
   */
  private resolveDevice(): TranslationDevice {
    return this.resolvePosture().device
  }

  /** The posture of a cold start and, when the headroom gate chose the processor, why (#473). */
  private resolvePosture(): { device: TranslationDevice; cause: TranslationCpuCause | null } {
    const gpuAllowed =
      (this.opts.gpu?.getGpuMode?.() ?? 'auto') === 'auto' &&
      !(this.opts.gpu?.getGpuAutoDisabled?.() ?? false)
    if (!gpuAllowed || this.gpuFellBack) return { device: 'cpu', cause: null }
    const verdict = this.opts.gpu?.gpuHeadroom?.(this.modelId) ?? 'auto'
    return verdict === 'auto' ? { device: 'auto', cause: null } : { device: 'cpu', cause: verdict }
  }

  /** Arm the session CPU-fallback latch once and report it (observability hook must never throw). */
  private noteDeviceFallback(reason: string): void {
    if (this.gpuFellBack) return
    this.gpuFellBack = true
    try {
      this.opts.onDeviceFallback?.(reason)
    } catch {
      /* observability only — a throwing hook must not break the start path */
    }
  }

  /**
   * The device outcome of the last successful cold start, with liveness — the Translate screen's
   * device hint (issue #42 reopen). Null until the first successful start; last-known values are
   * kept after the idle teardown / suspend (`live: false`) so a finished run stays explainable.
   */
  deviceStatus(): TranslationDeviceStatus | null {
    return this.lastStart ? { ...this.lastStart, live: this.server !== null } : null
  }

  /**
   * Subscribe to residency transitions (PR #303 P3): a successful cold start, the idle
   * teardown, a suspend/stop, and an unexpected exit — everything that flips
   * `deviceStatus().live`. Fired synchronously after the flip, before any kill is awaited,
   * so a reader in the callback sees the new state. Observability only; a throwing listener
   * never breaks the sidecar's lifecycle. Returns the unsubscribe.
   */
  onResidencyChange(cb: () => void): () => void {
    this.residencyListeners.add(cb)
    return () => {
      this.residencyListeners.delete(cb)
    }
  }

  private emitResidencyChange(): void {
    for (const cb of this.residencyListeners) {
      try {
        cb()
      } catch {
        /* observability only */
      }
    }
  }

  /**
   * Wave 8 ruling (b)(T): true while a GPU-posture ('auto') sidecar is loading, resident, or
   * still being torn down — hard (`teardownPromise` pending) or idle (`idleTeardownPromise`
   * pending). `deviceStatus().live` alone misses all three (F5 / B-5, the Wave 8 analysis):
   * `server` is set only after `start()` resolves healthy, and the idle teardown nulls `server`
   * before the kill settles. `resolveDevice()` is re-read live rather than cached per attempt:
   * it is pure over the current settings/latch state, so a start that already fell back from
   * 'auto' to 'cpu' (`gpuFellBack` latched first) is correctly read as no longer occupying the
   * card for the remainder of that same load. A forced-CPU sidecar never occupies the card, nor
   * (#671) a started one whose load log put no buffer on a graphics device.
   */
  gpuOccupied(): boolean {
    if (this.starting) return (this.startingDevice ?? this.resolveDevice()) === 'auto'
    if (this.server || this.teardownPromise || this.idleTeardownPromise) return this.lastStartOnCard()
    return false
  }

  /**
   * Did the last successful start load onto a graphics device? Its posture, unless its own load log
   * printed buffers and none on a graphics device (#671: a PC with no usable card under 'auto').
   */
  private lastStartOnCard(): boolean {
    return this.lastStart != null && !translationRanOnProcessor(this.lastStart)
  }

  /** One launch attempt at one device posture; installs `this.server` on success. */
  private async startAttempt(
    device: TranslationDevice,
    startSignal?: AbortSignal,
    cpuCause: TranslationCpuCause | null = null
  ): Promise<void> {
    // Read the server's own load log for where the start landed (issue #42 reopen): under the
    // 'auto' posture llama.cpp `--fit` can silently land a PARTIAL offload (a resident chat
    // model took the VRAM) that decodes at ~CPU speed, and the offload line is the only place
    // the real split is reported. #671: the chat runtime's parser, so the split comes with the
    // evidence the chat label uses since #653 — GPU buffers, never the line, which a start with
    // no usable graphics device prints as `N/N layers` too. It reassembles lines across chunks,
    // so a line split by a chunk boundary or buried in one large chunk is read (CODE-22). Fed until
    // the start lands: the reading is taken once, and the per-request lines after it need no parse.
    const placement = createPlacementParser()
    let loaded = false
    /** Set once the start lands: whether a crash of this child takes the GPU fallback (#671). */
    let ranOnProcessor = device === 'cpu'
    const server = new LlamaServer({
      binPath: this.opts.binPath,
      modelPath: this.opts.modelPath,
      contextTokens: this.ctxTokens,
      // NO `--jinja` (the #20305 regression, plan §2 D2) and NOT CHAT_SERVER_ARGS. `--parallel 1`
      // (sequential windows; #25142) + the device posture (issue #42: 'auto' = NO device args →
      // the pin's `-ngl auto` + `--fit on` VRAM-aware offload; 'cpu' = `--device none`) +
      // `--chat-template gemma` (avoids the #20305 STARTUP crash — see TRANSLATION_TEMPLATE_ARGS).
      extraArgs: translationServerArgs(device),
      spawn: this.opts.spawn,
      fetchImpl: this.opts.fetchImpl,
      findPort: this.opts.findPort,
      healthIntervalMs: this.opts.healthIntervalMs,
      // #159 (BE-1): let a lock/quit teardown abort this start mid-health-wait (the child is
      // killed via the normal stop path; start() rejects AbortError — never latched below).
      startAbortSignal: startSignal,
      // M1: a mid-session sidecar crash (the child dies on its own AFTER becoming healthy — driver
      // crash, VRAM/RAM exhaustion) otherwise leaves `this.server` pointing at a dead handle: every
      // subsequent `translate()` fails with a connection error, and each failed attempt re-arms the
      // idle clock, so the outage persists as long as attempts arrive < the idle window apart. Drop
      // the dead handle here so the NEXT `translate()` cold-starts (the doc-task's one retry then
      // gets a fresh spawn). Identity-compared so a late crash notification can never clobber a
      // NEWER instance that a soft teardown + restart already installed. `LlamaServer` fires this
      // only for a healthy child dying outside `stop()`, so a lock/quit kill never trips it.
      // Issue #42: a GPU-composed sidecar dying on its own additionally arms the session CPU
      // latch — the next cold start pins `--device none` instead of crash-looping the GPU across
      // a doc-task's per-window retries (the chat §5.3 auto-fallback, session-scoped). #671: not
      // when this start's own log put nothing on a graphics device — it ran on the processor, and
      // its crash is no GPU fault (chat's #599 rule for a CPU-mode crash).
      onUnexpectedExit: () => {
        if (this.server === server) {
          this.server = null
          this.emitResidencyChange()
        }
        if (!ranOnProcessor) {
          this.noteDeviceFallback('GPU-composed translation sidecar exited unexpectedly mid-session')
        }
      },
      onStderrData: (text) => {
        if (!loaded) placement.onStderrData(text)
      }
    })
    await server.start()
    loaded = true
    this.server = server
    // Record + report the observed outcome ONCE per successful cold start (issue #42 reopen).
    // A parse miss stays honest as null; the hook is observability-only and must never break the
    // start path. #671: `gpuBuffers` is the parser's `gpuBufferEvidence` — absent when the log gives
    // nothing to judge by.
    const { gpuLayers, totalLayers } = placement.reading()
    const gpuBuffers = placement.gpuBufferEvidence()
    this.lastStart = {
      device,
      gpuLayers,
      totalLayers,
      ...(gpuBuffers != null ? { gpuBuffers } : {}),
      ...(device === 'cpu' && cpuCause ? { cpuCause } : {})
    }
    ranOnProcessor = translationRanOnProcessor(this.lastStart)
    this.emitResidencyChange()
    try {
      this.opts.onStarted?.(this.lastStart)
    } catch {
      /* observability only */
    }
  }

  /**
   * The translation start LADDER (issue #42 — the chat rung-1/rung-2 pair, sized for a lazy
   * sidecar): try the resolved device posture; when a GPU attempt fails for a non-transient
   * reason, fall back to forced CPU ONCE within the same start, then latch the session to CPU.
   * The CPU rung runs only while a translate still waits for the start (#637). Only a failure of
   * the FINAL (CPU) attempt arms the permanent `startFailed` latch.
   */
  private async startLadder(): Promise<void> {
    const { device, cause } = this.resolvePosture()
    this.startingDevice = device
    // #159 (BE-1): arm the per-ladder abort so `doTeardown()` can cut a cold start short.
    const abort = new AbortController()
    this.startAbort = abort
    try {
      // #913: a file a check found damaged never starts, on either rung. Before the device ladder
      // (the reranker's order, #913 code review), so nothing the check does is read as a device
      // fault: the reranker keeps the card, and a check that throws arms no GPU fallback and walks
      // no CPU rung (its error goes to the caller as it is, unlatched). A teardown that begins
      // during the check aborts `abort`: the start ends as the abort it is.
      if (this.opts.checkModel) {
        const verdict = await this.opts.checkModel(abort.signal)
        if (abort.signal.aborted) throw new DOMException('The translation start was aborted', 'AbortError')
        if (verdict === 'damaged') {
          const startError = new TranslationStartError(new Error('The translation model file failed its check'), {
            modelDamaged: true
          })
          this.startFailed = startError
          throw startError
        }
      }
      await this.deviceLadder(device, cause, abort)
    } finally {
      if (this.startAbort === abort) this.startAbort = null
      this.startingDevice = null
    }
  }

  /** The device ladder proper (`startLadder`): the resolved posture, then the CPU rung on a GPU fault. */
  private async deviceLadder(
    device: TranslationDevice,
    cause: TranslationCpuCause | null,
    abort: AbortController
  ): Promise<void> {
    try {
      // #473: let the reranker leave the card first. Inside the try so a lock that begins while
      // this waits has aborted `abort` by the time `startAttempt` runs, which then never spawns.
      if (device === 'auto') await this.opts.beforeGpuStart?.().catch(() => undefined)
      await this.startAttempt(device, abort.signal, cause)
      return
    } catch (err) {
      const error = err instanceof Error ? err : new Error(String(err))
      // #159 (BE-1): a teardown-ABORTED start is not a device or model fault — never latch
      // `startFailed` (translation must lazily restart after the next unlock) and never fall
      // to the CPU rung (the lock/quit is tearing the child down right now). It propagates
      // raw; the in-flight job was already aborted by the teardown's own cancel pass.
      if (isStartAbortError(err) || abort.signal.aborted) throw error
      // A TRANSIENT port-bind race must NOT arm either latch (the reranker F7 fix / chat REL-1):
      // it is not a device fault — LlamaServer already retried once on a fresh port. It propagates
      // RAW (not a TranslationStartError), so the consumers' transient-retry paths still treat it
      // as the retryable class it is (and the retry re-attempts the SAME device posture).
      if (isBindRaceError(error.message)) throw error
      // #1012 code review: an engine file the pre-spawn check could not read just now is as transient
      // as a bind race — rethrown raw, no CPU fallback, no latch; the next translate reads the files again.
      if (isEngineFilesUnreadableError(error)) throw error
      // #530: the OS refused to start the program — not a device fault (no GPU-fallback latch,
      // no CPU retry: the same program is refused again). Latched like any load fault; the
      // consumers read `engineCannotRun` for the copy, and "Check again" re-arms the slot.
      if (isEngineCannotRunError(error)) {
        const startError = new TranslationStartError(error)
        this.startFailed = startError
        throw startError
      }
      if (device === 'auto') {
        this.noteDeviceFallback(`translation sidecar GPU-attempt start failed: ${error.message}`)
        // A lock/quit that began while the GPU attempt was failing must not cold-load ~10 GB on
        // the CPU rung just to tear it straight down. Nor for nobody (#637): when every translate
        // waiting for this start was cancelled, the next one starts on the CPU directly (the latch
        // just armed), and the GPU failure stays unlatched.
        if (!this.stopped && !this.tearingDown && this.inFlight > 0) {
          try {
            this.startingDevice = 'cpu'
            await this.startAttempt('cpu', abort.signal)
            return
          } catch (cpuErr) {
            const cpuError = cpuErr instanceof Error ? cpuErr : new Error(String(cpuErr))
            // #159 (BE-1): same rule on the CPU rung — an aborted start must not latch.
            if (isStartAbortError(cpuErr) || abort.signal.aborted) throw cpuError
            if (isBindRaceError(cpuError.message) || isEngineFilesUnreadableError(cpuError)) throw cpuError
            const startError = new TranslationStartError(cpuError)
            this.startFailed = startError
            throw startError
          }
        }
        throw error
      }
      // Every other start failure DOES latch (the reranker precedent — a permanent load fault
      // must not re-spawn + re-await the full health timeout per window). No reliable
      // transient/OOM signature exists to safely un-latch memory pressure (see
      // TRANSLATION_START_FAILED_CODE), so we keep the latch and tag it with the distinct code
      // that lets the UI say "restart the app / free memory" (F-7 / FA-4 option c).
      const startError = new TranslationStartError(error)
      this.startFailed = startError
      throw startError
    }
  }

  /**
   * Translate ONE window: format the trained prompt (`buildTranslationPrompt`), POST it to the raw
   * `/completion` endpoint with `temperature 0` (greedy — deterministic MT) + `stop:
   * ["<end_of_turn>"]`, stream the translation through `onToken`, and return the full text. Honours
   * `signal` (a user "Stop") combined with the per-request timeout. The signal also ends this
   * window's wait for a cold start, which keeps running for the next window or job (#637); a
   * translate already stopped starts nothing and rejects with the signal's reason. Windows from
   * overlapping callers take the one slot in turn (#605, `takeSlot`).
   */
  async translate(opts: TranslateOptions): Promise<string> {
    // #637: a caller already stopped starts nothing and leaves the idle clock alone.
    opts.signal?.throwIfAborted()
    // Cancel the idle timer and mark a job in flight BEFORE the (possibly slow, cold-start)
    // ensureStarted await, so a teardown can't fire during the start either.
    this.cancelIdleTimer()
    this.inFlight++
    try {
      const release = await this.takeSlot(opts.signal)
      try {
        return await this.runTranslate(opts)
      } finally {
        release()
      }
    } finally {
      this.inFlight--
      // The last job to settle re-arms the idle clock; a still-running job leaves it disarmed.
      if (this.inFlight === 0) this.armIdleTimer()
    }
  }

  /** #605: wait for the one slot, first come first served. A cancel ends only this caller's wait,
   *  and the slot passes on once the request ahead settles. Resolves with the release. */
  private async takeSlot(signal?: AbortSignal): Promise<() => void> {
    const ahead = this.slotTail
    let release!: () => void
    const mine = new Promise<void>((resolve) => (release = resolve))
    this.slotTail = ahead.then(() => mine)
    try {
      await waitUnlessAborted(ahead, signal)
    } catch (err) {
      release()
      throw err
    }
    return release
  }

  private async runTranslate(opts: TranslateOptions): Promise<string> {
    const server = await this.ensureStarted(opts.signal)
    const prompt = buildTranslationPrompt({
      sourceLang: opts.sourceLang,
      targetLang: opts.targetLang,
      text: opts.text
    })
    const body = JSON.stringify({
      prompt,
      stream: true,
      // Greedy decode — MT wants deterministic output (plan §2 D2). Stop at the turn boundary so
      // `<end_of_turn>` never leaks into the translation (a smoke assertion).
      temperature: 0,
      stop: [TRANSLATION_STOP_TOKEN],
      // Loopback compute hint: reuse the KV prefix across windows that share the instruction
      // prefix. Purely local, no telemetry (the chat-stream precedent).
      cache_prompt: true,
      // #605: a text-less `prompt_progress` frame at slot start and after every prompt batch (both
      // pins) — the only sign that prefill is advancing, which `readCompletionSSE`'s compute clock watches.
      return_progress: true,
      ...(opts.maxTokens != null ? { n_predict: opts.maxTokens } : {})
    })
    // Own the (long) timeout so it is cleared the instant the window finishes (REL-4).
    const combined = combineSignals(opts.signal, DEFAULT_REQUEST_TIMEOUT_MS)
    // #605: the headers get their own deadline; after them the request follows the cap and the caller.
    const headers = combineSignals(combined.signal, HEADER_WAIT_MS)
    try {
      let res: Response
      try {
        res = await server.fetch('/completion', {
          method: 'POST',
          headers: { 'content-type': 'application/json' },
          body,
          signal: headers.signal
        })
      } catch (err) {
        // Only the header deadline aborts `headers` while `combined` is clear; a Stop or the cap wins a tie.
        if (headers.signal.aborted && !combined.signal.aborted) {
          throw new RuntimeUnresponsiveError(HEADER_WAIT_MS, 'response headers')
        }
        throw err
      }
      headers.disarmTimeout()
      if (!res.ok) {
        void res.body?.cancel().catch(() => undefined)
        throw new Error(`Translation request failed: HTTP ${res.status}`)
      }
      if (!res.body) throw new Error('Translation request returned an empty response body')
      let out = ''
      for await (const delta of readCompletionSSE(res.body, opts.signal, opts.onFinal)) {
        out += delta
        opts.onToken?.(delta)
      }
      return out
    } catch (err) {
      if (isRuntimeUnresponsiveError(err)) this.restartHung(server, err as Error)
      throw err
    } finally {
      headers.clear()
      combined.clear()
    }
  }

  /**
   * #605: stop a sidecar found hung — no response headers within `HEADER_WAIT_MS`, or a liveness
   * clock in `readCompletionSSE` ran out — so the window's one retry (both consumers retry this error
   * once, tokens or not) cold-starts a fresh one. Before, the retry queued behind the stuck slot,
   * and so did every later window of a document. The kill is a soft teardown
   * (`idleTeardownPromise`): a translate arriving meanwhile waits for it (never two ~10 GB children),
   * and a lock or quit awaits it. The device posture is kept (owner call): unlike a GPU-composed
   * sidecar that crashes, one that hangs does not switch the session to the CPU. Identity-checked,
   * so a sidecar already replaced or torn down is left alone.
   */
  private restartHung(server: LlamaServer, err: Error): void {
    if (this.server !== server) return
    log.warn('Translation sidecar stopped responding; stopping it so the next window starts a fresh one', {
      reason: err.message
    })
    void this.softTeardown(server).catch(() => undefined)
  }

  /**
   * #473 ruling 2 (2026-10-12): a chat model start takes the graphics card first — the chat
   * runtime's `beforeStart` hook calls this. llama.cpp fixes a process's split at load, so a chat
   * model starting beside this sidecar would stay squeezed until restarted, while this sidecar
   * recovers by itself. A sidecar resident ON THE CARD is stopped the way #605 stops a hung one
   * (`softTeardown`): a window in flight fails with an ordinary stream error, both consumers retry
   * it once, and the retry cold-starts after this kill — on the processor while the chat start is
   * still in flight (the headroom gate). A GPU-posture cold start in flight is let finish first, for
   * at most `YIELD_START_WAIT_MS`: aborting it would reach a document task as a cancel. A sidecar on
   * the processor, or none, is left alone — so is a GPU-posture one whose own load log put no buffer
   * on a graphics device (#671).
   */
  async yieldGpu(): Promise<void> {
    if (this.stopped || this.tearingDown) return
    if (this.starting && this.startingDevice === 'auto') {
      await waitAtMost(this.starting.catch(() => undefined), YIELD_START_WAIT_MS)
    }
    // A soft kill already under way (the idle teardown, #605's) still holds the card until the
    // child exits — the chat start must not size itself while it does.
    if (this.idleTeardownPromise && this.lastStartOnCard()) {
      await this.idleTeardownPromise.catch(() => undefined)
    }
    const server = this.server
    if (server == null || !this.lastStartOnCard() || this.stopped || this.tearingDown) return
    // A start that offloaded no layer is left alone too (#473). It still holds its compute buffer
    // on the card (91 MiB for the 4B at `-ngl 0`, measured in #653), which the chat start then
    // sizes itself beside; #671 leaves that as it was.
    if (this.lastStart?.gpuLayers === 0) return
    log.info('Translation sidecar leaves the graphics card for a chat model start')
    await this.softTeardown(server).catch(() => undefined)
  }

  /**
   * Stop `server` (the live one) as a SOFT teardown: null the handle synchronously, so a translate
   * arriving meanwhile cold-starts a fresh, independent child — after waiting for this kill
   * (`ensureStarted`), never two ~10 GB children at once — and track the kill so a lock or quit
   * awaits it. Used by the idle teardown and by `restartHung` (#605).
   */
  private softTeardown(server: LlamaServer): Promise<void> {
    this.server = null
    this.emitResidencyChange()
    const teardown: Promise<void> = server.stop().finally(() => {
      if (this.idleTeardownPromise === teardown) this.idleTeardownPromise = null
    })
    this.idleTeardownPromise = teardown
    return teardown
  }

  /**
   * Kill the sidecar PERMANENTLY (no-op if never started). Used on `will-quit`, where a racing
   * lazy start must not resurrect the child as an orphan. Awaits an in-flight lazy start AND an
   * in-flight soft idle teardown so neither leaves an orphaned child after the app quits.
   */
  async stop(): Promise<void> {
    this.stopped = true
    await this.teardown()
    // Re-cancel AFTER the awaits so stop()'s postcondition ("no idle timer is live on return")
    // holds locally, independent of armIdleTimer's guards (the vision R7 defense-in-depth backstop).
    this.cancelIdleTimer()
  }

  /**
   * Kill the sidecar but allow a lazy restart on the next `translate()` — used on workspace LOCK,
   * like the reranker/E5 `suspend()`. The 12B keeps recent source/translation text in its KV cache,
   * so it must die before the vault re-encrypts; it comes back lazily after unlock. A PERMANENT
   * `startFailed` latch survives a suspend (a GGUF the server could not load won't load after
   * unlock either); a transient bind race never armed it, so a port race can't wrongly disable
   * translation past a lock/unlock.
   */
  async suspend(): Promise<void> {
    await this.teardown()
  }

  private teardown(): Promise<void> {
    // Single-flight (M5): an overlapping teardown — two suspends racing, or a quit `stop()` arriving
    // while a suspend's kill is still in its SIGTERM→SIGKILL window — SHARES this pass rather than
    // starting a second one. A second pass would see `this.server` already nulled, run a no-op body,
    // and its `finally` would clear `tearingDown` prematurely (see the field comment). `tearingDown`
    // + `teardownPromise` therefore clear together, only when the shared promise settles below.
    if (this.teardownPromise) return this.teardownPromise
    // Bar a racing ensureStarted from spawning a sidecar that would outlive this teardown (and
    // survive a lock). `stop()` also arms the permanent `stopped` latch before calling this.
    this.tearingDown = true
    this.cancelIdleTimer()
    // The `.finally` runs on a microtask, never synchronously — so the `this.teardownPromise = run`
    // assignment below always wins the race even when `doTeardown()` completes without awaiting.
    const run = this.doTeardown().finally(() => {
      // Cleared so a post-suspend translate() can lazily restart (suspend permits a fresh start;
      // only stop()'s separate, permanent `stopped` latch blocks that).
      this.tearingDown = false
      this.teardownPromise = null
    })
    this.teardownPromise = run
    return run
  }

  private async doTeardown(): Promise<void> {
    // A lazy start may be in flight (first translate() racing quit/lock). #159 (BE-1): ABORT it
    // rather than wait it out — awaiting the whole spawn + health wait (up to the 180 s default
    // health timeout for a wedged ~10 GB load) kept lock/quit hung with the plaintext DB open.
    // The abort kills the child inside the health wait (the normal stop path — no orphan), the
    // start rejects AbortError (never latches `startFailed`), and the await below then settles
    // in roughly one health-poll interval instead of the full load.
    this.startAbort?.abort()
    if (this.starting) await this.starting.catch(() => undefined)
    if (this.idleTeardownPromise) await this.idleTeardownPromise.catch(() => undefined)
    const server = this.server
    this.server = null
    if (server) {
      this.emitResidencyChange()
      await server.stop()
    }
  }

  // ---- Idle-teardown interlock (the vision RUNTIME-4 pattern) --------------------------

  private cancelIdleTimer(): void {
    if (this.idleHandle) {
      this.idleHandle.clear()
      this.idleHandle = null
    }
  }

  /** Arm the idle teardown — but only when there is a live, idle sidecar to reclaim. */
  private armIdleTimer(): void {
    this.cancelIdleTimer()
    if (this.stopped || this.tearingDown || this.starting || this.inFlight > 0 || !this.server) return
    this.idleHandle = this.idleClock.set(() => {
      this.idleHandle = null
      void this.idleTeardown()
    }, this.idleTimeoutMs)
    // Never let the idle timer keep the process alive (it would block a clean quit).
    this.idleHandle.unref?.()
  }

  /**
   * SOFT teardown fired by the idle timer: kill the child but do NOT latch `stopped`, so the next
   * `translate()` cold-starts cleanly. Guarded so it can never run under a `starting`/in-flight job
   * — if a job slipped in after the timer fired, we skip and that job's `finally` re-arms the clock.
   */
  private async idleTeardown(): Promise<void> {
    if (this.stopped || this.tearingDown || this.starting || this.inFlight > 0 || !this.server) return
    await this.softTeardown(this.server)
  }
}