AI, fully local on your computer.
TypeScript aiai-toolskiwixllama-cpplocal-ailocal-llmofflineoffline-aioffline-firstprivacy-firstragwikipediazim
import { describe, it, expect, vi, afterEach } from 'vitest'
import { EventEmitter } from 'node:events'
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { tmpdir, type CpuInfo } from 'node:os'
import { dirname, join } from 'node:path'
import http from 'node:http'
import https from 'node:https'
import net from 'node:net'
import {
resolveLlamaServerPath,
resolveCpuFallbackServerPath,
llamaServerBinaryName,
llamaServerDir,
llamaOsDir,
defaultThreadCount,
failureSignature,
findFreePort,
guardChildStdio,
killRegisteredSidecarChildren,
LlamaServer,
LOOPBACK_HOST,
redactExactKey,
redactSidecarSecrets,
registeredSidecarPids,
registerSidecarChild,
unregisterSidecarChild,
type ChildProcessLike,
type UnexpectedExitInfo
} from '../../src/main/services/runtime/sidecar'
import { holdEngineSpawns } from '../../src/main/services/runtime/spawn-gate'
import { log } from '../../src/main/services/logging'
// A switchable core count for the defaultThreadCount rows; everything else in this file reads the
// real cpus() (the switch is null) — the benchmark.test.ts RAM-pin idiom.
const osState = vi.hoisted(() => ({ cpus: null as null | (() => CpuInfo[]) }))
vi.mock('node:os', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:os')>()
return { ...actual, cpus: () => (osState.cpus ? osState.cpus() : actual.cpus()) }
})
afterEach(() => vi.restoreAllMocks())
// ---- A fake child process: kill() resolves the LlamaServer exit wait. -----------
class FakeChild extends EventEmitter implements ChildProcessLike {
pid = 4242
killed = false
signals: Array<NodeJS.Signals | number | undefined> = []
kill(signal?: NodeJS.Signals | number): boolean {
this.signals.push(signal)
this.killed = true
queueMicrotask(() => this.emit('exit', 0, null))
return true
}
}
/** A spawn() stub that records its calls — INCLUDING the options (env!) — and returns a
* FakeChild. Recording options is load-bearing: the sidecar API key travels only in the
* child-scoped env, so a helper that drops the third argument cannot assert on it. */
function fakeSpawn() {
const calls: Array<{ command: string; args: string[]; options: { env?: Record<string, string | undefined> } }> = []
const child = new FakeChild()
const spawn = (
command: string,
args: string[],
options: { env?: Record<string, string | undefined> }
): ChildProcessLike => {
calls.push({ command, args, options })
return child
}
return { spawn, calls, child }
}
/** A health endpoint that becomes ready after `readyAfter` polls. Records each request's
* url AND init (additive — the API-key tests assert on injected headers). */
function healthFetch(readyAfter = 0) {
let polls = 0
const urls: string[] = []
const requests: Array<{ url: string; init?: RequestInit }> = []
const fetchImpl = (async (url: string | URL, init?: RequestInit) => {
urls.push(String(url))
requests.push({ url: String(url), init })
polls++
const ok = polls > readyAfter
return { ok, status: ok ? 200 : 503, json: async () => ({ status: ok ? 'ok' : 'loading' }) } as Response
}) as typeof fetch
return { fetchImpl, urls, requests }
}
// ---- Binary discovery -----------------------------------------------------------
describe('resolveLlamaServerPath', () => {
it('finds the platform binary under runtime/llama.cpp/<os>/', () => {
const root = mkdtempSync(join(tmpdir(), 'hilbertraum-bin-'))
const bin = join(root, 'runtime', 'llama.cpp', 'win', 'llama-server.exe')
mkdirSync(dirname(bin), { recursive: true })
writeFileSync(bin, 'x')
expect(resolveLlamaServerPath(root, 'win32', {})).toBe(bin)
})
it('returns null when the binary is absent', () => {
const root = mkdtempSync(join(tmpdir(), 'hilbertraum-bin-'))
expect(resolveLlamaServerPath(root, 'win32', {})).toBeNull()
})
it('honours the HILBERTRAUM_LLAMA_BIN override in DEV when it exists, else null', () => {
const dir = mkdtempSync(join(tmpdir(), 'hilbertraum-bin-'))
const explicit = join(dir, 'my-llama-server')
writeFileSync(explicit, 'x')
expect(
resolveLlamaServerPath('/nope', 'linux', { HILBERTRAUM_LLAMA_BIN: explicit }, { isDev: true })
).toBe(explicit)
expect(
resolveLlamaServerPath('/nope', 'linux', { HILBERTRAUM_LLAMA_BIN: join(dir, 'absent') }, { isDev: true })
).toBeNull()
})
it('IGNORES the HILBERTRAUM_LLAMA_BIN override in a packaged build (M-5)', () => {
// The override would spawn an arbitrary, unverified binary; a packaged build must
// resolve only from the on-drive location. With no drive binary present → null.
const dir = mkdtempSync(join(tmpdir(), 'hilbertraum-bin-'))
const explicit = join(dir, 'evil-llama-server')
writeFileSync(explicit, 'x')
// Default (no opts) and explicit isDev:false both ignore the override.
expect(resolveLlamaServerPath('/nope', 'linux', { HILBERTRAUM_LLAMA_BIN: explicit })).toBeNull()
expect(
resolveLlamaServerPath('/nope', 'linux', { HILBERTRAUM_LLAMA_BIN: explicit }, { isDev: false })
).toBeNull()
// Even with the override set, a packaged build still finds the legitimate on-drive
// binary (the override is simply ignored, not a hard failure).
const root = mkdtempSync(join(tmpdir(), 'hilbertraum-bin-'))
const driveDir = llamaServerDir(root, 'linux')
mkdirSync(driveDir, { recursive: true })
const driveBin = join(driveDir, llamaServerBinaryName('linux'))
writeFileSync(driveBin, 'x')
expect(resolveLlamaServerPath(root, 'linux', { HILBERTRAUM_LLAMA_BIN: explicit })).toBe(driveBin)
})
it('maps platforms to os dirs and exe names', () => {
expect(llamaOsDir('win32')).toBe('win')
expect(llamaOsDir('darwin')).toBe('mac')
expect(llamaOsDir('linux')).toBe('linux')
expect(llamaServerBinaryName('win32')).toBe('llama-server.exe')
expect(llamaServerBinaryName('linux')).toBe('llama-server')
})
})
describe('resolveCpuFallbackServerPath (Phase 15, ladder rung 3)', () => {
it('finds the safety-net binary under runtime/llama.cpp/<os>/cpu/', () => {
const root = mkdtempSync(join(tmpdir(), 'hilbertraum-cpubin-'))
const bin = join(root, 'runtime', 'llama.cpp', 'win', 'cpu', 'llama-server.exe')
mkdirSync(dirname(bin), { recursive: true })
writeFileSync(bin, 'x')
expect(resolveCpuFallbackServerPath(root, 'win32')).toBe(bin)
})
it('returns null when the drive ships no safety net (e.g. mac)', () => {
const root = mkdtempSync(join(tmpdir(), 'hilbertraum-cpubin-'))
expect(resolveCpuFallbackServerPath(root, 'darwin')).toBeNull()
})
})
describe('defaultThreadCount', () => {
afterEach(() => {
osState.cpus = null
})
const core = { model: 'x', speed: 0, times: { user: 0, nice: 0, sys: 0, idle: 0, irq: 0 } }
it.each<[string, () => CpuInfo[], number]>([
['8 logical cores', () => Array(8).fill(core), 4],
['1 logical core', () => [core], 1],
['no cores reported', () => [], 1],
[
'cpus() throws',
() => {
throw new Error('EPERM')
},
1
]
])('is half the logical cores and never below 1 (never --threads 0): %s', (_label, cpus, expected) => {
osState.cpus = cpus
expect(defaultThreadCount()).toBe(expected)
})
})
describe('findFreePort', () => {
it('returns a usable loopback port', async () => {
const listen = vi.spyOn(net.Server.prototype, 'listen')
const port = await findFreePort()
expect(listen).toHaveBeenCalledTimes(1)
expect(listen.mock.calls[0]).toContain(LOOPBACK_HOST) // the probe bind is loopback-only, never 0.0.0.0
listen.mockRestore()
expect(port).toBeGreaterThan(0)
expect(port).toBeLessThan(65536)
// No re-bind check: the port is released before anyone binds it again, the very REL-1 window
// LlamaServer retries, so a re-bind here would flake under parallel workers.
})
})
// ---- LlamaServer lifecycle ------------------------------------------------------
describe('LlamaServer', () => {
it('spawns bound to 127.0.0.1 ONLY (never 0.0.0.0 / a routable host)', async () => {
const { spawn, calls } = fakeSpawn()
const { fetchImpl } = healthFetch(0)
const server = new LlamaServer({
binPath: '/bin/llama-server',
modelPath: '/models/x.gguf',
contextTokens: 4096,
spawn,
fetchImpl,
findPort: async () => 51234,
healthIntervalMs: 1
})
await server.start()
const args = calls[0].args
const hostIdx = args.indexOf('--host')
expect(hostIdx).toBeGreaterThanOrEqual(0)
expect(args[hostIdx + 1]).toBe(LOOPBACK_HOST)
expect(args).toContain('127.0.0.1')
expect(args.join(' ')).not.toContain('0.0.0.0')
// ctx-size + model + port are forwarded.
expect(args).toContain('--model')
expect(args).toContain('/models/x.gguf')
expect(args).toContain('--ctx-size')
expect(args).toContain('4096')
expect(args).toContain('51234')
await server.stop()
})
it('reports healthy once /health returns ok, with the bound port', async () => {
const { spawn } = fakeSpawn()
const { fetchImpl, urls } = healthFetch(1) // not ready on the first poll
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => 50000,
healthIntervalMs: 1
})
await server.start()
const h = await server.health()
expect(h.healthy).toBe(true)
expect(h.port).toBe(50000)
// Every health probe goes to loopback only.
expect(urls.every((u) => u.startsWith('http://127.0.0.1:50000/'))).toBe(true)
await server.stop()
})
it('throws (does not hang) when the server never becomes healthy', async () => {
const { spawn, child } = fakeSpawn()
const fetchImpl = (async () => ({ ok: false, status: 503 }) as Response) as typeof fetch
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => 50001,
healthTimeoutMs: 40,
healthIntervalMs: 5
})
await expect(server.start()).rejects.toThrow(/did not become healthy/)
// The wedged child is killed during the failed start (no orphan).
expect(child.killed).toBe(true)
})
// REL-1: findFreePort closes its listener BEFORE the child binds, so a concurrent
// process / sibling sidecar (chat + embedder + reranker + vision start near-
// simultaneously) can steal the port in that TOCTOU window. A first child that exits
// "address already in use" is a transient port race, not a model/device fault — so the
// server retries ONCE on a fresh port instead of failing the start.
it('retries once on a port-bind race, then starts healthy on a fresh port (REL-1)', async () => {
const ports: number[] = []
const spawnedArgs: string[][] = []
const failing = new FakeChild() as FakeChild & { stderr: EventEmitter }
failing.stderr = new EventEmitter()
const healthy = new FakeChild()
let n = 0
const spawn = (_c: string, args: string[]): ChildProcessLike => {
spawnedArgs.push(args)
n++
if (n === 1) {
queueMicrotask(() => {
failing.stderr.emit('data', Buffer.from('error: bind: address already in use\n'))
failing.emit('exit', 1, null)
})
return failing
}
return healthy // the retry's child stays up and reports healthy
}
// Only the retry's child (on the fresh port 50101) ever answers /health — the first
// child died before it could bind, so its port never serves a healthy response.
const fetchImpl = (async (url: string | URL) => {
const ok = String(url).includes(':50101/')
return { ok, status: ok ? 200 : 503 } as Response
}) as typeof fetch
let portCall = 0
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => {
const p = 50100 + portCall++
ports.push(p)
return p
},
healthIntervalMs: 1
})
await server.start() // resolves: the retry on a fresh port succeeds
expect(spawnedArgs).toHaveLength(2) // first lost the race, second won
expect(ports).toEqual([50100, 50101]) // a FRESH free port was acquired for the retry
const h = await server.health()
expect(h.healthy).toBe(true)
expect(h.port).toBe(50101)
await server.stop()
})
it('does NOT retry a non-bind immediate exit — only port races are transient (REL-1)', async () => {
let n = 0
const spawn = (): ChildProcessLike => {
n++
const child = new FakeChild()
queueMicrotask(() => child.emit('exit', 1, null)) // generic crash, no bind stderr
return child
}
const fetchImpl = (async () => ({ ok: false, status: 503 }) as Response) as typeof fetch
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => 50200,
healthIntervalMs: 1
})
await expect(server.start()).rejects.toThrow(/exited before becoming healthy/)
expect(n).toBe(1) // no retry for a non-bind failure
})
it('retries a port-bind race only ONCE, then fails (bounded retry, REL-1)', async () => {
let n = 0
const spawn = (): ChildProcessLike => {
n++
const child = new FakeChild() as FakeChild & { stderr: EventEmitter }
child.stderr = new EventEmitter()
queueMicrotask(() => {
child.stderr.emit('data', Buffer.from('error: bind: address already in use\n'))
child.emit('exit', 1, null)
})
return child
}
const fetchImpl = (async () => ({ ok: false, status: 503 }) as Response) as typeof fetch
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => 50300,
healthIntervalMs: 1
})
// The error names the exit code AND the captured stderr tail (what "surfaces the stderr tail +
// exit code" asserted).
await expect(server.start()).rejects.toThrow(/\(code 1\) — last output: .*address already in use/)
expect(n).toBe(2) // one initial attempt + exactly one retry, then it gives up
})
it('kills the child on stop() so no orphan survives', async () => {
const { spawn, child } = fakeSpawn()
const { fetchImpl } = healthFetch(0)
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => 50003,
healthIntervalMs: 1
})
await server.start()
expect(child.killed).toBe(false)
await server.stop()
expect(child.killed).toBe(true)
expect(child.signals).toEqual([undefined]) // only the polite SIGTERM: a child that exits on it is never SIGKILLed (B1)
expect(server.port).toBeNull()
})
// REL-2 (audit 2026-06-28): `this.child` is assigned only after the pre-spawn verify + findPort
// resolve, so two overlapping start() calls both passed `if (this.child)` and both spawned — the
// first child orphaned. The single-flight latch shares one start and resolves both on health.
it('two concurrent start() calls spawn exactly one child (REL-2 single-flight)', async () => {
const { spawn, calls } = fakeSpawn()
const { fetchImpl } = healthFetch(0)
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => 50014,
healthIntervalMs: 1
})
await Promise.all([server.start(), server.start()])
expect(calls).toHaveLength(1)
expect((await server.health()).healthy).toBe(true)
await server.stop()
})
// #516 (architecture.md "In-app engine updates" §3): while an install replaces runtime/llama.cpp/<os>/,
// every llama-server spawn waits for the swap. spawn-gate.test.ts proves the gate; this proves the one
// spawn site all five llama sidecars share actually waits on it.
it('waits for an engine install to finish its swap before it spawns (#516 spawn gate)', async () => {
const { spawn, calls } = fakeSpawn()
const { fetchImpl } = healthFetch(0)
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => 50015,
healthIntervalMs: 1
})
const release = holdEngineSpawns('llama_cpp')
const starting = server.start()
try {
// One macrotask: every microtask the start could chain (verify, findPort, spawn) has run.
await new Promise((r) => setImmediate(r))
expect(calls).toHaveLength(0) // held: nothing spawned mid-swap
} finally {
release()
}
await starting
expect(calls).toHaveLength(1)
await server.stop()
})
// Phase 15 (§5.3): the mid-session crash hook — fires only for a healthy server
// dying on its own, never for start-time failures or a stop()-initiated exit.
it('fires onUnexpectedExit when a healthy server dies on its own', async () => {
const { spawn, child } = fakeSpawn()
const { fetchImpl } = healthFetch(0)
const exits: UnexpectedExitInfo[] = []
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
onUnexpectedExit: (info) => exits.push(info),
spawn,
fetchImpl,
findPort: async () => 50005,
healthIntervalMs: 1
})
await server.start()
child.emit('exit', 134, null) // driver crash mid-generation
expect(exits).toHaveLength(1)
expect(exits[0].exitCode).toBe(134)
})
// M-C1: a post-ready 'error' WITHOUT an 'exit' (process gone via ECHILD/EPIPE) is
// still a mid-session death — it must fire onUnexpectedExit so the GPU auto-fallback
// runs and stop() doesn't hang waiting on an 'exit' that never comes. #656: Node may still
// emit 'exit' after the 'error'; that is the same death and is not reported a second time.
it('fires onUnexpectedExit once when a healthy server emits "error", with or without a trailing "exit" (#656)', async () => {
const { spawn, child } = fakeSpawn()
const { fetchImpl } = healthFetch(0)
const exits: UnexpectedExitInfo[] = []
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
onUnexpectedExit: (info) => exits.push(info),
spawn,
fetchImpl,
findPort: async () => 50008,
healthIntervalMs: 1
})
await server.start()
child.emit('error', new Error('read ECHILD')) // dies without ever emitting 'exit'
expect(exits).toHaveLength(1)
child.emit('exit', 1, null) // …or Node delivers the exit afterwards
expect(exits).toHaveLength(1)
})
// #656: that once-per-death flag belongs to the SPAWN. A server restarted on the same instance
// reports its own death, and a late event from the previous child (the bind retry leaves one
// behind too) neither reports again nor uses up the new child's report.
it('reports each spawn’s death once: a restarted server reports its own; a stale event from the old child counts for nothing (#656)', async () => {
const children: FakeChild[] = []
const spawn = (): ChildProcessLike => {
const child = new FakeChild()
children.push(child)
return child
}
const { fetchImpl } = healthFetch(0)
const exits: UnexpectedExitInfo[] = []
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
onUnexpectedExit: (info) => exits.push(info),
spawn,
fetchImpl,
findPort: async () => 50013,
healthIntervalMs: 1
})
await server.start()
children[0].emit('exit', 134, null)
expect(exits).toHaveLength(1)
await server.stop()
await server.start() // the owner's restart, same instance
children[0].emit('error', new Error('write EPIPE')) // late, from the dead child
expect(exits).toHaveLength(1)
children[1].emit('exit', 139, null)
expect(exits.map((e) => e.exitCode)).toEqual([134, 139])
})
it('stop() resolves (does not hang) when the child only ever emits "error"', async () => {
// A child whose kill() emits 'error' rather than 'exit'.
class ErrorOnlyChild extends EventEmitter implements ChildProcessLike {
pid = 9
killed = false
kill(): boolean {
this.killed = true
queueMicrotask(() => this.emit('error', new Error('gone')))
return true
}
}
const child = new ErrorOnlyChild()
const spawn = (): ChildProcessLike => child
const { fetchImpl } = healthFetch(0)
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => 50009,
healthIntervalMs: 1,
killGraceMs: 10_000 // long: the test would time out if stop() waited on the grace timer
})
await server.start()
await server.stop() // resolves via the 'error' branch of the race, not the grace timeout
expect(child.killed).toBe(true)
})
// M-C2: when child.kill() THROWS, stop() must not bail early (which would leave an
// orphan holding VRAM + the port) — it still races exit/grace and escalates to SIGKILL.
it('stop() still escalates to SIGKILL when the polite kill() throws', async () => {
const signals: Array<NodeJS.Signals | number | undefined> = []
class ThrowOnFirstKillChild extends EventEmitter implements ChildProcessLike {
pid = 11
killed = false
kill(signal?: NodeJS.Signals | number): boolean {
signals.push(signal)
if (signals.length === 1) throw new Error('kill failed (EPERM)') // the polite SIGTERM throws
this.killed = true
return true
}
}
const child = new ThrowOnFirstKillChild()
const spawn = (): ChildProcessLike => child
const { fetchImpl } = healthFetch(0)
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => 50011,
healthIntervalMs: 1,
killGraceMs: 1 // child never exits → grace window elapses → SIGKILL escalation
})
await server.start()
await server.stop()
// First call (the throwing SIGTERM) did NOT short-circuit stop(): SIGKILL was still sent.
expect(signals[0]).toBeUndefined() // child.kill() with no arg = SIGTERM
expect(signals).toContain('SIGKILL')
})
// T1 (post-merge audit Phase 5): the SIGTERM-ignore → SIGKILL escalation must be teeth-tested
// at the UNIT tier. The file's `FakeChild.kill()` exits on ANY signal, so stop() always settles
// on the "exited" branch and never reaches the escalation — the one path the line-572 comment
// warns can be silently unwired (gating on `child.killed`, which is true the instant a signal is
// SENT, would skip the SIGKILL entirely and orphan a process that ignored SIGTERM). This child
// RECORDS each signal but only dies on SIGKILL — the LlamaServer mirror of the transcriber's
// `makeStubbornChild(['SIGKILL'])` (REL-2). Teeth-checked: reverting the line-576 gate from
// `this.exited` to `child.killed` drops the SIGKILL → `signals` stays `[undefined]` → this reds.
it('stop() escalates SIGTERM→SIGKILL when the child ignores the polite signal (T1/REL-2)', async () => {
const signals: Array<NodeJS.Signals | number | undefined> = []
class StubbornChild extends EventEmitter implements ChildProcessLike {
pid = 12
killed = false
kill(signal?: NodeJS.Signals | number): boolean {
signals.push(signal)
this.killed = true // real ChildProcess sets killed once a signal is SENT — even if ignored
if (signal === 'SIGKILL') queueMicrotask(() => this.emit('exit', null, 'SIGKILL'))
return true // the polite SIGTERM (no arg) is recorded but the child lives on
}
}
const child = new StubbornChild()
const spawn = (): ChildProcessLike => child
const { fetchImpl } = healthFetch(0)
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => 50012,
healthIntervalMs: 1,
killGraceMs: 1 // SIGTERM is ignored → the grace window elapses → SIGKILL escalation
})
await server.start()
await server.stop() // resolves only via the SIGKILL escalation, not the ignored SIGTERM
expect(signals).toEqual([undefined, 'SIGKILL']) // polite SIGTERM first, then forceful SIGKILL
expect(child.killed).toBe(true)
})
it('does NOT fire onUnexpectedExit for an exit during stop()', async () => {
const { spawn } = fakeSpawn()
const { fetchImpl } = healthFetch(0)
const exits: UnexpectedExitInfo[] = []
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
onUnexpectedExit: (info) => exits.push(info),
spawn,
fetchImpl,
findPort: async () => 50006,
healthIntervalMs: 1
})
await server.start()
await server.stop() // FakeChild.kill emits 'exit'
expect(exits).toHaveLength(0)
})
it('does NOT fire onUnexpectedExit for an exit BEFORE becoming healthy (start throws instead)', async () => {
const child = new FakeChild()
const spawn = (): ChildProcessLike => {
queueMicrotask(() => child.emit('exit', 1, null))
return child
}
const fetchImpl = (async () => ({ ok: false, status: 503 }) as Response) as typeof fetch
const exits: UnexpectedExitInfo[] = []
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
onUnexpectedExit: (info) => exits.push(info),
spawn,
fetchImpl,
findPort: async () => 50007,
healthIntervalMs: 1
})
await expect(server.start()).rejects.toThrow(/exited before becoming healthy/)
expect(exits).toHaveLength(0)
})
// CODE-11 (full-audit 2026-07-11): every LlamaServer child is registered in the module-level
// PID registry the moment it spawns and deregistered when it exits/errors — so the
// `uncaughtException` crash exit (which skips will-quit's awaited stops) can best-effort
// reap it before `process.exit(1)`. On Windows the children otherwise survive the parent.
it('registers the child PID on spawn and deregisters it on exit (CODE-11 crash reap)', async () => {
killRegisteredSidecarChildren(() => undefined) // isolate: clear any leftover registrations
const { spawn, child } = fakeSpawn() // FakeChild pid 4242
const { fetchImpl } = healthFetch(0)
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => 50013,
healthIntervalMs: 1
})
expect(registeredSidecarPids()).not.toContain(4242)
await server.start()
expect(registeredSidecarPids()).toContain(4242) // reachable by the crash-exit reap
await server.stop() // FakeChild.kill emits 'exit' → deregistered
await new Promise((r) => setTimeout(r, 0))
expect(registeredSidecarPids()).not.toContain(4242)
})
it('makes ZERO non-loopback network calls during start/health/stop', async () => {
const httpSpy = vi.spyOn(http, 'request')
const httpsSpy = vi.spyOn(https, 'request')
const connectSpy = vi.spyOn(net, 'connect')
const socketConnectSpy = vi.spyOn(net.Socket.prototype, 'connect')
const { spawn } = fakeSpawn()
const { fetchImpl } = healthFetch(0)
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => 50004,
healthIntervalMs: 1
})
await server.start()
await server.health()
await server.stop()
// The injected fetch handles the (loopback) HTTP; no real sockets are opened.
expect(httpSpy).not.toHaveBeenCalled()
expect(httpsSpy).not.toHaveBeenCalled()
expect(connectSpy).not.toHaveBeenCalled()
expect(socketConnectSpy).not.toHaveBeenCalled()
})
})
// ---- Sidecar API key (D9): env-delivered, header-injected, stderr-redacted --------------
//
// The internal llama-server used to accept any same-machine request unauthenticated. Each
// spawn now generates a fresh key delivered ONLY via the child-scoped env (argv is visible
// in process lists, and llama-server echoes resolved params to stderr), injected as a
// Bearer header at the single fetch() chokepoint, and redacted from everything the
// captured stderr tail flows into (start-failure errors → gpuLastError → audit → log
// export). Verified against b9849: LLAMA_API_KEY enforces auth on every content-bearing route
// (only /health and /v1/models were exempt). On the b11146 pin (#512) only /health is: an
// unauthenticated /v1/models now answers 401. The app always sends the key, so nothing changes.
function makeServer(overrides: Partial<ConstructorParameters<typeof LlamaServer>[0]> = {}) {
const { spawn, calls, child } = fakeSpawn()
const { fetchImpl, requests } = healthFetch(0)
const server = new LlamaServer({
binPath: '/bin/llama-server',
modelPath: '/models/x.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => 51300,
healthIntervalMs: 1,
...overrides
})
return { server, calls, child, requests }
}
describe('LlamaServer sidecar API key (D9)', () => {
it('delivers a per-spawn hex key via the child-scoped env — never argv, never process.env', async () => {
const { server, calls } = makeServer()
await server.start()
expect(calls).toHaveLength(1)
const key = calls[0].options.env?.LLAMA_API_KEY
expect(key).toMatch(/^[0-9a-f]{64}$/) // 32 random bytes, hex (no argv-substring collisions)
// argv is clean: the key appears nowhere in the command line.
expect(calls[0].args.join(' ')).not.toContain(key!)
// The child env EXTENDS the parent env (PATH etc. must survive)…
expect(calls[0].options.env?.PATH ?? calls[0].options.env?.Path).toBeDefined()
// …but the parent's own env is never mutated (whisper/tar/GPU-probe would inherit it).
expect(process.env.LLAMA_API_KEY).toBeUndefined()
await server.stop()
})
it('keeps the host’s llama.cpp variables and config files out of the child (#730)', async () => {
const configVar = process.platform === 'win32' ? 'APPDATA' : 'XDG_CONFIG_HOME'
vi.stubEnv('LLAMA_ARG_RPC', 'host:50052')
vi.stubEnv(configVar, '/host/config')
try {
const { server, calls } = makeServer()
await server.start()
const env = calls[0].options.env!
expect(env.LLAMA_ARG_RPC).toBeUndefined()
expect(env[configVar]).not.toBe('/host/config')
expect(env.LLAMA_API_KEY).toMatch(/^[0-9a-f]{64}$/)
await server.stop()
} finally {
vi.unstubAllEnvs()
}
})
it('generates a FRESH key on every spawn (stop/start rotates it)', async () => {
const { server, calls } = makeServer()
await server.start()
const first = calls[0].options.env?.LLAMA_API_KEY
await server.stop()
await server.start()
const second = calls[1].options.env?.LLAMA_API_KEY
expect(second).toMatch(/^[0-9a-f]{64}$/)
expect(second).not.toBe(first)
await server.stop()
})
it('injects Authorization: Bearer <key> on EVERY fetch, including /health', async () => {
const { server, calls, requests } = makeServer()
await server.start()
await server.health()
const res = await server.fetch('/v1/chat/completions', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: '{}'
})
expect(res.ok).toBe(true)
await server.fetch('/tokenize', { headers: new Headers({ 'content-type': 'application/json' }) }) // a Headers INSTANCE must merge too
const key = calls[0].options.env?.LLAMA_API_KEY
expect(requests.length).toBeGreaterThanOrEqual(4) // start-health, health(), the two explicit fetches
for (const r of requests) {
const headers = new Headers(r.init?.headers)
expect(headers.get('authorization')).toBe(`Bearer ${key}`)
}
for (const path of ['/v1/chat/completions', '/tokenize']) {
const sent = requests.find((r) => r.url.endsWith(path))!
expect(new Headers(sent.init?.headers).get('content-type')).toBe('application/json') // the caller's headers survive, in both forms
}
await server.stop()
})
it('redacts a CHUNK-SPLIT key from a start-failure error — no fragment of it survives', async () => {
// The vacuous-assertion trap this replaces (review 2026-08-18): checking only for
// the full 64-char key passes while 44 chars of it leak. Assert both halves absent.
let spawnedKey: string | undefined
const child = new FakeChild() as FakeChild & { stderr: EventEmitter }
child.stderr = new EventEmitter()
const spawn = (
_c: string,
_args: string[],
options: { env?: Record<string, string | undefined> }
): ChildProcessLike => {
spawnedKey = options.env?.LLAMA_API_KEY
queueMicrotask(() => {
// A future pin echoing resolved params — the key split across TWO chunks.
child.stderr.emit('data', Buffer.from(`params: api_key = ${spawnedKey!.slice(0, 20)}`))
child.stderr.emit('data', Buffer.from(`${spawnedKey!.slice(20)}\nfatal: boom\n`))
child.emit('exit', 1, null)
})
return child
}
const fetchImpl = (async () => ({ ok: false, status: 503 }) as Response) as typeof fetch
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => 51301,
healthIntervalMs: 1
})
let message = ''
await server.start().catch((err: Error) => (message = err.message))
expect(message).toContain('exited before becoming healthy')
expect(message).toContain('fatal: boom') // the useful tail survives
expect(message).toContain('[redacted]')
expect(message).not.toContain(spawnedKey!)
expect(message).not.toContain(spawnedKey!.slice(0, 20)) // first half gone
expect(message).not.toContain(spawnedKey!.slice(20)) // second half gone too
})
it('never forwards any fragment of a chunk-split key to the onStderrData observer', async () => {
let spawnedKey: string | undefined
const forwarded: string[] = []
const child = new FakeChild() as FakeChild & { stderr: EventEmitter }
child.stderr = new EventEmitter()
const spawn = (
_c: string,
_args: string[],
options: { env?: Record<string, string | undefined> }
): ChildProcessLike => {
spawnedKey = options.env?.LLAMA_API_KEY
return child
}
const { fetchImpl } = healthFetch(0)
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
onStderrData: (text) => forwarded.push(text),
spawn,
fetchImpl,
findPort: async () => 51303,
healthIntervalMs: 1
})
await server.start()
child.stderr.emit('data', Buffer.from('load_tensors: offloaded 33/33 layers to GPU\n'))
child.stderr.emit('data', Buffer.from(`params: api_key = ${spawnedKey!.slice(0, 20)}`))
child.stderr.emit('data', Buffer.from(`${spawnedKey!.slice(20)} end\ndone\n`))
const joined = forwarded.join('')
// Complete lines flow with unchanged timing (the #42 offload consumer relies on it)…
expect(joined).toContain('load_tensors: offloaded 33/33 layers to GPU')
expect(joined).toContain('done')
// …but no fragment of the key ever reaches the observer, on any chunking.
expect(joined).not.toContain(spawnedKey!)
expect(joined).not.toContain(spawnedKey!.slice(0, 20))
expect(joined).not.toContain(spawnedKey!.slice(20))
expect(joined).toContain('[redacted]')
await server.stop()
})
it('redacts the key from onUnexpectedExit stderrTail (the gpuLastError/audit/log path)', async () => {
const exits: UnexpectedExitInfo[] = []
let spawnedKey: string | undefined
const child = new FakeChild() as FakeChild & { stderr: EventEmitter }
child.stderr = new EventEmitter()
const spawn = (
_c: string,
_args: string[],
options: { env?: Record<string, string | undefined> }
): ChildProcessLike => {
spawnedKey = options.env?.LLAMA_API_KEY
return child
}
const { fetchImpl } = healthFetch(0)
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
onUnexpectedExit: (info) => exits.push(info),
spawn,
fetchImpl,
findPort: async () => 51302,
healthIntervalMs: 1
})
await server.start()
child.stderr.emit('data', Buffer.from(`request denied: api-key ${spawnedKey} invalid\n`))
child.emit('exit', 134, null) // healthy server dies on its own → hook fires
expect(exits).toHaveLength(1)
expect(exits[0].stderrTail).toContain('request denied')
expect(exits[0].stderrTail).not.toContain(spawnedKey!)
expect(exits[0].stderrTail).toContain('[redacted]')
})
})
describe('redactExactKey / redactSidecarSecrets', () => {
it('removes the exact key wherever it appears', () => {
const key = 'a'.repeat(64)
expect(redactExactKey(`x ${key} y ${key}`, key)).toBe('x [redacted] y [redacted]')
expect(redactSidecarSecrets(`x ${key}`, key)).toBe('x [redacted]')
})
it('redacts generic api-key-adjacent VALUE-SHAPED tokens (≥8 chars) without a known key', () => {
expect(redactSidecarSecrets('--api-key secret123 --port 1', null)).toBe('--api-key [redacted] --port 1')
expect(redactSidecarSecrets('api_key: tok_abc12', null)).toBe('api_key: [redacted]')
expect(redactSidecarSecrets('LLAMA_API_KEY=deadbeef', null)).toBe('LLAMA_API_KEY=[redacted]')
})
it('leaves routine diagnostics untouched — the count line and short prose survive', () => {
// llama-server logs this on EVERY keyed start; mangling it sends support triage
// hunting a key leak that is a benign count (review 2026-08-18).
expect(redactSidecarSecrets('srv api_keys: 1 keys loaded', null)).toBe('srv api_keys: 1 keys loaded')
expect(redactSidecarSecrets('set LLAMA_API_KEY to enable auth', null)).toBe(
'set LLAMA_API_KEY to enable auth'
)
const line = 'load_tensors: offloaded 33/33 layers to GPU\nbind: address already in use'
expect(redactSidecarSecrets(line, 'f'.repeat(64))).toBe(line)
})
it('is stable under re-application (the read-time pass may run on drain-redacted text)', () => {
const once = redactSidecarSecrets('--api-key secret123', null)
expect(redactSidecarSecrets(once, null)).toBe(once)
// The drain's exact-key pass can leave `[redacted]` glued to trailing text; the read-time pass must
// not read that text as a second secret (the `(?!\[redacted\])` guard).
expect(redactSidecarSecrets('api_key=[redacted]tail', null)).toBe('api_key=[redacted]tail')
})
})
// ---- Start-failure signature (#312) -------------------------------------------------------
//
// Issue #312 — the comparable failure CLASS the GPU ladder's CPU control probe compares on.
// Text-matching llama.cpp's own vocabulary cannot do this job (a VRAM allocation failure — a
// genuine device fault — prints the same "error loading model:" prefix as an unsupported
// architecture), so the signature classifies only THIS module's four throw shapes plus the
// tail's failure line (#515: the first error-level line, else an `error …` line, else the last
// line), and answers null for anything else; the ladder reads null as "unknown ⇒ device fault".
describe('failureSignature (#312)', () => {
const EXIT = 'llama-server exited before becoming healthy'
it('classifies each of the four throw shapes', () => {
expect(failureSignature('llama-server failed to launch: spawn ENOENT')).toBe('launch')
expect(failureSignature(`${EXIT} (code 1)`)).toBe('exit:code 1')
expect(failureSignature(`${EXIT} (signal SIGABRT)`)).toBe('exit:signal SIGABRT')
expect(failureSignature('llama-server did not become healthy within 180000ms')).toBe('timeout')
expect(failureSignature('llama-server failed pre-spawn integrity verification')).toBe('integrity')
})
it("appends the tail's failure line: an error line, else the last one", () => {
expect(failureSignature(`${EXIT} (code 1) — last output: error loading model: bad arch`)).toBe(
'exit:code 1 | error loading model: bad arch'
)
expect(
failureSignature('llama-server did not become healthy within 180000ms — last output: still loading')
).toBe('timeout | still loading')
})
it('two exit failures differing only in EARLIER tail lines are equal', () => {
// Two loads of the same broken weight print different progress before the same final
// error — that noise must not make the CPU control look like a different failure.
const a = failureSignature(
`${EXIT} (code 1) — last output: load_tensors: loading 12 of 40\n\nerror loading model: bad arch`
)
const b = failureSignature(
`${EXIT} (code 1) — last output: load_tensors: loading 31 of 40\nerror loading model: bad arch `
)
expect(a).toBe('exit:code 1 | error loading model: bad arch')
expect(b).toBe(a)
})
it('a health timeout never equals an exit, even with the same tail', () => {
const timeout = failureSignature(
'llama-server did not become healthy within 180000ms — last output: error loading model: bad arch'
)
const exit = failureSignature(`${EXIT} (code 1) — last output: error loading model: bad arch`)
expect(timeout).not.toBe(exit)
// …and neither do two exits with different codes.
expect(failureSignature(`${EXIT} (code 134)`)).not.toBe(failureSignature(`${EXIT} (code 1)`))
})
it('answers null for anything it does not recognise', () => {
for (const unknown of [
'',
'something went sideways',
'Model start was cancelled (stopped while loading)',
'llama-server start aborted',
'Error: connect ECONNREFUSED 127.0.0.1:8080'
]) {
expect(failureSignature(unknown), unknown).toBeNull()
}
})
})
// #515: the #312 comparison on REAL llama-server tails (b11146, the app's chat argv, the app's
// stdio). The bare-line cases above never had llama.cpp's per-process timestamp, and under the
// app's own stdio the last line of a real tail is just a colour reset — so two rungs either never
// matched or always did. Fixtures: tests/fixtures/start-failure-b11146-*.txt (paths → <drive>).
describe('failureSignature on real llama-server tails (#515)', () => {
const EXIT = 'llama-server exited before becoming healthy (code 1) — last output: '
const tail = (name: string): string =>
readFileSync(join(__dirname, '..', 'fixtures', `start-failure-b11146-${name}.txt`), 'utf8').trim()
const ESC = String.fromCharCode(27)
const ROOT_CAUSE =
'gguf_init_from_reader: this GGUF file is version 117901063 but this software only supports up to version 3'
it('the same corrupt GGUF on the GPU and the CPU rung compares EQUAL — the root cause, no timestamp', () => {
const gpu = failureSignature(EXIT + tail('broken-gguf-gpu'))
const cpu = failureSignature(EXIT + tail('broken-gguf-cpu'))
expect(gpu).toBe(`exit:code 1 | ${ROOT_CAUSE}`)
expect(cpu).toBe(gpu)
// The raw last lines differ only in their timestamps — what made the old rule never match.
const last = (t: string): string => t.split('\n').filter(Boolean).at(-1)!
expect(last(tail('broken-gguf-gpu'))).not.toBe(last(tail('broken-gguf-cpu')))
})
it('a colour-coded tail (the app stdio before --log-colors off) gives the same signature', () => {
const coloured = tail('broken-gguf-gpu-coloured')
expect(coloured).toContain(ESC)
// Its last non-empty line is only a colour reset: the old rule compared that, i.e. nothing.
expect(coloured.split('\n').filter((l) => l.trim()).at(-1)!.trim()).toBe(`${ESC}[0m`)
expect(failureSignature(EXIT + coloured)).toBe(failureSignature(EXIT + tail('broken-gguf-cpu')))
})
it('CRLF line endings (how Windows delivers the tail) change nothing', () => {
const crlf = tail('broken-gguf-cpu').split('\n').join('\r\n')
expect(failureSignature(EXIT + crlf)).toBe(`exit:code 1 | ${ROOT_CAUSE}`)
})
it('an argument error is named by its own line, never by the usage screen after it', () => {
const arg = failureSignature(EXIT + tail('bad-device'))
expect(arg).toBe('exit:code 1 | error while handling argument "--device": invalid device: Vulkan7')
// …so a GPU-side failure and a CPU-side load failure stay DIFFERENT (a device verdict).
expect(arg).not.toBe(failureSignature(EXIT + tail('broken-gguf-cpu')))
})
})
// #729: the same tails on the b12110 pin (GTX 1070 Ti box, the app's chat argv and stdio, paths → <drive>). b12110 adds a
// CPU row to device_info and renames the last line's function (`server_run_i: exiting …`), and prints even its first line
// uncoloured; the root-cause line the signature takes is unchanged. A drive whose cpu/ net was not updated runs rung 1 on
// b12110 and rung 3 on b11146, so the two builds' tails must compare equal for the model to be blamed.
describe('failureSignature on real b12110 tails (#729)', () => {
const EXIT = 'llama-server exited before becoming healthy (code 1) — last output: '
const tail = (build: string, name: string): string =>
readFileSync(join(__dirname, '..', 'fixtures', `start-failure-${build}-${name}.txt`), 'utf8').trim()
const ROOT_CAUSE =
'gguf_init_from_reader: this GGUF file is version 117901063 but this software only supports up to version 3'
it('the corrupt GGUF on the GPU and the CPU rung compares equal, and equal to the b11146 tails', () => {
const gpu = failureSignature(EXIT + tail('b12110', 'broken-gguf-gpu'))
expect(gpu).toBe(`exit:code 1 | ${ROOT_CAUSE}`)
expect(failureSignature(EXIT + tail('b12110', 'broken-gguf-cpu'))).toBe(gpu)
expect(failureSignature(EXIT + tail('b11146', 'broken-gguf-cpu'))).toBe(gpu)
expect(tail('b12110', 'broken-gguf-gpu')).toContain('- CPU :')
})
it('an argument error is named by its own line and stays different from a load failure', () => {
const arg = failureSignature(EXIT + tail('b12110', 'bad-device'))
expect(arg).toBe('exit:code 1 | error while handling argument "--device": invalid device: Vulkan7')
expect(arg).toBe(failureSignature(EXIT + tail('b11146', 'bad-device')))
expect(arg).not.toBe(failureSignature(EXIT + tail('b12110', 'broken-gguf-cpu')))
})
})
describe('sidecar log output is never colour-coded (#515)', () => {
it('every llama-server spawn passes --log-colors off (all five sidecars share buildArgs)', () => {
const server = new LlamaServer({ binPath: '/bin/s', modelPath: '/m.gguf', contextTokens: 2048 })
const args = server.buildArgs(51302)
expect(args[args.indexOf('--log-colors') + 1]).toBe('off')
expect(args.filter((a) => a === '--log-colors')).toHaveLength(1)
})
it('strips colour codes from the tail a start-failure error carries', async () => {
const ESC = String.fromCharCode(27)
const child = new FakeChild() as FakeChild & { stderr: EventEmitter }
child.stderr = new EventEmitter()
const spawn = (): ChildProcessLike => {
queueMicrotask(() => {
// The first line llama.cpp prints before it parses --log-colors off.
child.stderr.emit('data', Buffer.from(`${ESC}[34m0.00.001.047${ESC}[0m ${ESC}[32mI ${ESC}[0msrv llama_server: initializing ...\r\n`))
child.stderr.emit('data', Buffer.from('0.00.160.242 E gguf_init_from_reader: failed to read header\r\n'))
child.emit('exit', 1, null)
})
return child
}
const fetchImpl = (async () => ({ ok: false, status: 503 }) as Response) as typeof fetch
const server = new LlamaServer({
binPath: '/bin/s',
modelPath: '/m.gguf',
contextTokens: 2048,
spawn,
fetchImpl,
findPort: async () => 51303,
healthIntervalMs: 1
})
let message = ''
await server.start().catch((err: Error) => (message = err.message))
expect(message).toContain('initializing ...')
expect(message).not.toContain(ESC)
expect(failureSignature(message)).toBe('exit:code 1 | gguf_init_from_reader: failed to read header')
})
})
// A hard `uncaughtException` skips the graceful will-quit teardown; on Windows the sidecar
// children (up to five co-resident llama-servers + whisper-cli) survive `process.exit(1)`,
// holding GBs of RAM + loopback ports. The registry is the crash handler's kill list:
// LlamaServer + WhisperCliTranscriber (the two seams every sidecar spawn funnels through)
// register on spawn and deregister on exit/error.
describe('sidecar child-PID registry (full-audit 2026-07-11 CODE-11)', () => {
it('register/deregister lifecycle, guarded against pid-less failed spawns', () => {
killRegisteredSidecarChildren(() => undefined) // isolate: clear leftovers from other tests
registerSidecarChild(undefined, 'llama_cpp') // a failed spawn has no pid — ignored, never throws
registerSidecarChild(1234, 'llama_cpp')
registerSidecarChild(1234, 'llama_cpp') // idempotent
registerSidecarChild(5678, 'llama_cpp')
expect([...registeredSidecarPids()].sort()).toEqual([1234, 5678])
unregisterSidecarChild(1234)
unregisterSidecarChild(undefined)
unregisterSidecarChild(999_999) // never registered — harmless
expect(registeredSidecarPids()).toEqual([5678])
unregisterSidecarChild(5678)
expect(registeredSidecarPids()).toEqual([])
})
it('killRegisteredSidecarChildren SIGKILLs every registered pid, is throw-safe per pid, and clears the set', () => {
killRegisteredSidecarChildren(() => undefined)
registerSidecarChild(11, 'llama_cpp')
registerSidecarChild(22, 'whisper_cpp') // crash-reap is family-agnostic — kills both
registerSidecarChild(33, 'llama_cpp')
const killed: number[] = []
const signals = new Set<string>()
killRegisteredSidecarChildren((pid, signal) => {
signals.add(String(signal))
// One already-dead / foreign pid throwing (ESRCH/EPERM) must not stop the loop.
if (pid === 22) throw new Error('kill ESRCH')
killed.push(pid)
})
expect(killed.sort()).toEqual([11, 33])
expect(signals).toEqual(new Set(['SIGKILL'])) // no polite-then-escalate: the parent is dying NOW
expect(registeredSidecarPids()).toEqual([]) // cleared either way — the process is exiting
})
})
// #790: the guard every spawn site calls on its child. Each site's own row (engine-load-spawn, gpu,
// engine-health, transcriber, zim-serve) proves it is called there; these pin what it does. The
// streams are EventEmitters, which throw on an unhandled 'error' exactly as Node's streams do.
describe('guardChildStdio (#790)', () => {
const streamError = (code: string): Error =>
// The message of a real one names no path, but nothing may rely on that: only the code is logged.
Object.assign(new Error(`read ${code} C:\\Users\\someone\\Kit\\runtime`), { code })
it('absorbs the error of every piped stream of a spawn that failed (no PID), logs nothing and tells the site which stream', () => {
// Measured (Node 24.13, Electron 43.8.3): a spawn that fails before its pipes are open emits the
// child's ENOENT, then ENOTCONN on each piped stream, and the child never got a PID.
const child = { pid: undefined, stdin: new EventEmitter(), stdout: new EventEmitter(), stderr: new EventEmitter() }
const heard: string[] = []
const warn = vi.spyOn(log, 'warn')
try {
guardChildStdio(child, 'the device probe', (stream) => heard.push(stream))
for (const stream of [child.stdin, child.stdout, child.stderr]) {
expect(() => stream.emit('error', streamError('ENOTCONN'))).not.toThrow()
}
expect(heard).toEqual(['stdin', 'stdout', 'stderr'])
expect(warn).not.toHaveBeenCalled() // the child's own 'error' is what each site logs
} finally {
warn.mockRestore()
}
})
it('logs a started child’s failed pipe with its code, never the message; a stream that is not piped is skipped', () => {
const child = { pid: 4242, stdin: null, stderr: new EventEmitter() } // stdout absent, stdin ignored
const warn = vi.spyOn(log, 'warn')
try {
guardChildStdio(child, 'whisper-cli')
expect(() => child.stderr.emit('error', streamError('ECONNRESET'))).not.toThrow()
expect(warn.mock.calls).toEqual([
[
'A pipe of a child process failed after it started; what it carries is no longer read',
{ program: 'whisper-cli', stream: 'stderr', code: 'ECONNRESET' }
]
])
} finally {
warn.mockRestore()
}
})
})