Skip to content

AI, fully local on your computer.

29.8 KB
Raw Blame
import { describe, it, expect, afterEach, vi } from 'vitest'
import { EventEmitter } from 'node:events'
import { createServer } from 'node:http'
import type { AddressInfo } from 'node:net'
import {
  CHAT_SERVER_ARGS,
  ChatRequestError,
  DEEP_TEMPERATURE,
  FAST_MAX_TOKENS,
  FAST_TEMPERATURE,
  isExceedContextError,
  isRuntimeConnectionLostError,
  isRuntimeUnresponsiveError,
  LlamaRuntime,
  requestParamsForMode
} from '../../src/main/services/runtime/llama'
import { sseFrames } from '../helpers/fake-sidecar'
import { within } from '../helpers/hang-budget'
import type { ChildProcessLike } from '../../src/main/services/runtime/sidecar'
import type { RuntimeStartOptions } from '../../src/main/services/runtime'

class FakeChild extends EventEmitter implements ChildProcessLike {
  pid = 7
  killed = false
  kill(): boolean {
    this.killed = true
    queueMicrotask(() => this.emit('exit', 0, null))
    return true
  }
}

// Fixture provenance (CODE-9/TQ-6, full-audit 2026-07-11): the SSE frames throughout this file are
// hand-authored to the llama-server output shape — content/reasoning_content deltas,
// `finish_reason` (stop/length), and `[DONE]`; no captured file is read here. The content + `stop`
// shape matches the real captures on the current pin b11146 (`chat-sse-timings-b11146.txt`, #512); the
// reasoning and `length` shapes have no capture. CI green does NOT evidence the real wire contract
// (see BUILD_STATE §5 TS-3 inventory); re-verify against a captured smoke transcript on a runtime pin bump.
function chatChunk(content: string): string {
  return `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n\n`
}

/** A `--reasoning-format deepseek` thinking delta (Phase 20 Deep mode). */
function reasoningChunk(reasoning_content: string): string {
  return `data: ${JSON.stringify({ choices: [{ delta: { reasoning_content } }] })}\n\n`
}

/** A fetch stub that routes /health (ok) and /v1/chat/completions (an SSE body). */
function chatFetch(opts: {
  frames: string[]
  onChat?: (url: string, init?: RequestInit) => void
  chatOk?: boolean
}): typeof fetch {
  return (async (url: string | URL, init?: RequestInit) => {
    const u = String(url)
    if (u.endsWith('/health')) return { ok: true, status: 200 } as Response
    if (u.endsWith('/v1/chat/completions')) {
      opts.onChat?.(u, init)
      if (opts.chatOk === false) return { ok: false, status: 500, body: null } as unknown as Response
      return { ok: true, status: 200, body: sseFrames(opts.frames) } as unknown as Response
    }
    throw new Error(`unexpected url ${u}`)
  }) as typeof fetch
}

function fakeSpawn() {
  const calls: Array<{ command: string; args: string[] }> = []
  const child = new FakeChild()
  const spawn = (command: string, args: string[]): ChildProcessLike => {
    calls.push({ command, args })
    return child
  }
  return { spawn, calls, child }
}

describe('LlamaRuntime', () => {
  const startOpts: RuntimeStartOptions = {
    modelId: 'qwen3-4b-instruct-q4',
    modelPath: '/models/x.gguf',
    contextTokens: 4096
  }

  it('starts the loopback sidecar and streams tokens from /v1/chat/completions', async () => {
    const { spawn, calls } = fakeSpawn()
    let chatUrl = ''
    let chatBody: unknown
    const fetchImpl = chatFetch({
      frames: [chatChunk('Privacy'), chatChunk(' first'), 'data: [DONE]\n\n'],
      onChat: (url, init) => {
        chatUrl = url
        chatBody = JSON.parse(String(init?.body))
      }
    })
    const runtime = new LlamaRuntime(startOpts, {
      binPath: '/bin/llama-server',
      spawn,
      fetchImpl,
      findPort: async () => 51000,
      healthIntervalMs: 1
    })
    await runtime.start()

    const out: string[] = []
    for await (const t of runtime.chatStream([{ role: 'user', content: 'hi' }], { maxTokens: 32 }))
      out.push(t)
    expect(out.join('')).toBe('Privacy first')

    // Localhost-only: the spawn binds 127.0.0.1 and the chat request targets loopback.
    expect(calls[0].args.join(' ')).toContain('--host 127.0.0.1')
    expect(calls[0].args.join(' ')).not.toContain('0.0.0.0')
    expect(chatUrl).toBe('http://127.0.0.1:51000/v1/chat/completions')
    // Messages are sent as plain role/content (server applies the chat template);
    // options map to the OpenAI request fields.
    expect(chatBody).toMatchObject({
      stream: true,
      max_tokens: 32,
      messages: [{ role: 'user', content: 'hi' }]
    })

    const h = await runtime.health()
    expect(h.healthy).toBe(true)
    expect(h.port).toBe(51000)
    await runtime.stop()
  })

  it('forwards the server timings through RuntimeChatOptions.onFinish end-to-end (#290/#291)', async () => {
    const { spawn } = fakeSpawn()
    const timings = { prompt_n: 5, prompt_ms: 40, predicted_n: 2, predicted_ms: 50, predicted_per_second: 40, prompt_per_second: 125 }
    const runtime = new LlamaRuntime(startOpts, {
      binPath: '/bin/llama-server',
      spawn,
      fetchImpl: chatFetch({
        frames: [
          chatChunk('Privacy'),
          chatChunk(' first'),
          `data: ${JSON.stringify({ choices: [{ delta: {}, finish_reason: 'stop' }], timings })}\n\n`,
          'data: [DONE]\n\n'
        ]
      }),
      findPort: async () => 51001,
      healthIntervalMs: 1
    })
    await runtime.start()
    const finishes: Array<[string, unknown]> = []
    const out: string[] = []
    for await (const t of runtime.chatStream([{ role: 'user', content: 'hi' }], {
      onFinish: (reason, tm) => finishes.push([reason, tm])
    })) {
      out.push(t)
    }
    expect(out.join('')).toBe('Privacy first')
    expect(finishes).toEqual([['stop', timings]])
    await runtime.stop()
  })

  it('sets --batch-size/--ubatch-size to min(ctx, 2048) on the chat sidecar (RT-1 prefill)', async () => {
    // Without these flags llama-server defaults the physical batch to 512, chunking prompt
    // prefill — the dominant time-to-first-token cost. The reranker raises its batch the same
    // way for the same reason (reranker.test.ts asserts --batch-size 2048). ctx 4096 caps at 2048.
    const { spawn, calls } = fakeSpawn()
    const runtime = new LlamaRuntime(startOpts, {
      binPath: '/bin/llama-server',
      spawn,
      fetchImpl: chatFetch({ frames: ['data: [DONE]\n\n'] }),
      findPort: async () => 51020,
      healthIntervalMs: 1
    })
    await runtime.start()
    const joined = calls[0].args.join(' ')
    expect(joined).toContain('--batch-size 2048')
    expect(joined).toContain('--ubatch-size 2048')
    await runtime.stop()

    // A context BELOW the cap sizes the batch to the context (it is min(ctx, 2048), not a fixed
    // 2048 — the whole prompt can't exceed n_ctx, so a larger physical batch would be wasted).
    const { spawn: spawn2, calls: calls2 } = fakeSpawn()
    const small = new LlamaRuntime(
      { ...startOpts, contextTokens: 1024 },
      {
        binPath: '/bin/llama-server',
        spawn: spawn2,
        fetchImpl: chatFetch({ frames: ['data: [DONE]\n\n'] }),
        findPort: async () => 51021,
        healthIntervalMs: 1
      }
    )
    await small.start()
    const joined2 = calls2[0].args.join(' ')
    expect(joined2).toContain('--batch-size 1024')
    expect(joined2).toContain('--ubatch-size 1024')
    await small.stop()
  })

  it('throws when the chat request fails (non-ok HTTP)', async () => {
    const { spawn } = fakeSpawn()
    const runtime = new LlamaRuntime(startOpts, {
      binPath: '/bin/s',
      spawn,
      fetchImpl: chatFetch({ frames: [], chatOk: false }),
      findPort: async () => 51001,
      healthIntervalMs: 1
    })
    await runtime.start()
    await expect(async () => {
      for await (const _t of runtime.chatStream([{ role: 'user', content: 'hi' }])) void _t
    }).rejects.toThrow(/HTTP 500/)
    await runtime.stop()
  })

  it('surfaces the server error body and flags an exceed-context HTTP 400', async () => {
    const { spawn } = fakeSpawn()
    const errorJson = JSON.stringify({
      error: {
        message: 'request (6006 tokens) exceeds the available context size (4096 tokens)',
        type: 'exceed_context_size_error'
      }
    })
    const fetchImpl = (async (url: string | URL) => {
      const u = String(url)
      if (u.endsWith('/health')) return { ok: true, status: 200 } as Response
      return {
        ok: false,
        status: 400,
        text: async () => errorJson
      } as unknown as Response
    }) as typeof fetch
    const runtime = new LlamaRuntime(startOpts, {
      binPath: '/bin/s',
      spawn,
      fetchImpl,
      findPort: async () => 51010,
      healthIntervalMs: 1
    })
    await runtime.start()
    let caught: unknown
    try {
      for await (const _t of runtime.chatStream([{ role: 'user', content: 'hi' }])) void _t
    } catch (err) {
      caught = err
    }
    expect(caught).toBeInstanceOf(ChatRequestError)
    expect((caught as Error).message).toMatch(/HTTP 400/)
    // The server's REASON is now part of the error (it used to be discarded).
    expect((caught as Error).message).toMatch(/exceeds the available context size/)
    expect(isExceedContextError(caught)).toBe(true)
    await runtime.stop()
  })

  it('isExceedContextError is false for ordinary errors and non-context HTTP failures', () => {
    expect(isExceedContextError(new Error('boom'))).toBe(false)
    expect(isExceedContextError(new ChatRequestError(503, 'service unavailable', ''))).toBe(false)
  })
})

// ---- #594: the wait for the response headers ----------------------------------------------------------------------------
//
// CB-5's watchdog lived in `readChatSSE`, i.e. it started once `res.body` existed. A sidecar that took the request and
// never answered it (seen 2026-10-05: b9849 Vulkan on a GTX 1070 Ti, 0 % CPU, /health silent too) left the turn waiting
// until undici's own 300 s headers timeout ended it as a raw "fetch failed". Both pinned builds send the headers when the
// slot starts, BEFORE prefill (measured on b11146: 14 ms), so the wait is queueing for the one slot; #598 gave it the
// owner's 180 s (it was CB-5's 120 s first-output budget, which a re-ask behind a cancelled request's batch outlasted).

/** A loopback llama-server that answers /health and takes the chat request without ever writing its headers. */
async function silentSidecar(): Promise<{
  port: number
  chatReached: Promise<void>
  chatClosed: Promise<void>
  close: () => Promise<void>
}> {
  let reached!: () => void
  let closed!: () => void
  const chatReached = new Promise<void>((r) => (reached = r))
  const chatClosed = new Promise<void>((r) => (closed = r))
  const server = createServer((req, res) => {
    if (req.url === '/health') {
      res.writeHead(200, { 'content-type': 'application/json', connection: 'close' })
      res.end('{"status":"ok"}')
      return
    }
    res.on('close', closed) // the client tore the connection down — llama-server then frees its slot
    req.resume()
    req.on('end', reached) // body read; no writeHead, ever
  })
  await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))
  return {
    port: (server.address() as AddressInfo).port,
    chatReached,
    chatClosed,
    close: () => {
      server.closeAllConnections()
      return new Promise<void>((r) => server.close(() => r()))
    }
  }
}

describe('LlamaRuntime — the wait for the response headers (#594)', () => {
  const startOpts: RuntimeStartOptions = { modelId: 'qwen3-4b-instruct-q4', modelPath: '/models/x.gguf', contextTokens: 4096 }
  const ask = [{ role: 'user' as const, content: 'hi' }]

  afterEach(() => {
    vi.useRealTimers()
  })

  it('no headers ⇒ RuntimeUnresponsiveError at exactly the 180 s budget (#598), and the connection is closed', async () => {
    const sidecar = await silentSidecar()
    const runtime = new LlamaRuntime(startOpts, {
      binPath: '/bin/llama-server',
      spawn: fakeSpawn().spawn,
      findPort: async () => sidecar.port,
      healthIntervalMs: 1
    })
    await runtime.start() // real fetch, real socket
    vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
    let outcome: unknown = 'pending'
    const first = runtime
      .chatStream(ask)
      .next()
      .then(
        () => (outcome = 'answered'),
        (e: unknown) => (outcome = e)
      )
    await within(sidecar.chatReached, 'the chat request reaching the sidecar')
    await vi.advanceTimersByTimeAsync(179_999)
    expect(outcome).toBe('pending')
    await vi.advanceTimersByTimeAsync(1)
    await within(first, 'the header deadline firing')
    expect(isRuntimeUnresponsiveError(outcome)).toBe(true) // CB-5's error ⇒ main.chat.runtimeUnresponsive / 502
    expect((outcome as Error).message).toContain('no response headers for 180000ms')
    await within(sidecar.chatClosed, 'the request connection closing')
    vi.useRealTimers()
    await runtime.stop()
    await sidecar.close()
  })

  it('a user Stop during the header wait is a clean stop, not RuntimeUnresponsiveError', async () => {
    const sidecar = await silentSidecar()
    const runtime = new LlamaRuntime(startOpts, {
      binPath: '/bin/llama-server',
      spawn: fakeSpawn().spawn,
      findPort: async () => sidecar.port,
      healthIntervalMs: 1
    })
    await runtime.start()
    const stop = new AbortController()
    const first = runtime.chatStream(ask, { signal: stop.signal }).next()
    await within(sidecar.chatReached, 'the chat request reaching the sidecar')
    stop.abort()
    const err = await within(first.then(() => null, (e: unknown) => e), 'the Stop ending the request')
    expect((err as Error).name).toBe('AbortError') // what isAbortError / withChatStream treat as a Stop
    expect(isRuntimeUnresponsiveError(err)).toBe(false)
    await within(sidecar.chatClosed, 'the request connection closing')
    await runtime.stop()
    await sidecar.close()
  })

  it('the deadline ends when the headers arrive: a b11146 CPU prefill (a ping every 30 s, first token at 320.9 s) answers', async () => {
    // Replays the 2026-10-05 capture's timing. The body errors when the request is aborted, as a fetch body does — so a
    // header deadline still armed at 180 s would cut this stream. That capture predates `return_progress`, so it has no
    // progress events and the pings alone carry it (readChatSSE's no-progress rule, #598).
    let sse!: ReadableStreamDefaultController<Uint8Array>
    const enc = new TextEncoder()
    const fetchImpl = (async (url: string | URL, init?: RequestInit) => {
      if (String(url).endsWith('/health')) return { ok: true, status: 200 } as Response
      const body = new ReadableStream<Uint8Array>({
        start(c) {
          sse = c
        }
      })
      init?.signal?.addEventListener('abort', () => sse.error(init.signal!.reason), { once: true })
      return { ok: true, status: 200, body } as unknown as Response
    }) as typeof fetch
    const runtime = new LlamaRuntime(startOpts, {
      binPath: '/bin/llama-server',
      spawn: fakeSpawn().spawn,
      fetchImpl,
      findPort: async () => 51020,
      healthIntervalMs: 1
    })
    await runtime.start()
    vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] }) // the watchdog's quiet time reads it
    const out: string[] = []
    const run = (async () => {
      for await (const t of runtime.chatStream(ask)) out.push(t)
    })()
    for (let t = 30_000; t <= 300_000; t += 30_000) {
      await vi.advanceTimersByTimeAsync(30_000)
      sse.enqueue(enc.encode(':\n\n'))
    }
    await vi.advanceTimersByTimeAsync(20_900)
    sse.enqueue(enc.encode(chatChunk('Answer') + 'data: [DONE]\n\n'))
    await within(run, 'the answer finishing')
    expect(out).toEqual(['Answer'])
    vi.useRealTimers()
    await runtime.stop()
  })
})

// ---- #600: a sidecar that dies under a request --------------------------------------------------------------------------
//
// A crash or an OS kill of llama-server mid-request used to reach the chat as undici's bare TypeError — "fetch failed" before
// the headers, "terminated" once the body streamed — shown to the user as that raw text. Measured in Electron 43.7.7 by
// killing a b11146 server at each phase (all within 3 ms of the kill). The runtime now throws `RuntimeConnectionLostError`,
// which the chat maps to `main.chat.connectionLost`. Real loopback socket, real fetch: the shapes come from undici itself.

/** A loopback llama-server that answers /health and then loses the chat request's socket in the given phase. */
async function dyingSidecar(phase: 'before-headers' | 'mid-stream'): Promise<{
  port: number
  close: () => Promise<void>
}> {
  const server = createServer((req, res) => {
    if (req.url === '/health') {
      res.writeHead(200, { 'content-type': 'application/json', connection: 'close' })
      res.end('{"status":"ok"}')
      return
    }
    req.resume()
    req.on('end', () => {
      if (phase === 'mid-stream') {
        res.writeHead(200, { 'content-type': 'text/event-stream' })
        res.write(chatChunk('Lighthouses'))
        // Let the first chunk reach the reader, then the process "dies".
        setImmediate(() => res.socket?.destroy())
      } else {
        req.socket.destroy()
      }
    })
  })
  await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))
  return {
    port: (server.address() as AddressInfo).port,
    close: () => {
      server.closeAllConnections()
      return new Promise<void>((r) => server.close(() => r()))
    }
  }
}

describe('LlamaRuntime — a sidecar that dies under the request (#600)', () => {
  const startOpts: RuntimeStartOptions = { modelId: 'qwen3-4b-instruct-q4', modelPath: '/models/x.gguf', contextTokens: 4096 }
  const ask = [{ role: 'user' as const, content: 'hi' }]

  async function runAgainst(port: number, signal?: AbortSignal): Promise<{ out: string[]; err: unknown }> {
    const runtime = new LlamaRuntime(startOpts, {
      binPath: '/bin/llama-server',
      spawn: fakeSpawn().spawn,
      findPort: async () => port,
      healthIntervalMs: 1
    })
    await runtime.start()
    const out: string[] = []
    let err: unknown = null
    try {
      for await (const t of runtime.chatStream(ask, { signal })) out.push(t)
    } catch (e) {
      err = e
    }
    await runtime.stop()
    return { out, err }
  }

  it.each([['before-headers' as const], ['mid-stream' as const]])(
    'the socket closes %s ⇒ RuntimeConnectionLostError, never the raw undici TypeError',
    async (phase) => {
      const sidecar = await dyingSidecar(phase)
      const { out, err } = await runAgainst(sidecar.port)
      expect(isRuntimeConnectionLostError(err)).toBe(true)
      // The log line keeps undici's reason and socket code — the only trace of why the sidecar went.
      expect((err as Error).message).toMatch(/\((terminated|fetch failed): [A-Z_]+\)\.$/)
      expect(out).toEqual(phase === 'mid-stream' ? ['Lighthouses'] : [])
      await sidecar.close()
    }
  )

  it('a request to a sidecar that is already gone (connection refused) ⇒ RuntimeConnectionLostError', async () => {
    const sidecar = await dyingSidecar('before-headers')
    const runtime = new LlamaRuntime(startOpts, {
      binPath: '/bin/llama-server',
      spawn: fakeSpawn().spawn,
      findPort: async () => sidecar.port,
      healthIntervalMs: 1
    })
    await runtime.start()
    await sidecar.close() // the process died after its health check — nothing listens on the port now
    let err: unknown = null
    try {
      for await (const _t of runtime.chatStream(ask)) void _t
    } catch (e) {
      err = e
    }
    expect(isRuntimeConnectionLostError(err)).toBe(true)
    expect((err as Error).message).toContain('(fetch failed: ECONNREFUSED)')
    await runtime.stop()
  })

  it('a Stop that landed first stays a Stop, not a lost connection', async () => {
    const sidecar = await dyingSidecar('before-headers')
    const stop = new AbortController()
    stop.abort()
    const { err } = await runAgainst(sidecar.port, stop.signal)
    expect((err as Error).name).toBe('AbortError')
    expect(isRuntimeConnectionLostError(err)).toBe(false)
    await sidecar.close()
  })
})

// ---- Answer-depth modes (Phase 20, wave-1 decisions D4+D5 — architecture.md "Chat & streaming") ---------------------------

describe('answer-depth mode → request mapping (D4)', () => {
  it('maps fast / balanced / deep / omitted per the locked D4 table', () => {
    expect(requestParamsForMode('fast')).toEqual({
      enableThinking: false,
      temperature: FAST_TEMPERATURE,
      maxTokens: FAST_MAX_TOKENS
    })
    expect(requestParamsForMode('balanced')).toEqual({ enableThinking: false })
    expect(requestParamsForMode('deep')).toEqual({
      enableThinking: true,
      temperature: DEEP_TEMPERATURE
    })
    // Omitted = balanced: thinking must be EXPLICITLY off (the b9585 server default
    // is thinking ON for any capable template — omitting the kwarg would think).
    expect(requestParamsForMode(undefined)).toEqual({ enableThinking: false })
  })

  const startOpts: RuntimeStartOptions = {
    modelId: 'qwen3-4b-instruct-q4',
    modelPath: '/models/x.gguf',
    contextTokens: 4096
  }

  async function captureBody(opts?: Parameters<LlamaRuntime['chatStream']>[1]): Promise<{
    body: Record<string, unknown>
    args: string[]
  }> {
    const { spawn, calls } = fakeSpawn()
    let chatBody: Record<string, unknown> = {}
    const runtime = new LlamaRuntime(startOpts, {
      binPath: '/bin/llama-server',
      spawn,
      fetchImpl: chatFetch({
        frames: ['data: [DONE]\n\n'],
        onChat: (_url, init) => {
          chatBody = JSON.parse(String(init?.body)) as Record<string, unknown>
        }
      }),
      findPort: async () => 51002,
      healthIntervalMs: 1
    })
    await runtime.start()
    for await (const _t of runtime.chatStream([{ role: 'user', content: 'q' }], opts)) void _t
    await runtime.stop()
    return { body: chatBody, args: calls[0].args }
  }

  it('sends chat_template_kwargs.enable_thinking=false with NO sampling overrides when mode is omitted (balanced)', async () => {
    const { body, args } = await captureBody()
    expect(body.chat_template_kwargs).toEqual({ enable_thinking: false })
    expect(body).not.toHaveProperty('temperature')
    expect(body).not.toHaveProperty('max_tokens')
    // The D5 mechanism's preconditions are pinned in the spawn args: jinja templating
    // (kwargs only act there) + deepseek reasoning extraction (separate deltas).
    expect(args.join(' ')).toContain('--jinja')
    expect(args.join(' ')).toContain('--reasoning-format deepseek')
  })

  it('runs ONE server slot: -np 1, not b9849\'s four unified slots (issue #319)', async () => {
    const { args } = await captureBody()
    // Owner decision 2026-09-07. The app is single-user and already serialises every lane that
    // reaches this server (the model-slot arbiter; the local API's depth-one admission), so the
    // four default slots were never used in parallel while costing card memory exactly where the
    // fit decides between full and half speed: on the rig this turned the 27B Q5's 62/66 layers
    // at 30.4 tok/s into 66/66 at 51.0 (#318 leg 1, recurrent state 1,795.50 → 448.88 MiB).
    expect(args.join(' ')).toContain('-np 1')
    // What it does NOT change: the context window. `--ctx-size` is the TOTAL cache on both
    // settings and each slot still sees all of it (n_ctx_slot = 8192 either way), which is why
    // only the per-SEQUENCE recurrent term moved in the manifests' cache estimates.
    expect(args.join(' ')).toContain(`--ctx-size ${startOpts.contextTokens}`)
  })

  it('sends cache_prompt:true so the slot KV prefix is reused across turns (skill-fence prefill is one-time)', async () => {
    const { body } = await captureBody()
    expect(body.cache_prompt).toBe(true)
  })

  it('asks for prompt-progress events (return_progress), the only sign that a prefill advances (#598)', async () => {
    // Without them readChatSSE's compute clock never runs, and a wedged prefill is pinged alive forever.
    const { body } = await captureBody()
    expect(body.return_progress).toBe(true)
  })

  it('fast → thinking off + temperature 0.7 + modest max_tokens', async () => {
    const { body } = await captureBody({ mode: 'fast' })
    expect(body.chat_template_kwargs).toEqual({ enable_thinking: false })
    expect(body.temperature).toBe(FAST_TEMPERATURE)
    expect(body.max_tokens).toBe(FAST_MAX_TOKENS)
  })

  it('deep → thinking ON + the Qwen3 thinking-mode temperature, uncapped', async () => {
    const { body } = await captureBody({ mode: 'deep' })
    expect(body.chat_template_kwargs).toEqual({ enable_thinking: true })
    expect(body.temperature).toBe(DEEP_TEMPERATURE)
    expect(body).not.toHaveProperty('max_tokens')
  })

  it('explicit maxTokens/temperature win over the mode mapping', async () => {
    const { body } = await captureBody({ mode: 'fast', maxTokens: 64, temperature: 0.2 })
    expect(body.max_tokens).toBe(64)
    expect(body.temperature).toBe(0.2)
    expect(body.chat_template_kwargs).toEqual({ enable_thinking: false })
  })

  it('routes reasoning deltas to onReasoning and never into the yielded answer', async () => {
    const { spawn } = fakeSpawn()
    const runtime = new LlamaRuntime(startOpts, {
      binPath: '/bin/llama-server',
      spawn,
      fetchImpl: chatFetch({
        frames: [
          reasoningChunk('Let me'),
          reasoningChunk(' think.'),
          // A single chunk may carry BOTH keys (diffs batched into one delta).
          `data: ${JSON.stringify({ choices: [{ delta: { reasoning_content: ' Done.', content: 'The' } }] })}\n\n`,
          chatChunk(' answer.'),
          'data: [DONE]\n\n'
        ]
      }),
      findPort: async () => 51003,
      healthIntervalMs: 1
    })
    await runtime.start()
    const reasoning: string[] = []
    const out: string[] = []
    for await (const t of runtime.chatStream([{ role: 'user', content: 'q' }], {
      mode: 'deep',
      onReasoning: (d) => reasoning.push(d)
    })) {
      out.push(t)
    }
    expect(reasoning.join('')).toBe('Let me think. Done.')
    expect(out.join('')).toBe('The answer.')
    await runtime.stop()
  })

  it('CHAT_SERVER_ARGS precede ladder extraArgs (a rung can still force --device none)', async () => {
    const { spawn, calls } = fakeSpawn()
    const runtime = new LlamaRuntime(startOpts, {
      binPath: '/bin/llama-server',
      spawn,
      fetchImpl: chatFetch({ frames: ['data: [DONE]\n\n'] }),
      findPort: async () => 51004,
      healthIntervalMs: 1,
      extraArgs: ['--device', 'none']
    })
    await runtime.start()
    const joined = calls[0].args.join(' ')
    for (const a of CHAT_SERVER_ARGS) expect(calls[0].args).toContain(a)
    expect(joined).toContain('--device none')
    await runtime.stop()
  })

  // ---- #512: the prompt cache — RAM-scaled ceiling, manifest opt-out ----------------------
  //
  // CHAT_SERVER_ARGS is shared by EVERY chat model start on every machine. Since #512 each start
  // carries exactly one `--cache-ram`: min(8192, total RAM MiB / 8), or 0 when the manifest sets
  // `disable_prompt_cache: true` (the #399 family list is gone — see shared/prompt-cache-rules.ts).

  const GiB = 1024 ** 3
  const cacheRamOf = (args: string[]): string[] =>
    args.flatMap((a, i) => (a === '--cache-ram' ? [args[i + 1]] : []))

  it('passes a RAM-scaled --cache-ram to every chat model (#512 decision 2)', async () => {
    // The size table is prompt-cache-rules.test.ts's; this row pins the wiring — the runtime reads its RAM input and
    // spawns exactly one rule-derived flag. 12 GiB → 1536, a reading no real host is likely to report exactly.
    const { spawn, calls } = fakeSpawn()
    const runtime = new LlamaRuntime(startOpts, {
      binPath: '/bin/llama-server',
      spawn,
      fetchImpl: chatFetch({ frames: ['data: [DONE]\n\n'] }),
      findPort: async () => 51010,
      healthIntervalMs: 1,
      totalRamBytes: 12 * GiB
    })
    await runtime.start()
    expect(cacheRamOf(calls[0].args)).toEqual(['1536'])
    expect(calls[0].args).not.toContain('-cram')
    for (const a of CHAT_SERVER_ARGS) expect(calls[0].args).toContain(a)
    await runtime.stop()
  })

  it('disable_prompt_cache wins with --cache-ram 0 — still exactly one flag (#512 decision 1)', async () => {
    const { spawn, calls } = fakeSpawn()
    const runtime = new LlamaRuntime(
      { ...startOpts, disablePromptCache: true },
      {
        binPath: '/bin/llama-server',
        spawn,
        fetchImpl: chatFetch({ frames: ['data: [DONE]\n\n'] }),
        findPort: async () => 51011,
        healthIntervalMs: 1,
        totalRamBytes: 64 * GiB
      }
    )
    await runtime.start()
    expect(cacheRamOf(calls[0].args)).toEqual(['0'])
    await runtime.stop()
  })

  it('defaults the ceiling to the real machine RAM when no seam is given', async () => {
    const { totalmem } = await import('node:os')
    const { promptCacheRamMib } = await import('../../src/shared/prompt-cache-rules')
    const { spawn, calls } = fakeSpawn()
    const runtime = new LlamaRuntime(startOpts, {
      binPath: '/bin/llama-server',
      spawn,
      fetchImpl: chatFetch({ frames: ['data: [DONE]\n\n'] }),
      findPort: async () => 51013,
      healthIntervalMs: 1
    })
    await runtime.start()
    expect(cacheRamOf(calls[0].args)).toEqual([String(promptCacheRamMib(totalmem()))])
    await runtime.stop()
  })

  it('the prompt-cache flag never displaces a ladder rung arg (--device none still wins)', async () => {
    // The rung's extraArgs are appended AFTER the cache flag, so rung 2 can still force CPU — the
    // ladder contract is unchanged by #399 and #512.
    const { spawn, calls } = fakeSpawn()
    const runtime = new LlamaRuntime(
      { ...startOpts, disablePromptCache: true },
      {
        binPath: '/bin/llama-server',
        spawn,
        fetchImpl: chatFetch({ frames: ['data: [DONE]\n\n'] }),
        findPort: async () => 51012,
        healthIntervalMs: 1,
        extraArgs: ['--device', 'none']
      }
    )
    await runtime.start()
    const joined = calls[0].args.join(' ')
    expect(joined).toContain('--cache-ram 0')
    expect(joined).toContain('--device none')
    expect(joined.indexOf('--cache-ram')).toBeLessThan(joined.indexOf('--device none'))
    await runtime.stop()
  })
})