Skip to content

AI, fully local on your computer.

64.0 KB
Raw Blame
import { describe, it, expect, vi } from 'vitest'
import { EventEmitter } from 'node:events'
import type { ChildProcessLike, SpawnFn } from '../../src/main/services/runtime/sidecar'
import { RuntimeManager, ExternalGenerationBusyError } from '../../src/main/services/runtime'
import type {
  HealthStatus,
  ModelRuntime,
  RuntimeStartOptions,
  RuntimeChatOptions
} from '../../src/main/services/runtime'
import {
  createSelectingRuntimeFactory,
  createGpuCrashAutoFallback,
  createCpuCrashAutoRestart,
  type LlamaRungOptions
} from '../../src/main/services/runtime/factory'
import {
  createLlamaRuntime,
  RuntimeConnectionLostError,
  RuntimeUnresponsiveError
} from '../../src/main/services/runtime/llama'
import { performShutdown } from '../../src/main/shutdown'
import type { AppContext } from '../../src/main/services/context'
import type { GpuDevice } from '../../src/shared/types'
import { t } from '../../src/shared/i18n'
import { sseBody } from '../helpers/fake-sidecar'
import { manualSource, type ManualSource } from '../helpers/manual-stream'
import { hangBudgetMs, until, within } from '../helpers/hang-budget'
import { workspaceStandIn } from '../helpers/workspace-stand-in'

// Regression tests for the runtime-lifecycle fix:
//  B2 — RuntimeManager.start() must NOT leave a half-started runtime as "active" when
//       start()/health() throws (callers gate chat/RAG on active() != null).

/** A child that records the signals it receives; only exits when told which signal does. */
class RecordingChild extends EventEmitter implements ChildProcessLike {
  pid = 9
  killed = false
  signals: Array<string | undefined> = []
  constructor(private readonly exitOn: 'SIGTERM' | 'SIGKILL') {
    super()
  }
  kill(signal?: NodeJS.Signals | number): boolean {
    this.signals.push(signal === undefined ? undefined : String(signal))
    this.killed = true
    // SIGTERM is delivered as kill() with no signal arg; SIGKILL is explicit.
    const isTerm = signal === undefined || signal === 'SIGTERM'
    if ((this.exitOn === 'SIGTERM' && isTerm) || (this.exitOn === 'SIGKILL' && signal === 'SIGKILL')) {
      queueMicrotask(() => this.emit('exit', 0, signal ?? null))
    }
    return true
  }
}

describe('RuntimeManager.start() — B2 reset on failed start', () => {
  const opts: RuntimeStartOptions = { modelId: 'm', modelPath: '/w.gguf', contextTokens: 2048 }

  function runtime(over: Partial<ModelRuntime> & { onStop?: () => void }): ModelRuntime {
    return {
      modelId: 'm',
      start: async () => {},
      stop: async () => over.onStop?.(),
      health: async () => ({ healthy: true, message: '', port: 1 }),
      chatStream: async function* () {},
      ...over
    }
  }

  it.each<[string, Partial<ModelRuntime>, RegExp]>([
    [
      'start() throws',
      {
        start: async () => {
          throw new Error('llama-server health timeout')
        }
      },
      /health timeout/
    ],
    [
      'health() throws after a successful start',
      {
        health: async () => {
          throw new Error('health probe blew up')
        }
      },
      /health probe/
    ]
  ])('leaves no active runtime when %s, and cleans up the failed runtime', async (_label, failure, message) => {
    let stopped = false
    const failing = runtime({
      ...failure,
      onStop: () => {
        stopped = true
      }
    })
    const mgr = new RuntimeManager(() => failing)
    await expect(mgr.start(opts)).rejects.toThrow(message)
    // No stale "active" runtime — chat/RAG gate on active() != null.
    expect(mgr.active()).toBeNull()
    expect(mgr.activeModelId()).toBeNull()
    expect(mgr.status().running).toBe(false)
    // The half-started runtime was stopped (best-effort cleanup) — on the health-throws path too.
    expect(stopped).toBe(true)
  })

  // H2 (audit round 4): start/stop must be SERIALIZED. A real GGUF start can take up
  // to the health timeout; in that window a second start() used to skip the stop
  // (current was still null) and spawn a second, never-stopped llama-server (orphan),
  // and a stop() used to be a silent no-op the in-flight start then overrode. A model
  // SWITCH (start A, then start B) must stop A before starting B.
  it('serializes a model switch — the first runtime is stopped, never orphaned', async () => {
    const events: string[] = []
    const gate: { release: (() => void) | null } = { release: null }
    const mgr = new RuntimeManager((o) =>
      runtime({
        modelId: o.modelId,
        start: async () => {
          events.push(`start:${o.modelId}`)
          if (o.modelId === 'a') await new Promise<void>((resolve) => (gate.release = resolve))
        },
        onStop: () => events.push(`stop:${o.modelId}`)
      })
    )

    const p1 = mgr.start({ modelId: 'a', modelPath: '/a.gguf', contextTokens: 2048 })
    const p2 = mgr.start({ modelId: 'b', modelPath: '/b.gguf', contextTokens: 2048 })
    // Let A finish loading; B must then stop A before starting B.
    await new Promise((r) => setTimeout(r, 0))
    gate.release?.()
    await Promise.all([p1, p2])

    expect(events).toEqual(['start:a', 'stop:a', 'start:b'])
    expect(mgr.activeModelId()).toBe('b')
  })

  // The reported double-start bug: clicking Start twice for the SAME model (or revisiting
  // the AI Model screen before the GGUF finished loading) used to stop-and-restart the
  // runtime — two "Start runtime" log lines, two backend selections. start() is now
  // idempotent for the in-flight/running model, and exposes `startingModelId` so the UI
  // can disable the button.
  it('is idempotent for the same model — a double-start does not restart it', async () => {
    const events: string[] = []
    const gate: { release: (() => void) | null } = { release: null }
    const mgr = new RuntimeManager((o) =>
      runtime({
        modelId: o.modelId,
        start: async () => {
          events.push(`start:${o.modelId}`)
          await new Promise<void>((resolve) => (gate.release = resolve))
        },
        onStop: () => events.push(`stop:${o.modelId}`)
      })
    )

    const p1 = mgr.start(opts) // opts.modelId === 'm'
    // The in-flight model is visible immediately (server truth for the disabled button).
    expect(mgr.status().startingModelId).toBe('m')
    // #107: the "Starting…" window carries its elapsed time for honest load progress.
    expect(mgr.status().starting?.elapsedMs).toBeGreaterThanOrEqual(0)
    const p2 = mgr.start(opts) // a double-click while m is still loading
    await new Promise((r) => setTimeout(r, 0)) // let m's start() run and arm the gate
    gate.release?.()
    const [s1, s2] = await Promise.all([p1, p2])

    expect(events).toEqual(['start:m']) // ONE start, no stop/restart
    expect(mgr.activeModelId()).toBe('m')
    expect(s1.running).toBe(true)
    expect(s2.running).toBe(true)
    expect(mgr.status().startingModelId).toBeNull() // cleared once settled
    expect(mgr.status().starting).toBeUndefined() // #107: the window closed with it
  })

  // Starting the model that is ALREADY running is a no-op too (the AI Model screen shows
  // Stop, but a stale tab or race could still call start).
  it('is idempotent for the already-running model', async () => {
    const events: string[] = []
    const mgr = new RuntimeManager((o) =>
      runtime({
        modelId: o.modelId,
        start: async () => {
          events.push(`start:${o.modelId}`)
        },
        onStop: () => events.push(`stop:${o.modelId}`)
      })
    )
    await mgr.start(opts)
    await mgr.start(opts) // already running
    expect(events).toEqual(['start:m'])
    expect(mgr.activeModelId()).toBe('m')
  })

  it('stop() during an in-flight start stops the runtime that start committed', async () => {
    const events: string[] = []
    const gate: { release: (() => void) | null } = { release: null }
    const mgr = new RuntimeManager(() =>
      runtime({
        modelId: 'r1',
        start: async () => {
          events.push('start:r1')
          await new Promise<void>((resolve) => (gate.release = resolve))
        },
        onStop: () => events.push('stop:r1')
      })
    )

    const p1 = mgr.start(opts)
    const pStop = mgr.stop() // user clicks Stop (or the app quits) mid-load
    await new Promise((r) => setTimeout(r, 0))
    gate.release?.()
    await Promise.all([p1, pStop])

    expect(events).toEqual(['start:r1', 'stop:r1'])
    expect(mgr.active()).toBeNull()
    expect(mgr.status().running).toBe(false)
  })

  it('a later successful start works after an earlier failed one', async () => {
    let mode: 'fail' | 'ok' = 'fail'
    const mgr = new RuntimeManager(() =>
      runtime({
        modelId: mode === 'ok' ? 'good' : 'bad',
        start: async () => {
          if (mode === 'fail') throw new Error('boom')
        }
      })
    )
    await expect(mgr.start(opts)).rejects.toThrow(/boom/)
    expect(mgr.active()).toBeNull()
    mode = 'ok'
    const status = await mgr.start(opts)
    expect(status.running).toBe(true)
    expect(mgr.activeModelId()).toBe('good')
  })
})

// REL-1 (audit 2026-06-28) — the GPU mid-session crash auto-fallback, wired THROUGH the real
// RuntimeManager + the real createSelectingRuntimeFactory + the real createGpuCrashAutoFallback,
// with the fake placed at the SPAWN/child level (no fake `restart` is injected — the production
// `restart → manager.forceRestart` wiring is exercised verbatim). This is the path the existing
// runtime-ladder/runtime-manager unit tests never connected: ladder tests inject a fake `restart`
// (so the manager interaction is skipped) and manager tests prove the idempotency guard in
// isolation. Before the fix, the crash restart hit that guard (the crashed runtime is still
// `current` with the same modelId) and was silently swallowed.

const CRASH_OPTS: RuntimeStartOptions = { modelId: 'm', modelPath: '/w.gguf', contextTokens: 2048 }
const RTX: GpuDevice = {
  id: 'Vulkan0',
  name: 'NVIDIA GeForce RTX 3080 Ti',
  totalMb: 12300,
  freeMb: 11511
}

/** A fake llama-server child: it never exits on its own until `crash()` is called. */
class FakeServerChild extends EventEmitter implements ChildProcessLike {
  readonly pid: number
  killed = false
  exited = false
  constructor(pid: number) {
    super()
    this.pid = pid
  }
  kill(signal?: NodeJS.Signals | number): boolean {
    this.killed = true
    if (!this.exited) {
      this.exited = true
      queueMicrotask(() => this.emit('exit', 0, signal ?? null))
    }
    return true
  }
  /** Simulate a mid-session crash: a healthy server dies on its own (driver crash / VRAM theft). */
  crash(code: number): void {
    if (this.exited) return
    this.exited = true
    this.emit('exit', code, null)
  }
}

/**
 * Wire the REAL stack as `main/index.ts` does — the §5.3 GPU fallback (`createGpuCrashAutoFallback`)
 * and the #599 CPU crash handler (`createCpuCrashAutoRestart`) routed to `manager.forceRestart` /
 * `manager.stopCrashed`, `createSelectingRuntimeFactory` with the ladder hooks, `RuntimeManager` —
 * minus the composition's lock admission (AUD-02) and the speculative rung. A fake child is
 * injected at the spawn seam, and a loopback `fetch` only answers for a LIVE child's port (so a
 * request routed to a dead server actually fails, the way it would in prod).
 */
function crashHarness() {
  let pidSeq = 100
  let portSeq = 52000
  let pendingPort = 0
  const children: Array<{ child: FakeServerChild; args: string[]; port: number }> = []
  const liveByPort = new Map<number, FakeServerChild>()

  const findPort = async (): Promise<number> => {
    pendingPort = ++portSeq
    return pendingPort
  }
  const spawn: SpawnFn = (_command, args) => {
    const child = new FakeServerChild(++pidSeq)
    liveByPort.set(pendingPort, child)
    children.push({ child, args, port: pendingPort })
    return child
  }
  const fetchImpl = (async (url: string | URL) => {
    const u = new URL(String(url))
    const child = liveByPort.get(Number(u.port))
    // A crashed server's socket is gone — refuse the connection, so a chat/health routed to the
    // dead runtime genuinely fails (this is what gives the post-crash chat assertion its teeth).
    if (!child || child.exited) throw new Error('connect ECONNREFUSED (llama-server is gone)')
    if (u.pathname === '/health') return { ok: true, status: 200 } as Response
    if (u.pathname === '/v1/chat/completions') {
      const body = sseBody('data: {"choices":[{"delta":{"content":"hello"}}]}\n\ndata: [DONE]\n\n')
      return { ok: true, status: 200, body } as unknown as Response
    }
    throw new Error(`unexpected url ${u.pathname}`)
  }) as typeof fetch

  // The makeLlama seam builds the REAL LlamaRuntime over the fake child (so the real LlamaServer
  // unexpected-exit hook → LadderRuntime → onGpuCrash chain runs); we spy each runtime's stop()
  // to count the stops the crash path drives.
  const made: Array<{ stops: number; extraArgs: string[] }> = []
  const makeLlama = (o: RuntimeStartOptions, binPath: string, rung?: LlamaRungOptions): ModelRuntime => {
    const rt = createLlamaRuntime(o, {
      binPath,
      extraArgs: rung?.extraArgs,
      onUnexpectedExit: rung?.onUnexpectedExit,
      spawn,
      fetchImpl,
      findPort,
      healthIntervalMs: 1
    })
    const rec = { stops: 0, extraArgs: rung?.extraArgs ?? [] }
    const origStop = rt.stop.bind(rt)
    ;(rt as { stop: () => Promise<void> }).stop = async () => {
      rec.stops++
      return origStop()
    }
    made.push(rec)
    return rt
  }

  let gpuAutoDisabled = false
  const persisted: string[] = []
  const notices: string[] = []

  // Late-bind the manager into the crash fallback, exactly as main/index.ts does.
  let mgrRef: RuntimeManager | null = null
  const restartPromises: Array<Promise<unknown>> = []
  const fallback = createGpuCrashAutoFallback({
    restart: (o) => {
      const p = mgrRef!.forceRestart(o)
      restartPromises.push(p)
      return p
    },
    persistFailure: (reason) => {
      gpuAutoDisabled = true // before the restart → the rebuilt ladder skips rung 1 → CPU
      persisted.push(reason)
    },
    notify: (m) => notices.push(m)
  })
  const cpuCrashPromises: Array<Promise<unknown>> = []
  const cpuCrash = createCpuCrashAutoRestart({
    restart: (o) => {
      const p = mgrRef!.forceRestart(o)
      cpuCrashPromises.push(p)
      return p
    },
    stop: (o) => {
      const p = mgrRef!.stopCrashed(o.modelId)
      cpuCrashPromises.push(p)
      return p
    }
  })

  const factory = createSelectingRuntimeFactory({
    rootPath: '/root',
    resolveBin: () => '/bin/llama-server',
    modelExists: () => true,
    makeLlama,
    gpu: {
      getGpuMode: () => 'auto',
      getGpuAutoDisabled: () => gpuAutoDisabled,
      onGpuFailure: (reason) => persisted.push(reason),
      probeDevices: async () => (gpuAutoDisabled ? [] : [RTX]),
      resolveCpuBin: () => null,
      onGpuCrash: (o, info) => fallback(o, info),
      onCpuCrash: (o, info) => cpuCrash(o, info)
    }
  })
  const mgr = new RuntimeManager(factory)
  mgrRef = mgr

  return {
    mgr,
    children,
    made,
    persisted,
    notices,
    restartPromises,
    cpuCrashPromises,
    gpuDisabled: () => gpuAutoDisabled
  }
}

describe('GPU mid-session crash auto-fallback through the real manager (REL-1)', () => {
  it('forces a real CPU restart on an unexpected exit — exactly one stop + one start, status reflects the NEW server', async () => {
    const h = crashHarness()

    // 1. A GPU-backed runtime is current + healthy.
    const start = await h.mgr.start(CRASH_OPTS)
    expect(start.backend).toBe('gpu')
    expect(h.mgr.status().healthy).toBe(true)
    expect(h.children).toHaveLength(1)
    const deadPort = h.children[0].port

    // 2. The GPU server dies mid-session (driver crash / VRAM stolen).
    h.children[0].child.crash(134)
    // The fallback fires `restart` fire-and-forget (`void restart(opts)`); await its completion.
    await Promise.all(h.restartPromises)
    expect(h.restartPromises).toHaveLength(1)

    // 3. The real path actually restarted: one new spawn (not zero = swallowed, not a loop),
    //    the dead runtime stopped exactly once, the new backend is CPU, and status() reflects
    //    the NEW server — not the dead one whose cached health used to be reported as live.
    expect(h.children).toHaveLength(2)
    expect(h.made[0].stops).toBe(1) // the crashed runtime was stopped
    expect(h.made[1].stops).toBe(0) // the restarted runtime is still live
    expect(h.children[0].args).not.toContain('none') // rung 1 — GPU auto-offload
    expect(h.children[1].args).toContain('none') // rung 2 — `--device none` (forced CPU)
    expect(h.gpuDisabled()).toBe(true) // persisted before the restart (retry lands on CPU)
    expect(h.notices).toEqual([t('en', 'main.runtime.compatibilityMode')])

    const status = h.mgr.status()
    expect(status.backend).toBe('cpu')
    expect(status.healthy).toBe(true)
    expect(status.modelId).toBe('m')
    expect(status.port).toBe(h.children[1].port)
    expect(status.port).not.toBe(deadPort)

    // 4. A chat turn AFTER the crash succeeds against the restarted (CPU) server. On the pre-fix
    //    code this routed to the dead server's refused socket and threw.
    const tokens: string[] = []
    for await (const tok of h.mgr.active()!.chatStream([{ role: 'user', content: 'hi' }])) {
      tokens.push(tok)
    }
    expect(tokens.join('')).toBe('hello')

    // 5. T8 (post-merge audit Phase 5): `made[0].stops===1` above only counts the stop() WRAPPER —
    //    it would still hold if stop() stopped reaching the child kill (an orphan). Pin the REAL
    //    reap on observable child state. The crashed child already exited, so the manager correctly
    //    does NOT re-kill it (no orphan to reap) — its `killed` stays false; what must hold is that
    //    the LIVE restarted CPU child is genuinely killed by the manager's stop(). (DIVERGES from the
    //    audit's literal "crashed child killed===true", which is false on correct code — the crashed
    //    child is already dead, so stop() early-returns on `this.exited` before any kill.)
    expect(h.children[0].child.exited).toBe(true) // the crashed GPU child is genuinely dead
    await h.mgr.stop()
    expect(h.children[1].child.killed).toBe(true) // stop() reached the LIVE child's kill — real reap
  })

  it('does NOT loop: after the GPU fallback a CPU crash restarts once, the next one stops the model (#599)', async () => {
    const h = crashHarness()
    await h.mgr.start(CRASH_OPTS)
    h.children[0].child.crash(134) // GPU crash → the §5.3 fallback: one CPU restart
    await Promise.all(h.restartPromises)
    expect(h.children).toHaveLength(2)
    expect(h.mgr.status().backend).toBe('cpu')
    // The restarted CPU server crashes: NOT a GPU-fallback case (the ladder routes it to onCpuCrash) —
    // its one #599 restart, through the real forceRestart.
    h.children[1].child.crash(1)
    await Promise.all(h.cpuCrashPromises)
    expect(h.children).toHaveLength(3)
    expect(h.children[2].args).toContain('none') // still CPU
    expect(h.mgr.status()).toMatchObject({ running: true, backend: 'cpu', healthy: true })
    // It crashes again: the restart is spent — stopCrashed reads the dead sidecar's /health and drops it.
    h.children[2].child.crash(1)
    await Promise.all(h.cpuCrashPromises)
    expect(h.children).toHaveLength(3) // no fourth spawn
    expect(h.mgr.status().running).toBe(false)
    expect(h.restartPromises).toHaveLength(1) // the GPU fallback fired exactly once
  })
})

// ---- #109: the hidden warm-up generation, through the REAL manager + LlamaRuntime ----
//
// The unit coverage (runtime-ladder.test.ts, "hidden warm-up generation (#109)") drives a fake
// chatStream. These two tests pin the same guarantees through the real SSE path: a healthy
// server whose /v1/chat/completions has not finished streaming holds `RuntimeManager.status()`
// at "Starting" (ready means warmed), and a stop() landing inside that window still settles
// promptly as a cancelled start (the killed child's socket teardown errors the warm-up stream).

/** Real LlamaRuntime over a fake child; the warm-up SSE stream stays open until release(). */
function warmupWindowHarness() {
  const child = new RecordingChild('SIGTERM')
  let completionRequests = 0
  let release: () => void = () => {}
  const gate = new Promise<void>((r) => (release = r))
  const fetchImpl = (async (url: string | URL) => {
    if (String(url).endsWith('/health')) return { ok: true, status: 200 } as Response
    if (String(url).endsWith('/v1/chat/completions')) {
      completionRequests++
      const body = new ReadableStream<Uint8Array>({
        start(c) {
          // The socket dies with the server — a stop() mid-warm-up must error the read,
          // exactly as a killed llama-server tears down its connections in prod.
          child.once('exit', () => {
            try {
              c.error(new Error('socket closed (llama-server is gone)'))
            } catch {
              /* already closed */
            }
          })
          void gate.then(() => {
            try {
              c.enqueue(
                new TextEncoder().encode('data: {"choices":[{"delta":{"content":"ok"}}]}\n\ndata: [DONE]\n\n')
              )
              c.close()
            } catch {
              /* errored first (stop-path test) */
            }
          })
        }
      })
      return { ok: true, status: 200, body } as unknown as Response
    }
    throw new Error(`unexpected url ${String(url)}`)
  }) as typeof fetch

  const factory = createSelectingRuntimeFactory({
    rootPath: '/root',
    resolveBin: () => '/bin/llama-server',
    modelExists: () => true,
    makeLlama: (o, binPath, rung?: LlamaRungOptions) =>
      createLlamaRuntime(o, {
        binPath,
        extraArgs: rung?.extraArgs,
        onUnexpectedExit: rung?.onUnexpectedExit,
        spawn: () => child,
        fetchImpl,
        findPort: async () => 52200,
        healthIntervalMs: 1
      }),
    gpu: { probeDevices: async () => [], resolveCpuBin: () => null }
  })
  return {
    mgr: new RuntimeManager(factory),
    child,
    release,
    completionRequests: () => completionRequests
  }
}

describe('#109 warm-up window through the real manager', () => {
  it('a healthy server mid-warm-up still reports "Starting"; ready lands only after the stream ends', async () => {
    const h = warmupWindowHarness()
    const startP = h.mgr.start(QUIT_OPTS)
    await until(() => h.completionRequests() > 0, 'the first completion request')

    // /health said yes long ago — but the warm-up generation is still streaming.
    expect(h.mgr.status().running).toBe(false)
    expect(h.mgr.status().message).toBe('Starting')
    expect(h.mgr.status().startingModelId).toBe('m')

    h.release()
    const status = await startP
    expect(status.running).toBe(true)
    expect(status.healthy).toBe(true)
    expect(status.warmedUp).toBe(false) // the #39 hint stays armed (served did not flip)
    expect(h.completionRequests()).toBe(1)
    await h.mgr.stop()
  })

  it('stop() during the warm-up settles promptly as a cancelled start — no orphan, no commit', async () => {
    const h = warmupWindowHarness()
    const startP = h.mgr.start(QUIT_OPTS)
    startP.catch(() => undefined)
    await until(() => h.completionRequests() > 0, 'the first completion request')

    const t0 = Date.now()
    await h.mgr.stop() // pre-#109 semantics preserved: the CODE-2 cancel reaches the new window
    expect(Date.now() - t0).toBeLessThan(hangBudgetMs(5_000)) // a hang detector: the warm-up cap is 90 s
    expect(h.child.killed).toBe(true)
    await expect(startP).rejects.toThrow(/cancelled/i)
    expect(h.mgr.active()).toBeNull()
    expect(h.mgr.status().running).toBe(false)
  })
})

// ---- Phase C (full-audit 2026-07-11): CODE-2 cancellable start + CODE-3 shutdown latch ----
//
// CODE-2: `stop()` used to QUEUE behind an uncancellable in-flight start — a 20 GB GGUF load
// (or a failing ladder walking up to 3 rungs × 180 s health timeouts) held the queue for
// minutes while quit and "Lock now" both awaited it; users hard-kill, which orphans the
// loading child — the exact outcome the queue exists to prevent. `LlamaServer.stop()`
// DURING `waitForHealthy` already worked one layer down (the exit-check throw); these tests
// pin that the manager's stop now actually REACHES it.
// CODE-3: `performShutdown` had no latch, so an auto-start whose multi-GB weight hash
// completed during the ~7 s of awaited teardown windows could enqueue a fresh start AFTER
// the stop; `app.exit(0)` then killed the parent mid-start and orphaned the child.

const QUIT_OPTS: RuntimeStartOptions = { modelId: 'm', modelPath: '/w.gguf', contextTokens: 2048 }

/**
 * The REAL ladder + REAL LlamaRuntime/LlamaServer over a fake child that never turns
 * healthy (a slow multi-GB load, /health stays 503). `healthTimeoutMs` is 60 s so the
 * PRE-fix behavior (stop waits out the whole timeout) reds as a test timeout, while the
 * fixed prompt-cancel path settles in milliseconds.
 */
function loadingStartHarness() {
  const child = new RecordingChild('SIGTERM')
  let spawned = 0
  const failures: string[] = []
  let mockMade = false
  const makeLlama = (o: RuntimeStartOptions, binPath: string, rung?: LlamaRungOptions): ModelRuntime =>
    createLlamaRuntime(o, {
      binPath,
      extraArgs: rung?.extraArgs,
      onUnexpectedExit: rung?.onUnexpectedExit,
      spawn: () => {
        spawned++
        return child
      },
      fetchImpl: (async () => ({ ok: false, status: 503 }) as Response) as typeof fetch,
      findPort: async () => 52100,
      healthTimeoutMs: 60_000,
      healthIntervalMs: 5
      // (no killGraceMs seam through LlamaRuntimeDeps — irrelevant: the fake child dies on SIGTERM)
    })
  const factory = createSelectingRuntimeFactory({
    rootPath: '/root',
    resolveBin: () => '/bin/llama-server',
    modelExists: () => true,
    makeLlama,
    makeMock: (o) => {
      mockMade = true
      return {
        modelId: o.modelId,
        backend: 'mock',
        start: async () => {},
        stop: async () => {},
        health: async () => ({ healthy: true, message: 'mock', port: null }),
        chatStream: async function* () {}
      }
    },
    gpu: {
      probeDevices: async () => [],
      onGpuFailure: (r) => failures.push(r),
      resolveCpuBin: () => null
    }
  })
  return {
    mgr: new RuntimeManager(factory),
    child,
    failures,
    spawnCount: () => spawned,
    wasMock: () => mockMade
  }
}

const tick = (ms = 1): Promise<void> => new Promise((r) => setTimeout(r, ms))

describe('quit-path lifecycle (full-audit 2026-07-11 CODE-2/CODE-3)', () => {
  it('stop() mid-start kills the loading child and settles promptly (CODE-2, mid-waitForHealthy)', async () => {
    const h = loadingStartHarness()
    const startP = h.mgr.start(QUIT_OPTS)
    startP.catch(() => undefined) // asserted below; pre-arm so no unhandled rejection
    await until(() => h.spawnCount() > 0, 'the runtime spawn')
    const t0 = Date.now()
    await h.mgr.stop() // pre-fix: queued behind the full 60 s health timeout → test timeout
    expect(Date.now() - t0).toBeLessThan(hangBudgetMs(5_000)) // a hang detector, not a timing proof
    expect(h.child.killed).toBe(true)
    await expect(startP).rejects.toThrow(/cancelled/i)
    // A start killed by the cancel is NOT a GPU fault — nothing persists gpuAutoDisabled…
    expect(h.failures).toEqual([])
    // …and the ladder walk aborted: no rung-2 respawn, no mock fallback for a cancelled start.
    expect(h.spawnCount()).toBe(1)
    expect(h.wasMock()).toBe(false)
    expect(h.mgr.active()).toBeNull()
    expect(h.mgr.status().running).toBe(false)
  })

  it('performShutdown during a model start settles promptly and latches the manager (CODE-2/CODE-3 quit path)', async () => {
    const h = loadingStartHarness()
    const startP = h.mgr.start(QUIT_OPTS)
    startP.catch(() => undefined)
    await until(() => h.spawnCount() > 0, 'the runtime spawn')

    const ctx = {
      runtime: h.mgr,
      embedder: {},
      workspace: workspaceStandIn()
    } as unknown as AppContext
    await performShutdown(ctx, {
      inFlightStreams: new Map(),
      streamSettled: new Map(),
      detachVaultKey: () => undefined,
      log: { error: () => undefined, info: () => undefined }
    })

    expect(h.child.killed).toBe(true) // the loading child died with the teardown — no orphan
    await expect(startP).rejects.toThrow(/cancelled/i) // a quit mid-start reads as a cancelled start
    // The latch is armed: a late auto-start (its weight hash just completed) can't spawn.
    await expect(h.mgr.start(QUIT_OPTS)).rejects.toThrow(/shut down/i)
    expect(h.spawnCount()).toBe(1)
  })

  it('start() after shutdown() rejects WITHOUT invoking the factory (CODE-3)', async () => {
    let made = 0
    const mgr = new RuntimeManager(() => {
      made++
      return {
        modelId: 'm',
        start: async () => {},
        stop: async () => {},
        health: async () => ({ healthy: true, message: '', port: 1 }),
        chatStream: async function* () {}
      }
    })
    mgr.shutdown()
    expect(mgr.isShutdown()).toBe(true)
    await expect(mgr.start(QUIT_OPTS)).rejects.toThrow(/shut down/i)
    await expect(mgr.forceRestart(QUIT_OPTS)).rejects.toThrow(/shut down/i) // crash restart too
    expect(made).toBe(0)
    // stop() still works after the latch (it IS the teardown) — a no-op here.
    await expect(mgr.stop()).resolves.toBeUndefined()
  })

  // CODE-3 review follow-up: doStart's TOP latch check can already have passed when quit
  // arms the latch — a model SWITCH first spends `await this.doStop()` seconds killing the
  // old runtime (SIGTERM → grace → SIGKILL), and in that window `startingRuntime` is not
  // yet set either, so stop()'s CODE-2 cancel misses. Without a re-check AFTER the internal
  // stop, the factory then spawns and the quit's queued stop waits out the full model load.
  it("quit landing inside a model-switch's internal stop never spawns the new model (CODE-3 follow-up)", async () => {
    let made = 0
    let releaseStop: () => void = () => undefined
    const stopGate = new Promise<void>((r) => (releaseStop = r))
    const mgr = new RuntimeManager((o) => {
      made++
      return {
        modelId: o.modelId,
        start: async () => {},
        stop: async () => {
          if (o.modelId === 'a') await stopGate // the old runtime's teardown takes a while
        },
        health: async () => ({ healthy: true, message: '', port: 1 }),
        chatStream: async function* () {}
      }
    })
    await mgr.start({ modelId: 'a', modelPath: '/a.gguf', contextTokens: 2048 })
    expect(made).toBe(1)

    // The switch: doStart('b') passes its TOP latch check, then parks inside doStop('a').
    const p2 = mgr.start({ modelId: 'b', modelPath: '/b.gguf', contextTokens: 2048 })
    await tick(0)
    expect(made).toBe(1) // still stopping 'a' — 'b' has not been built yet
    mgr.shutdown() // quit arms the latch INSIDE that window (top check already passed)
    releaseStop()

    await expect(p2).rejects.toThrow(/shut down/i)
    expect(made).toBe(1) // the post-internal-stop re-check refused BEFORE the factory ran
    await expect(mgr.stop()).resolves.toBeUndefined() // the quit's queued stop settles promptly
    expect(mgr.active()).toBeNull()
  })

  it('a start already ENQUEUED when shutdown() arms never spawns (CODE-3)', async () => {
    const events: string[] = []
    const gate: { release: (() => void) | null } = { release: null }
    let made = 0
    const mgr = new RuntimeManager((o) => {
      made++
      return {
        modelId: o.modelId,
        start: async () => {
          events.push(`start:${o.modelId}`)
          if (o.modelId === 'a') await new Promise<void>((r) => (gate.release = r))
        },
        stop: async () => {
          events.push(`stop:${o.modelId}`)
        },
        health: async () => ({ healthy: true, message: '', port: 1 }),
        chatStream: async function* () {}
      }
    })
    const p1 = mgr.start({ modelId: 'a', modelPath: '/a.gguf', contextTokens: 2048 })
    // b is enqueued BEHIND a's in-flight start (a switch) — it passed start()'s entry check
    // before the latch armed, so only doStart's re-check can stop it from spawning.
    const p2 = mgr.start({ modelId: 'b', modelPath: '/b.gguf', contextTokens: 2048 })
    await tick(0)
    mgr.shutdown() // quit begins while b still sits in the queue
    gate.release?.()
    await p1 // a committed (it started before the latch)
    await expect(p2).rejects.toThrow(/shut down/i)
    expect(made).toBe(1) // b's factory was NEVER invoked
    expect(events).toEqual(['start:a'])
  })
})

// ---- Generation gate (local-api P1) ------------------------------------------------------
//
// The busy signal for external (local-API) admission lives at the MANAGER, not in any one
// runtime: doStart wraps whatever the factory returned (ladder AND mock — the gate CI
// exercises is the shipped one) so every lane that reaches the model via active().chatStream
// — chat/RAG, doc tasks, skill runs, the benchmark, compaction, classification — is counted
// with zero call-site changes. Known bypass, covered by fail-closed admission: the #109
// warm-up generation talks to the INNER rung runtime while active() is still null, so
// "no active runtime ⇒ busy" (asserted in local-api-admission.test.ts) closes that window.

/** Manager whose factory returns a runtime streaming from a fresh manualSource per call. */
async function gatedHarness() {
  const sources: ManualSource[] = []
  const mgr = new RuntimeManager((startOpts) => ({
    modelId: startOpts.modelId,
    start: async () => {},
    stop: async () => {},
    health: async () => ({ healthy: true, message: '', port: null }),
    chatStream(_messages, options?: RuntimeChatOptions) {
      const src = manualSource()
      sources.push(src)
      return src.stream(options?.signal)
    }
  }))
  await mgr.start({ modelId: 'gate-m', modelPath: '/m.gguf', contextTokens: 2048 })
  const runtime = mgr.active()!
  return { mgr, runtime, sources }
}

describe('RuntimeManager generation gate (local-api P1)', () => {
  it('counts an in-app stream while it runs; created-but-never-iterated holds NO count', async () => {
    const { mgr, runtime, sources } = await gatedHarness()
    expect(mgr.isGenerating()).toBe(false)
    const gen = runtime.chatStream([{ role: 'user', content: 'q' }])
    // Created but never pulled: the counter must not move (perf M5 leak class).
    expect(mgr.isGenerating()).toBe(false)
    const first = gen.next()
    await Promise.resolve()
    expect(mgr.isGenerating()).toBe(true)
    sources[0].push('tok')
    expect((await first).value).toBe('tok')
    expect(mgr.isGenerating()).toBe(true)
    sources[0].end()
    expect((await gen.next()).done).toBe(true)
    expect(mgr.isGenerating()).toBe(false)
  })

  it('releases the count on an inner error and on consumer abandonment (gen.return)', async () => {
    const { mgr, runtime, sources } = await gatedHarness()
    // Error path.
    const failing = runtime.chatStream([{ role: 'user', content: 'q' }])
    const firstPull = failing.next()
    await Promise.resolve()
    expect(mgr.isGenerating()).toBe(true)
    sources[0].fail(new Error('mid-stream crash'))
    await expect(firstPull).rejects.toThrow('mid-stream crash')
    expect(mgr.isGenerating()).toBe(false)
    // Abandonment path (the consumer walks away without erroring).
    const abandoned = runtime.chatStream([{ role: 'user', content: 'q' }])
    const pull = abandoned.next()
    await Promise.resolve()
    expect(mgr.isGenerating()).toBe(true)
    sources[1].push('tok')
    await pull
    await abandoned.return()
    expect(mgr.isGenerating()).toBe(false)
  })

  it('releases the count when the inner runtime throws BEFORE the first yield', async () => {
    const mgr = new RuntimeManager((opts) => ({
      modelId: opts.modelId,
      start: async () => {},
      stop: async () => {},
      health: async () => ({ healthy: true, message: '', port: null }),
      // The real runtime's synchronous guard: LadderRuntime.chatStream is a plain method that throws
      // RuntimeConnectionLostError at CALL time (#600) — before any generator exists.
      chatStream: () => {
        throw new RuntimeConnectionLostError()
      }
    }))
    await mgr.start({ modelId: 'm', modelPath: '/m.gguf', contextTokens: 2048 })
    const gen = mgr.active()!.chatStream([{ role: 'user', content: 'q' }])
    await expect(gen.next()).rejects.toThrow(RuntimeConnectionLostError)
    expect(mgr.isGenerating()).toBe(false) // a pre-yield throw must not wedge the gate
  })

  it('REFUSES an external stream while an in-app generation is active (429 class)', async () => {
    const { mgr, runtime, sources } = await gatedHarness()
    const inApp = runtime.chatStream([{ role: 'user', content: 'q' }])
    const inAppFirst = inApp.next()
    await Promise.resolve()
    sources[0].push('a')
    await inAppFirst
    const external = runtime.chatStream([{ role: 'user', content: 'x' }], { lane: 'external' })
    await expect(external.next()).rejects.toThrow(ExternalGenerationBusyError)
    // The refusal released its own count — the in-app stream still owns the gate.
    expect(mgr.isGenerating()).toBe(true)
    sources[0].end()
    await inApp.return()
    expect(mgr.isGenerating()).toBe(false)
  })

  it('TOCTOU probe: an external generator created BEFORE the in-app turn cannot start after it', async () => {
    const { runtime, sources } = await gatedHarness()
    // "Admitted" external request, parked before its first pull (the admit→stream await gap).
    const external = runtime.chatStream([{ role: 'user', content: 'x' }], { lane: 'external' })
    // An in-app turn enters and starts streaming.
    const inApp = runtime.chatStream([{ role: 'user', content: 'q' }])
    const inAppFirst = inApp.next()
    await Promise.resolve()
    sources[0].push('a')
    await inAppFirst
    // The parked external now tries to start: the same-frame check refuses it.
    await expect(external.next()).rejects.toThrow(ExternalGenerationBusyError)
    sources[0].end()
    await inApp.return()
  })

  it('an entering in-app turn pre-empts the external lane and AWAITS its real teardown (D8)', async () => {
    const { mgr, runtime, sources } = await gatedHarness()
    const order: string[] = []
    const externalAbort = new AbortController()
    mgr.setExternalPreemption(() => {
      order.push('preempt-hook')
      externalAbort.abort(new DOMException('preempted', 'AbortError'))
    })
    // External stream running.
    const external = runtime.chatStream([{ role: 'user', content: 'x' }], {
      lane: 'external',
      signal: externalAbort.signal
    })
    const extFirst = external.next()
    await Promise.resolve()
    sources[0].push('e1')
    await extFirst
    expect(mgr.isGenerating()).toBe(true)
    // The in-app turn enters while the external consumer is BETWEEN pulls: the hook aborts it, but its
    // count only drops when the consumer pulls again — its real teardown. Until then the in-app
    // generation must not reach the runtime.
    const inApp = runtime.chatStream([{ role: 'user', content: 'q' }])
    const inAppFirst = (async () => {
      const r = await inApp.next()
      order.push(`in-app-first:${String(r.value)}`)
      return r
    })()
    await tick(0) // one macrotask: every microtask the in-app entry could chain has run
    expect(order).toEqual(['preempt-hook'])
    expect(sources).toHaveLength(1) // parked on the external teardown — not issued
    const r = await external.next() // the consumer resumes: the abort ends its stream, the count drops
    order.push(`external-settled:${r.done}`)
    await until(() => sources.length === 2, 'the in-app generation issued once the external stream ended')
    sources[1].push('a1')
    await inAppFirst
    expect(order).toEqual(['preempt-hook', 'external-settled:true', 'in-app-first:a1'])
    expect(mgr.isGenerating()).toBe(true) // the in-app stream now owns the gate
    sources[1].end()
    await inApp.return()
    expect(mgr.isGenerating()).toBe(false)
    mgr.setExternalPreemption(null)
  })

  it('an external stream never fires the pre-emption hook (no self-pre-emption, perf M4)', async () => {
    const { mgr, runtime, sources } = await gatedHarness()
    const hook = vi.fn()
    mgr.setExternalPreemption(hook)
    const first = runtime.chatStream([{ role: 'user', content: 'x' }], { lane: 'external' })
    const firstPull = first.next()
    await Promise.resolve()
    sources[0].push('e')
    await firstPull
    sources[0].end()
    expect((await first.next()).done).toBe(true)
    // A second external request after the first — still no pre-emption anywhere.
    const second = runtime.chatStream([{ role: 'user', content: 'y' }], { lane: 'external' })
    const secondPull = second.next()
    await Promise.resolve()
    sources[1].push('e2')
    await secondPull
    sources[1].end()
    await second.return()
    expect(hook).not.toHaveBeenCalled()
    mgr.setExternalPreemption(null)
  })

  it('a throwing pre-emption hook never fails the in-app turn', async () => {
    const { mgr, runtime, sources } = await gatedHarness()
    const externalAbort = new AbortController()
    mgr.setExternalPreemption(() => {
      externalAbort.abort()
      throw new Error('hook exploded')
    })
    const external = runtime.chatStream([{ role: 'user', content: 'x' }], {
      lane: 'external',
      signal: externalAbort.signal
    })
    const extFirst = external.next()
    await Promise.resolve()
    sources[0].push('e')
    await extFirst
    const drain = (async () => {
      await external.next() // abort → done on next pull
    })()
    const inApp = runtime.chatStream([{ role: 'user', content: 'q' }])
    const pull = inApp.next()
    await drain
    sources[1].push('a')
    expect((await pull).value).toBe('a')
    sources[1].end()
    await inApp.return()
    mgr.setExternalPreemption(null)
  })

  it('two concurrent IN-APP streams are both admitted (the gate serializes external only)', async () => {
    // Pre-existing app behavior (A6/A7): in-app lanes are not serialized by this gate —
    // it makes them VISIBLE to external admission. This pin documents that boundary.
    const { mgr, runtime, sources } = await gatedHarness()
    const g1 = runtime.chatStream([{ role: 'user', content: '1' }])
    const g2 = runtime.chatStream([{ role: 'user', content: '2' }])
    const p1 = g1.next()
    const p2 = g2.next()
    await Promise.resolve()
    sources[0].push('a')
    sources[1].push('b')
    await p1
    await p2
    expect(mgr.isGenerating()).toBe(true)
    sources[0].end()
    sources[1].end()
    await g1.return()
    await g2.return()
    expect(mgr.isGenerating()).toBe(false)
  })

  it('the gate rides the MOCK factory path too (maintainer F4 — the gate CI exercises)', async () => {
    // No binary ⇒ createSelectingRuntimeFactory returns the MockRuntime directly (never
    // a ladder) — the decorator must still wrap it.
    const factory = createSelectingRuntimeFactory({ rootPath: '/nope', resolveBin: () => null })
    const mgr = new RuntimeManager(factory)
    await mgr.start({ modelId: 'mock-m', modelPath: '/nope.gguf', contextTokens: 2048 })
    const runtime = mgr.active()!
    expect(runtime.backend).toBe('mock')
    const gen = runtime.chatStream([{ role: 'user', content: 'hello' }])
    const first = await gen.next()
    expect(first.done).toBe(false)
    expect(mgr.isGenerating()).toBe(true)
    // An external request during the mock stream is refused exactly like on the ladder.
    const external = runtime.chatStream([{ role: 'user', content: 'x' }], { lane: 'external' })
    await expect(external.next()).rejects.toThrow(ExternalGenerationBusyError)
    await gen.return()
    expect(mgr.isGenerating()).toBe(false)
    await mgr.stop()
  })

  it('REFUSES a second concurrent external stream (the slot is single, structurally)', async () => {
    const { runtime, sources } = await gatedHarness()
    const first = runtime.chatStream([{ role: 'user', content: 'x' }], { lane: 'external' })
    const firstPull = first.next()
    await Promise.resolve()
    sources[0].push('e1')
    await firstPull
    // Admission serialization is advisory — the gate itself must refuse the overlap.
    const second = runtime.chatStream([{ role: 'user', content: 'y' }], { lane: 'external' })
    await expect(second.next()).rejects.toThrow(ExternalGenerationBusyError)
    sources[0].end()
    await first.return()
  })

  it('fires the pre-emption hook on EVERY in-app entry — an admitted-but-unstarted external is cancelled too', async () => {
    const { mgr, runtime, sources } = await gatedHarness()
    const hook = vi.fn()
    mgr.setExternalPreemption(hook)
    // No external stream is counted yet (the admitted request hasn't started) — the
    // hook must still fire so admission can abort the parked admission.
    const inApp = runtime.chatStream([{ role: 'user', content: 'q' }])
    const pull = inApp.next()
    await Promise.resolve()
    expect(hook).toHaveBeenCalledTimes(1)
    sources[0].push('a')
    await pull
    await inApp.return()
    mgr.setExternalPreemption(null)
  })

  it('bounds the pre-emption teardown wait — a consumer that never resumes cannot wedge in-app turns', async () => {
    vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
    try {
      const { mgr, runtime, sources } = await gatedHarness()
      // External stream started, then ABANDONED: no further pull, no return() — its
      // finally can never run, so the count stays 1 (the buggy-consumer class).
      const external = runtime.chatStream([{ role: 'user', content: 'x' }], { lane: 'external' })
      const extFirst = external.next()
      await Promise.resolve()
      sources[0].push('e1')
      await extFirst
      // In-app turn enters: waits the bound, then proceeds anyway (the abort already
      // killed the sidecar socket in production — the KV slot is free).
      const inApp = runtime.chatStream([{ role: 'user', content: 'q' }])
      const pull = inApp.next()
      await vi.advanceTimersByTimeAsync(4_999)
      expect(sources).toHaveLength(1) // still waiting inside the bound
      await vi.advanceTimersByTimeAsync(1) // EXTERNAL_TEARDOWN_TIMEOUT_MS = 5 s (data-contracts.md "bounded ~5 s (D8)")
      await until(() => sources.length === 2, 'the in-app turn proceeding past the 5 s bound')
      sources[1].push('a1')
      expect((await pull).value).toBe('a1')
      expect(mgr.isGenerating()).toBe(true)
      await inApp.return()
      // The abandoned external still leaks its count within this epoch (documented) …
      expect(mgr.isGenerating()).toBe(true)
    } finally {
      vi.useRealTimers()
    }
  })

  it('self-heals a leaked lane count on the next model start (gate epoch)', async () => {
    const { mgr, runtime, sources } = await gatedHarness()
    const abandoned = runtime.chatStream([{ role: 'user', content: 'x' }], { lane: 'external' })
    const pull = abandoned.next()
    await Promise.resolve()
    sources[0].push('e1')
    await pull
    expect(mgr.isGenerating()).toBe(true)
    // No return(), no further pull — the count is leaked. A model restart heals it.
    await mgr.start({ modelId: 'gate-m2', modelPath: '/m2.gguf', contextTokens: 2048 })
    expect(mgr.isGenerating()).toBe(false)
    // A live external stream on the NEW runtime …
    const fresh = mgr.active()!.chatStream([{ role: 'user', content: 'y' }], { lane: 'external' })
    const freshPull = fresh.next()
    await Promise.resolve()
    expect(mgr.isGenerating()).toBe(true)
    // … survives the stale stream's late teardown: its decrement belongs to the old epoch.
    await abandoned.return()
    expect(mgr.isGenerating()).toBe(true)
    sources[1].end()
    expect((await freshPull).done).toBe(true)
    expect(mgr.isGenerating()).toBe(false)
    await mgr.stop()
  })

  it('a user Stop during the pre-emption wait ends the in-app turn cleanly (no hang, no error)', async () => {
    // The 5 s bound can never fire: only the abort can end the wait.
    vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
    try {
      const { mgr, runtime, sources } = await gatedHarness()
      const external = runtime.chatStream([{ role: 'user', content: 'x' }], { lane: 'external' })
      const extFirst = external.next()
      await Promise.resolve()
      sources[0].push('e1')
      await extFirst
      const stop = new AbortController()
      const inApp = runtime.chatStream([{ role: 'user', content: 'q' }], { signal: stop.signal })
      const pull = inApp.next()
      await Promise.resolve()
      stop.abort() // the user stops while the turn is parked on external teardown
      const r = await within(pull, 'the in-app turn ending on the user Stop')
      expect(r.done).toBe(true) // clean abort shape, exactly like the runtimes' own
      expect(sources).toHaveLength(1) // the stopped turn never reached the runtime
      expect(mgr.isGenerating()).toBe(true) // only the external stream still counts
      sources[0].end()
      await external.return()
      expect(mgr.isGenerating()).toBe(false)
    } finally {
      vi.useRealTimers()
    }
  })
})

// #600 — a deliberate stop or switch of the chat model ends the work running on it FIRST (the model-stop
// hook, wired in main/index.ts to `endWorkOnModelStop`), so each answer ends as a clean stop instead of
// failing on the killed sidecar. The hook must run after the manager marks the model stopped (nothing new
// may start on it meanwhile) and before the kill, with no wait in between; never for the crash restart.
describe('the model-stop hook — a deliberate stop or switch ends in-flight work first (#600)', () => {
  async function hookHarness(hook?: (kind: 'stop' | 'switch') => void) {
    const order: string[] = []
    const mgr = new RuntimeManager((opts) => ({
      modelId: opts.modelId,
      start: async () => {},
      stop: async () => {
        order.push(`kill ${opts.modelId}`)
      },
      health: async () => ({ healthy: true, message: '', port: null }),
      // eslint-disable-next-line require-yield
      chatStream: async function* (): AsyncGenerator<string, void, unknown> {}
    }))
    mgr.setModelStopHook(hook ?? ((kind) => order.push(`hook ${kind}, active: ${mgr.active()?.modelId ?? 'none'}`)))
    await mgr.start({ modelId: 'a', modelPath: '/a.gguf', contextTokens: 2048 })
    return { mgr, order }
  }

  it.each([
    ['Stop runtime', (mgr: RuntimeManager) => mgr.stop(), 'stop'],
    // An engine update / the demo → real engine restart: the app starts the model again itself.
    ['a stop the app follows with a start', (mgr: RuntimeManager) => mgr.stop({ startFollows: true }), 'switch'],
    ['a switch to another model',(mgr: RuntimeManager) => mgr.start({ modelId: 'b', modelPath: '/b.gguf', contextTokens: 2048 }), 'switch']
  ])('%s: the hook runs once the model is marked stopped, then the kill', async (_label, act, kind) => {
    const { mgr, order } = await hookHarness()
    await act(mgr)
    expect(order).toEqual([`hook ${kind}, active: none`, 'kill a'])
  })

  it('the crash auto-restart (forceRestart) does not run it — that sidecar is dead and its answers already failed', async () => {
    const { mgr, order } = await hookHarness()
    await mgr.forceRestart({ modelId: 'a', modelPath: '/a.gguf', contextTokens: 2048 })
    expect(order).toEqual(['kill a'])
  })

  it('a hook that throws never blocks the stop', async () => {
    const { mgr, order } = await hookHarness(() => {
      throw new Error('boom')
    })
    await mgr.stop()
    expect(order).toEqual(['kill a'])
    expect(mgr.active()).toBeNull()
  })

  it('an in-app call whose turn is already aborted pre-empts nothing (the local API keeps its own stop code)', async () => {
    // A turn the hook ended inside its compaction pre-pass still calls the runtime (compaction swallows
    // the abort); that call must not label the external request `preempted_by_user`.
    const { mgr, runtime } = await gatedHarness()
    const preempt = vi.fn()
    mgr.setExternalPreemption(preempt)
    const stopped = new AbortController()
    stopped.abort()
    const gen = runtime.chatStream([{ role: 'user', content: 'q' }], { signal: stopped.signal })
    expect((await gen.next()).done).toBe(true)
    expect(preempt).not.toHaveBeenCalled()
    expect(mgr.isGenerating()).toBe(false)
    mgr.setExternalPreemption(null)
  })
})

// #599 — the running model's liveness. `last` used to be the start's health check, never re-read: the
// #594 hang (b9849, a frozen process answering neither chat nor /health) stayed "running, healthy" on
// every surface for 4½ minutes. Two signals now feed `status().unresponsive`: a /health re-probe on
// status reads (cached), and an answer the CB-5 watchdog ended (a wedged compute loop, which /health —
// served by the HTTP thread — cannot see).
describe('liveness of the running model (#599)', () => {
  async function livenessHarness() {
    const sources: ManualSource[] = []
    const health = { healthy: true }
    const probes = { count: 0 }
    const started: RuntimeStartOptions[] = []
    const order: string[] = []
    const mgr = new RuntimeManager((startOpts) => {
      started.push(startOpts)
      return {
        modelId: startOpts.modelId,
        start: async () => {},
        stop: async () => {
          order.push(`kill ${startOpts.modelId}`)
        },
        health: async () => {
          probes.count++
          return { healthy: health.healthy, message: health.healthy ? 'ok' : 'Health check failed', port: 1 }
        },
        chatStream(_messages, options?: RuntimeChatOptions) {
          const src = manualSource()
          sources.push(src)
          return src.stream(options?.signal)
        }
      }
    })
    mgr.setModelStopHook((kind) => order.push(`hook ${kind}`))
    const startOpts = { modelId: 'm', modelPath: '/m.gguf', contextTokens: 2048 }
    await mgr.start(startOpts)
    probes.count = 0 // the start's own health check
    return { mgr, sources, health, probes, started, order, startOpts }
  }

  async function answer(mgr: RuntimeManager, src: () => ManualSource, end: (s: ManualSource) => void): Promise<unknown> {
    const gen = mgr.active()!.chatStream([{ role: 'user', content: 'q' }])
    const pulled = gen.next()
    await Promise.resolve()
    end(src())
    try {
      await pulled
      for (;;) if ((await gen.next()).done) return null
    } catch (err) {
      return err
    }
  }

  it('an answer the watchdog ended marks the model unresponsive; a passing /health does not clear it, the next completed answer does', async () => {
    vi.useFakeTimers({ toFake: ['performance'] })
    try {
      const { mgr, sources, probes } = await livenessHarness()
      const err = await answer(mgr, () => sources[0], (s) => s.fail(new RuntimeUnresponsiveError(600_000)))
      expect(err).toBeInstanceOf(RuntimeUnresponsiveError)
      expect(mgr.status()).toMatchObject({ running: true, healthy: false, unresponsive: true })

      vi.advanceTimersByTime(10_000) // past the 10 s probe TTL
      await mgr.refreshHealth() // /health passes — the HTTP thread answers while the compute loop is wedged
      expect(probes.count).toBe(1) // the probe ran — and passed — yet …
      expect(mgr.status().unresponsive).toBe(true)

      await answer(mgr, () => sources[1], (s) => {
        s.push('fine')
        s.end()
      })
      expect(mgr.status()).toMatchObject({ healthy: true })
      expect(mgr.status().unresponsive).toBeUndefined()
    } finally {
      vi.useRealTimers()
    }
  })

  it('a failed /health re-probe marks it unresponsive until a probe passes; one probe per TTL', async () => {
    vi.useFakeTimers({ toFake: ['performance'] })
    try {
      vi.advanceTimersByTime(60_000) // a start that did not stamp its own check would now read stale
      const { mgr, health, probes } = await livenessHarness()
      await mgr.refreshHealth()
      expect(probes.count).toBe(0) // inside the TTL of the start's own check: nothing probed
      vi.advanceTimersByTime(9_999)
      await mgr.refreshHealth()
      expect(probes.count).toBe(0) // still inside HEALTH_PROBE_TTL_MS (10 s, architecture.md #599)
      vi.advanceTimersByTime(1)
      health.healthy = false // frozen: the probe fails
      await Promise.all([mgr.refreshHealth(), mgr.refreshHealth()])
      expect(probes.count).toBe(1) // concurrent reads share one probe
      expect(mgr.status()).toMatchObject({ healthy: false, unresponsive: true })
      health.healthy = true // resumed
      vi.advanceTimersByTime(10_000)
      await mgr.refreshHealth()
      expect(probes.count).toBe(2)
      expect(mgr.status().unresponsive).toBeUndefined()
    } finally {
      vi.useRealTimers()
    }
  })

  it('Restart starts the same model again with its own options and ends its answers as a switch (#600)', async () => {
    const { mgr, started, order, startOpts } = await livenessHarness()
    expect(await mgr.restartCurrent()).toMatchObject({ running: true, modelId: 'm' })
    expect(started).toEqual([startOpts, startOpts])
    expect(order).toEqual(['hook switch', 'kill m'])
  })

  it('Restart with no model running does nothing', async () => {
    const { mgr, started } = await livenessHarness()
    await mgr.stop()
    expect(await mgr.restartCurrent()).toBeNull()
    expect(started).toHaveLength(1)
  })

  it('a crashed model the app will not restart is stopped without the model-stop hook; a live runtime is left alone', async () => {
    const { mgr, order, health } = await livenessHarness()
    await mgr.stopCrashed('m') // a late or duplicate report: the runtime of m now answers — keep it
    expect(mgr.status().running).toBe(true)
    health.healthy = false // the process is gone
    await mgr.stopCrashed('another')
    expect(mgr.status().running).toBe(true)
    await mgr.stopCrashed('m')
    expect(mgr.status().running).toBe(false)
    expect(order).toEqual(['kill m'])
  })

  it('Restart while a start is in flight joins it instead of loading the model again', async () => {
    let release!: () => void
    const parked = new Promise<void>((r) => (release = r))
    const slow = new RuntimeManager((o) => ({
      modelId: o.modelId,
      start: () => (o.modelId === 'b' ? parked : Promise.resolve()),
      stop: async () => {},
      health: async () => ({ healthy: true, message: '', port: 1 }),
      // eslint-disable-next-line require-yield
      chatStream: async function* (): AsyncGenerator<string, void, unknown> {}
    }))
    await slow.start({ modelId: 'a', modelPath: '/a.gguf', contextTokens: 2048 })
    const switching = slow.start({ modelId: 'b', modelPath: '/b.gguf', contextTokens: 2048 })
    const restart = slow.restartCurrent() // the user's Restart on a's card, mid-switch
    release()
    await switching
    expect(await restart).toMatchObject({ running: true, modelId: 'b' }) // the switch stands
  })

  it('a crash restart queued behind a start of the same model keeps its "starting" window', async () => {
    let release!: () => void
    const parked = new Promise<void>((r) => (release = r))
    let calls = 0
    const mgr = new RuntimeManager((o) => {
      calls++
      const first = calls === 1
      return {
        modelId: o.modelId,
        start: () => (first ? Promise.resolve() : parked),
        stop: async () => {},
        health: async () => ({ healthy: true, message: '', port: 1 }),
        // eslint-disable-next-line require-yield
        chatStream: async function* (): AsyncGenerator<string, void, unknown> {}
      }
    })
    const opts = { modelId: 'm', modelPath: '/m.gguf', contextTokens: 2048 }
    const starting = mgr.start(opts)
    const restart = mgr.forceRestart(opts) // the crash during the start's warm-up
    await starting
    expect(mgr.status().startingModelId).toBe('m') // the restart is still loading
    release()
    await restart
    expect(mgr.status().startingModelId ?? null).toBeNull()
  })

  it('a start request counts as starting before the load begins, until it is released', async () => {
    const { mgr } = await livenessHarness()
    await mgr.stop()
    expect(mgr.isStarting()).toBe(false)
    const release = mgr.beginStartRequest()
    expect(mgr.isStarting()).toBe(true)
    expect(mgr.status()).toMatchObject({ running: false, startRequested: true })
    release()
    release() // idempotent: the next request still counts
    expect(mgr.isStarting()).toBe(false)
    expect(mgr.status().startRequested).toBeUndefined()
    const next = mgr.beginStartRequest()
    expect(mgr.isStarting()).toBe(true)
    next()
  })

  it('a /health probe that outlives a model switch is discarded — it never marks the new model (#599)', async () => {
    vi.useFakeTimers({ toFake: ['performance'] })
    try {
      let parkA = false
      let probedA = false
      let answerA: (healthy: boolean) => void = () => undefined
      const mgr = new RuntimeManager((o) => ({
        modelId: o.modelId,
        start: async () => {},
        stop: async () => {},
        health: () =>
          o.modelId === 'a' && parkA
            ? new Promise<HealthStatus>((r) => {
                probedA = true
                answerA = (healthy) => r({ healthy, message: '', port: 1 })
              })
            : Promise.resolve({ healthy: true, message: '', port: 1 }),
        // eslint-disable-next-line require-yield
        chatStream: async function* (): AsyncGenerator<string, void, unknown> {}
      }))
      await mgr.start({ modelId: 'a', modelPath: '/a.gguf', contextTokens: 2048 })
      parkA = true // a freezes: its next /health answers only when the test says so
      vi.advanceTimersByTime(10_000) // past the 10 s probe TTL
      const probe = mgr.refreshHealth()
      expect(probedA).toBe(true) // the probe really went out to a (not skipped inside the TTL)
      await mgr.start({ modelId: 'b', modelPath: '/b.gguf', contextTokens: 2048 }) // the switch lands meanwhile
      answerA(false) // a's late verdict
      await probe
      expect(mgr.status()).toMatchObject({ running: true, modelId: 'b', healthy: true })
      expect(mgr.status().unresponsive).toBeUndefined()
    } finally {
      vi.useRealTimers()
    }
  })
})

// #473 ruling 2: every chat start awaits `beforeStart` after the old runtime stopped and before the
// factory spawns, while the start is visible as starting — the composition takes a translation
// sidecar off the graphics card there, because a chat model that starts second stays squeezed.
describe('the beforeStart hook (#473)', () => {
  function hookHarness(beforeStart: (mgr: RuntimeManager) => Promise<void>) {
    const order: string[] = []
    const mgr: RuntimeManager = new RuntimeManager(
      (opts) => {
        order.push(`spawn ${opts.modelId}`)
        return {
          modelId: opts.modelId,
          start: async () => {},
          stop: async () => {
            order.push(`kill ${opts.modelId}`)
          },
          health: async () => ({ healthy: true, message: '', port: null }),
          // eslint-disable-next-line require-yield
          chatStream: async function* (): AsyncGenerator<string, void, unknown> {}
        }
      },
      { beforeStart: () => beforeStart(mgr) }
    )
    return { mgr, order }
  }
  const A: RuntimeStartOptions = { modelId: 'a', modelPath: '/a.gguf', contextTokens: 2048 }
  const B: RuntimeStartOptions = { modelId: 'b', modelPath: '/b.gguf', contextTokens: 2048 }

  it.each([
    ['a switch (start)', (mgr: RuntimeManager) => mgr.start(B)],
    ['a Restart or crash restart (forceRestart)', (mgr: RuntimeManager) => mgr.forceRestart(B)]
  ])('%s: the old model stops, then the hook runs with the start visible, then the spawn', async (_label, go) => {
    const { mgr, order } = hookHarness(async (m) => {
      order.push(`hook, starting: ${m.status().startingModelId ?? 'none'}`)
    })
    await mgr.start(A)
    order.length = 0
    await go(mgr)
    expect(order).toEqual(['kill a', 'hook, starting: b', 'spawn b'])
  })

  it('a quit during the hook spawns nothing', async () => {
    const { mgr, order } = hookHarness(async (m) => {
      m.shutdown()
    })
    await expect(mgr.start(A)).rejects.toThrow()
    expect(order).toEqual([])
  })

  it('a Stop or a lock during the hook cancels the start before it spawns — never a whole load first', async () => {
    // Until the factory runs, `stop()` has no starting runtime to cancel; without this, a lock that
    // arrived during the hook (or the old model's stop) waited out a full load of the new model.
    let stopped: Promise<void> | null = null
    const { mgr, order } = hookHarness(async (m) => {
      stopped = m.stop() // queued behind this start, so not awaited here
    })
    await expect(mgr.start(A)).rejects.toThrow(/stopped before it began/)
    await stopped
    expect(order).toEqual([])
    expect(mgr.active()).toBeNull()
  })
})