[idea] Docker 04/14: Headless entry for the sidecars
Which part? Desktop app
What would you like?
Step 4 of 14 of #2100: running SurfSense in Docker. Depends on #2103; start once it is merged.
A Node entry that runs the API, the workers and the model servers without Electron, which is what the container will run.
Design: Docker proposal, The supervisor, shared with Electron
What to change
surfsense_local/electron/src/headless/main.ts: build the context, callboot.ts, wait for/health, forward SIGTERM and SIGINT to every child, exit when the API exits.electron/src/headless/context-from-env.ts: the data dir, the backend dir, the runtime and model dirs and the secret, from environment variables, with the packaged-only environment (HF_HUB_OFFLINE) set when asked.- It runs as TypeScript on Node 24, as the package's tests do; no build step.
Done when
- [ ] On a dev machine,
node src/headless/main.tswith the documented variables starts the API and both workers, and/healthanswers. - [ ] Ctrl-C stops every child.
- [ ] Tests for
context-from-env.ts.
Scope: code and tests only. Don't edit docs/ or AGENTS.md, except to fix a link this change breaks; the maintainers update the docs when the Docker work ships.
Why would it help?
Each step leaves something that runs, so the Docker image is built and reviewed one piece at a time.
I would like to take the headless entry step once #2103 is merged. I checked the current assignment: #2103 is already owned by @llwand1, so I will coordinate with that extraction instead of duplicating it.
For #2104, the implementation would stay in surfsense_local/electron/src/headless/ and use the shared boot context. I propose tests for environment-to-context mapping (data/backend/runtime/model directories, secret and opt-in packaged environment), startup ordering through API health, and child-process shutdown on SIGTERM/SIGINT or API exit. The entry should run directly under Node 24, with code/tests only as requested.
I will wait for the prerequisite merge before implementing against its final interface. Could this step be assigned to me?
Hi @Protocol-zero-0, thanks for picking this up, and for checking the assignments first. Assigned to you.
The plan looks good to me: keeping it in surfsense_local/electron/src/headless/ on the shared boot context, plus tests for the environment-to-context mapping, startup ordering through API health, and shutdown on SIGTERM/SIGINT or API exit.
Edit: sorry I did not see that @llwand1 has already pushed their PR. I will soon merge it.
Thanks for assigning this and confirming the plan. I'll start #2104 once #2215 is merged, using the final shared boot interface. The delivery will include the environment context, health-gated startup, and shutdown tests for SIGTERM/SIGINT and API exit.
Implemented the headless entry against dev 1559bc9d8a3e3906213ac4747b2825962fd22c76. This uses the existing bootSidecars/supervisor unchanged and stays within code/tests; Caddy and Docker packaging remain #2105.
- Environment context selects data/backend/model/runtime directories and the source venv (
packaged=false).SURFSENSE_LOCAL_SECREToverrides the existing volumesecretfile; a fresh volume gets a private, persistent key. Existing keys are preserved.HF_HUB_OFFLINE=1is inherited when explicitly supplied, without making Python use frozen binaries. - Readiness is announced only after API health. SIGTERM/SIGINT and API failure stop watchers and reap the shared sidecars. A missing executable also fails promptly; shutdown does not leave the non-cancellable health poll holding the CLI open.
- The standard Electron test command includes the new headless tests.
Validation on Linux x86_64, Node 24.19.0: TypeScript check passed; the updated Electron test command passed 200 tests, including ten headless tests. Process tests use the actual shared boot/supervisor with small executable fixtures, not the production backend. They cover delayed health, SIGTERM, SIGINT during startup, API exits before/after health, missing interpreter, and child liveness after shutdown. Removing child cleanup deliberately makes the liveness test fail.
Separately, I synced the actual backend from the current lock and launched main.ts against it with a fresh data directory and HF_HUB_OFFLINE=1: the real API and both Huey workers started, /health returned 200, Ctrl-C returned exit code 0, and all three child PIDs were gone. No model download, remote model call, GPU, Docker image, Caddy or cross-platform test is claimed. The repository secret scan passes; fixture secrets are generated per test.
Reproduce from surfsense_local/electron after uv sync --frozen --no-dev in ../backend:
SURFSENSE_LOCAL_BACKEND_DIR="$PWD/../backend" \
SURFSENSE_LOCAL_DATA_DIR="$(mktemp -d)" \
SURFSENSE_LOCAL_MODELS_DIR="$PWD/models" \
SURFSENSE_LOCAL_RUNTIMES_DIR="$PWD/runtimes" \
HF_HUB_OFFLINE=1 node src/headless/main.ts
# Wait for [headless] ready http://127.0.0.1:..., then Ctrl-C.
Below is an apply-ready patch against the exact base (checked with git apply --cached --check on a clean base index). This is a patch delivery on the assigned issue, not a merged change or a PR. For #2105, the ready API URL comes from the unchanged boot result; Caddy can be added as another supervised sidecar after that health gate.
Apply-ready patch
diff --git a/surfsense_local/electron/package.json b/surfsense_local/electron/package.json
index c5e692a71..dcb544422 100644
--- a/surfsense_local/electron/package.json
+++ b/surfsense_local/electron/package.json
@@ -26,7 +26,7 @@
"build:audiocpp": "node scripts/audiocpp/stage.mjs",
"build:opencode": "node scripts/opencode/stage.mjs",
"dist": "pnpm build:llamacpp && pnpm build:sdcpp --strict && pnpm build:audiocpp --strict && pnpm build:opencode && pnpm build:frontend && pnpm build:binaries && pnpm build:model && pnpm build:voice && pnpm build:parser && pnpm build && electron-builder",
- "test": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON --test src/main/*.test.ts src/main/**/*.test.ts scripts/**/*.test.mjs",
+ "test": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON --test src/headless/*.test.ts src/main/*.test.ts src/main/**/*.test.ts scripts/**/*.test.mjs",
"typecheck": "tsc --noEmit -p tsconfig.json",
"check:sidecars": "node scripts/check-sidecars.mjs"
},
diff --git a/surfsense_local/electron/src/headless/context-from-env.test.ts b/surfsense_local/electron/src/headless/context-from-env.test.ts
new file mode 100644
index 000000000..e8fa2e5ba
--- /dev/null
+++ b/surfsense_local/electron/src/headless/context-from-env.test.ts
@@ -0,0 +1,75 @@
+import assert from "node:assert/strict"
+import { randomBytes } from "node:crypto"
+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+import { test } from "node:test"
+
+import { contextFromEnv } from "./context-from-env.ts"
+
+test("container context uses the source venv and the image layout", () => {
+ const suppliedSecret = randomBytes(32).toString("hex")
+ const context = contextFromEnv({ SURFSENSE_LOCAL_SECRET: suppliedSecret })
+ assert.deepEqual(context, {
+ packaged: false,
+ backendDir: "/app/backend",
+ binariesDir: "/app",
+ dataDir: "/data",
+ modelsDir: "/app/models",
+ llamacppBinariesDir: "/app/runtimes/llamacpp",
+ audioBinariesDir: "/app/runtimes/audiocpp",
+ sdcppBinariesDir: "/app/runtimes/sdcpp",
+ opencodeBinariesDir: "/app/runtimes/opencode",
+ secret: suppliedSecret,
+ })
+})
+
+test("a dev install selects its directories without changing the caller environment", () => {
+ const env = {
+ SURFSENSE_LOCAL_BACKEND_DIR: "/work/backend",
+ SURFSENSE_LOCAL_DATA_DIR: "/work/data",
+ SURFSENSE_LOCAL_MODELS_DIR: "/work/models",
+ SURFSENSE_LOCAL_RUNTIMES_DIR: "/work/runtimes",
+ SURFSENSE_LOCAL_SECRET: randomBytes(32).toString("hex"),
+ HF_HUB_OFFLINE: "1",
+ }
+ const before = { ...env }
+ const context = contextFromEnv(env)
+ assert.equal(context.backendDir, "/work/backend")
+ assert.equal(context.dataDir, "/work/data")
+ assert.equal(context.modelsDir, "/work/models")
+ assert.equal(context.llamacppBinariesDir, "/work/runtimes/llamacpp")
+ assert.equal(context.audioBinariesDir, "/work/runtimes/audiocpp")
+ assert.equal(context.sdcppBinariesDir, "/work/runtimes/sdcpp")
+ assert.equal(context.opencodeBinariesDir, "/work/runtimes/opencode")
+ assert.equal(context.packaged, false)
+ assert.deepEqual(env, before)
+})
+
+test("a volume keeps the same secret across restarts", (t) => {
+ const directory = mkdtempSync(join(tmpdir(), "headless-context-"))
+ t.after(() => rmSync(directory, { recursive: true, force: true }))
+ const env = { SURFSENSE_LOCAL_DATA_DIR: directory }
+ const first = contextFromEnv(env)
+ assert.match(first.secret, /^[a-f0-9]{64}$/)
+ assert.equal(contextFromEnv(env).secret, first.secret)
+ if (process.platform !== "win32") assert.equal(statSync(join(directory, "secret")).mode & 0o777, 0o600)
+})
+
+test("the persisted key remains compatible with Python's trimmed file fallback", (t) => {
+ const directory = mkdtempSync(join(tmpdir(), "headless-existing-secret-"))
+ t.after(() => rmSync(directory, { recursive: true, force: true }))
+ writeFileSync(join(directory, "secret"), "previous-install-key\n")
+ assert.equal(contextFromEnv({ SURFSENSE_LOCAL_DATA_DIR: directory }).secret, "previous-install-key")
+ const override = randomBytes(32).toString("hex")
+ assert.equal(contextFromEnv({ SURFSENSE_LOCAL_DATA_DIR: directory, SURFSENSE_LOCAL_SECRET: override }).secret, override)
+ assert.equal(readFileSync(join(directory, "secret"), "utf8"), "previous-install-key\n")
+})
+
+test("an empty persisted key fails without silently rotating it", (t) => {
+ const directory = mkdtempSync(join(tmpdir(), "headless-empty-secret-"))
+ t.after(() => rmSync(directory, { recursive: true, force: true }))
+ writeFileSync(join(directory, "secret"), "\n")
+ assert.throws(() => contextFromEnv({ SURFSENSE_LOCAL_DATA_DIR: directory }), /secret file is empty/)
+ assert.equal(readFileSync(join(directory, "secret"), "utf8"), "\n")
+})
diff --git a/surfsense_local/electron/src/headless/context-from-env.ts b/surfsense_local/electron/src/headless/context-from-env.ts
new file mode 100644
index 000000000..ce40401bc
--- /dev/null
+++ b/surfsense_local/electron/src/headless/context-from-env.ts
@@ -0,0 +1,35 @@
+import { randomBytes } from "node:crypto"
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs"
+import { join } from "node:path"
+import type { BootContext } from "../main/sidecars/boot.ts"
+
+/** The image runs Python from its venv, even when its models are bundled. */
+export function contextFromEnv(env: NodeJS.ProcessEnv): BootContext {
+ const dataDir = env.SURFSENSE_LOCAL_DATA_DIR || "/data"
+ return {
+ packaged: false,
+ backendDir: env.SURFSENSE_LOCAL_BACKEND_DIR || "/app/backend",
+ binariesDir: "/app",
+ dataDir,
+ modelsDir: env.SURFSENSE_LOCAL_MODELS_DIR || "/app/models",
+ llamacppBinariesDir: join(env.SURFSENSE_LOCAL_RUNTIMES_DIR || "/app/runtimes", "llamacpp"),
+ audioBinariesDir: join(env.SURFSENSE_LOCAL_RUNTIMES_DIR || "/app/runtimes", "audiocpp"),
+ sdcppBinariesDir: join(env.SURFSENSE_LOCAL_RUNTIMES_DIR || "/app/runtimes", "sdcpp"),
+ opencodeBinariesDir: join(env.SURFSENSE_LOCAL_RUNTIMES_DIR || "/app/runtimes", "opencode"),
+ secret: env.SURFSENSE_LOCAL_SECRET || volumeSecret(dataDir),
+ }
+}
+
+function volumeSecret(dataDir: string): string {
+ mkdirSync(dataDir, { recursive: true })
+ const path = join(dataDir, "secret")
+ try {
+ writeFileSync(path, randomBytes(32).toString("hex"), { flag: "wx", mode: 0o600 })
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error
+ }
+ // Match Python's existing file fallback; never replace an install's key.
+ const secret = readFileSync(path, "utf8").trim()
+ if (!secret) throw new Error("The data volume's secret file is empty")
+ return secret
+}
diff --git a/surfsense_local/electron/src/headless/fixtures/backend.mjs b/surfsense_local/electron/src/headless/fixtures/backend.mjs
new file mode 100644
index 000000000..7196a771a
--- /dev/null
+++ b/surfsense_local/electron/src/headless/fixtures/backend.mjs
@@ -0,0 +1,27 @@
+import { appendFileSync } from "node:fs"
+import { createServer } from "node:http"
+
+const name = process.argv[2] === "main.py" ? "api" : `worker-${process.argv[3]}`
+appendFileSync(process.env.TEST_CHILDREN, JSON.stringify({ name, pid: process.pid,
+ offline: process.env.HF_HUB_OFFLINE ?? null,
+ models: process.env.SURFSENSE_LOCAL_MODELS_DIR,
+ secretPresent: Boolean(process.env.SURFSENSE_LOCAL_SECRET),
+}) + "\n")
+if (name === "api") {
+ if (process.env.TEST_API_EXIT === "before-health") process.exit(7)
+ const started = Date.now()
+ createServer((req, res) => {
+ if (req.url === "/exit") {
+ res.end("exiting")
+ setImmediate(() => process.exit(9))
+ } else if (req.url === "/health") {
+ res.statusCode = Date.now() - started >= Number(process.env.TEST_HEALTH_DELAY || 0) ? 200 : 503
+ res.end("ok")
+ } else {
+ res.statusCode = 404
+ res.end()
+ }
+ }).listen(Number(process.env.SURFSENSE_LOCAL_PORT), process.env.SURFSENSE_LOCAL_HOST)
+} else {
+ setInterval(() => {}, 1000)
+}
diff --git a/surfsense_local/electron/src/headless/main.test.ts b/surfsense_local/electron/src/headless/main.test.ts
new file mode 100644
index 000000000..e65192e16
--- /dev/null
+++ b/surfsense_local/electron/src/headless/main.test.ts
@@ -0,0 +1,109 @@
+import assert from "node:assert/strict"
+import { randomBytes } from "node:crypto"
+import { spawn } from "node:child_process"
+import { once } from "node:events"
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
+import { tmpdir } from "node:os"
+import { join } from "node:path"
+import { setTimeout as delay } from "node:timers/promises"
+import { test, type TestContext } from "node:test"
+import { fileURLToPath } from "node:url"
+
+const main = fileURLToPath(new URL("./main.ts", import.meta.url))
+const fixture = fileURLToPath(new URL("./fixtures/backend.mjs", import.meta.url))
+
+function start(t: TestContext, extra: NodeJS.ProcessEnv = {}) {
+ const directory = mkdtempSync(join(tmpdir(), "headless-process-"))
+ const backend = join(directory, "backend")
+ mkdirSync(join(backend, ".venv/bin"), { recursive: true })
+ if (extra.TEST_MISSING_PYTHON !== "1") writeFileSync(join(backend, ".venv/bin/python"),
+ `#!/bin/sh\nexec '${process.execPath}' '${fixture}' "$@"\n`, { mode: 0o755 })
+ const childrenPath = join(directory, "children.jsonl")
+ const env: NodeJS.ProcessEnv = { ...process.env,
+ SURFSENSE_LOCAL_BACKEND_DIR: backend,
+ SURFSENSE_LOCAL_DATA_DIR: join(directory, "data"),
+ SURFSENSE_LOCAL_MODELS_DIR: join(directory, "models"),
+ SURFSENSE_LOCAL_RUNTIMES_DIR: join(directory, "runtimes"),
+ SURFSENSE_LOCAL_SECRET: randomBytes(32).toString("hex"),
+ TEST_CHILDREN: childrenPath,
+ ...extra,
+ }
+ delete env.HF_HUB_OFFLINE
+ if (extra.HF_HUB_OFFLINE !== undefined) env.HF_HUB_OFFLINE = extra.HF_HUB_OFFLINE
+ const child = spawn(process.execPath, ["--disable-warning=MODULE_TYPELESS_PACKAGE_JSON", main], { env })
+ let output = ""
+ child.stdout.on("data", (data) => { output += data })
+ child.stderr.on("data", (data) => { output += data })
+ const ended = once(child, "exit")
+ const children = (): { name: string; pid: number; offline: string | null; secretPresent: boolean }[] =>
+ existsSync(childrenPath) ? readFileSync(childrenPath, "utf8").trim().split("\n").filter(Boolean).map(line => JSON.parse(line)) : []
+ t.after(async () => {
+ if (child.exitCode === null && child.signalCode === null) {
+ child.kill("SIGKILL")
+ await ended
+ }
+ for (const row of children()) {
+ try { process.kill(-row.pid, "SIGKILL") } catch { /* Already reaped. */ }
+ }
+ rmSync(directory, { recursive: true, force: true })
+ })
+ async function until(condition: () => boolean) {
+ const deadline = Date.now() + 8000
+ while (!condition()) {
+ assert.equal(child.exitCode, null, output)
+ assert.ok(Date.now() < deadline, output || "headless readiness timed out")
+ await delay(20)
+ }
+ }
+ return { child, ended, children, until, output: () => output }
+}
+
+const posix = { skip: process.platform === "win32", timeout: 15_000 }
+
+test("readiness waits for health, then SIGTERM reaps API and both workers", posix, async (t) => {
+ const app = start(t, { TEST_HEALTH_DELAY: "600", HF_HUB_OFFLINE: "1" })
+ await app.until(() => app.children().length === 3)
+ assert.doesNotMatch(app.output(), /\[headless\] ready/)
+ await app.until(() => /\[headless\] ready/.test(app.output()))
+ assert.deepEqual(app.children().map(row => row.name).sort(), ["api", "worker-ingest", "worker-studio"])
+ assert.ok(app.children().every(row => row.offline === "1" && row.secretPresent))
+ const url = app.output().match(/\[headless\] ready (http:\/\/127\.0\.0\.1:\d+)/)![1]
+ assert.equal((await fetch(`${url}/health`)).status, 200)
+ app.child.kill("SIGTERM")
+ assert.deepEqual(await app.ended, [0, null])
+ for (const row of app.children()) assert.throws(() => process.kill(row.pid, 0), { code: "ESRCH" })
+})
+
+test("SIGINT during startup stops every child without announcing readiness", posix, async (t) => {
+ const app = start(t, { TEST_HEALTH_DELAY: "30000" })
+ await app.until(() => app.children().length === 3)
+ assert.ok(app.children().every(row => row.offline === null))
+ app.child.kill("SIGINT")
+ assert.deepEqual(await app.ended, [0, null])
+ assert.doesNotMatch(app.output(), /\[headless\] ready/)
+ for (const row of app.children()) assert.throws(() => process.kill(row.pid, 0), { code: "ESRCH" })
+})
+
+test("API exit after readiness stops the workers and preserves the failure code", posix, async (t) => {
+ const app = start(t)
+ await app.until(() => /\[headless\] ready/.test(app.output()) && app.children().length === 3)
+ const url = app.output().match(/\[headless\] ready (http:\/\/127\.0\.0\.1:\d+)/)![1]
+ await fetch(`${url}/exit`)
+ assert.deepEqual(await app.ended, [9, null])
+ for (const row of app.children()) assert.throws(() => process.kill(row.pid, 0), { code: "ESRCH" })
+})
+
+test("API exit before health fails promptly and cleans up startup", posix, async (t) => {
+ const app = start(t, { TEST_API_EXIT: "before-health" })
+ assert.deepEqual(await app.ended, [7, null])
+ assert.doesNotMatch(app.output(), /\[headless\] ready/)
+ for (const row of app.children()) assert.throws(() => process.kill(row.pid, 0), { code: "ESRCH" })
+})
+
+
+test("a missing interpreter fails promptly without leaving a health poll alive", posix, async (t) => {
+ const app = start(t, { TEST_MISSING_PYTHON: "1" })
+ const deadline = delay(1500).then(() => "still-running")
+ assert.deepEqual(await Promise.race([app.ended, deadline]), [1, null])
+ assert.doesNotMatch(app.output(), /\[headless\] ready/)
+})
diff --git a/surfsense_local/electron/src/headless/main.ts b/surfsense_local/electron/src/headless/main.ts
new file mode 100644
index 000000000..a4be6c450
--- /dev/null
+++ b/surfsense_local/electron/src/headless/main.ts
@@ -0,0 +1,62 @@
+import { bootSidecars, type Booted, type BootContext } from "../main/sidecars/boot.ts"
+import { stopAll } from "../main/sidecars/supervisor.ts"
+import { contextFromEnv } from "./context-from-env.ts"
+
+/** Keep the process alive until a signal or API failure, then reap the shared stack. */
+export async function runHeadless(context: BootContext): Promise<number> {
+ let booted: Booted | undefined
+ let exitCode: number | undefined
+ let requestStop!: () => void
+ const stopped = new Promise<void>((resolve) => { requestStop = resolve })
+ const stop = (code: number) => {
+ exitCode ??= code
+ requestStop()
+ }
+ const signal = () => stop(0)
+ process.on("SIGTERM", signal)
+ process.on("SIGINT", signal)
+ try {
+ booted = await bootSidecars(context, (name, code) => {
+ if (name === "api") stop(code && code > 0 ? code : 1)
+ })
+ for (const [name, child] of booted.sidecars) {
+ child.on("error", () => {
+ console.error(`[headless] could not start ${name}`)
+ stop(1)
+ })
+ }
+ if (exitCode === undefined) {
+ const healthy = await Promise.race([
+ booted.waitHealthy().then(() => true),
+ stopped.then(() => false),
+ ])
+ if (healthy && exitCode === undefined) console.log(`[headless] ready ${booted.apiUrl}`)
+ }
+ await stopped
+ } catch (error) {
+ if (exitCode === undefined) {
+ console.error("[headless] startup failed:", error instanceof Error ? error.message : "unknown error")
+ exitCode = 1
+ }
+ } finally {
+ // Watchers must not restart a runtime while its process group is stopping.
+ booted?.stopWatching()
+ if (booted) await stopAll(booted.sidecars)
+ process.off("SIGTERM", signal)
+ process.off("SIGINT", signal)
+ }
+ return exitCode ?? 1
+}
+
+if (import.meta.main) {
+ try {
+ const code = await runHeadless(contextFromEnv(process.env))
+ // The shared health probe has no cancellation; cleanup has reaped every child.
+ await new Promise<void>((resolve) => process.stdout.write("", () => resolve()))
+ await new Promise<void>((resolve) => process.stderr.write("", () => resolve()))
+ process.exit(code)
+ } catch (error) {
+ console.error("[headless] configuration failed:", error instanceof Error ? error.message : "unknown error")
+ process.exitCode = 1
+ }
+}
Additional CPU/backend compatibility evidence for the headless work, checked on current dev 299abf676a4ab1eec059e8e92f423f53aefa222d.
I ran the real bundled-runtime adapter against the pinned llama.cpp b11050 / 60b06ab9a Linux x86_64 Vulkan archive on a host with no available GPU devices, using the curated Qwen3-0.6B Q4_K_M artifact. Both downloads matched the SHA-256 pinned by this repository. The worker used two CPU threads and a 2048-token context.
The reproducible probe records 13 checks:
- Empty router: healthy, router role detected, empty inventory; an absent model returns HTTP 400 with its actual error.
- Installed model: initially unloaded, then auto-loaded by the real
LlamaCppProvider. Cold and warm streamed replies contain text; prompt-progress events survive. A JSON Schema-constrained reply parses to{"answer": 4}. - Real backend + freshly migrated SQLite database: connection creation returns 201, model discovery returns 200 and declares
text_gen,/chat-testreturns 200 with actual model text, and an absent model becomes 502 with the upstream reason. - The real tokenizer reports 2 tokens for
hello world; loaded/propsreports the requested 2048-token context. Unload reaches the unloaded state, and the next adapter call auto-loads the model and answers again. The probe terminates its router/worker process group infinally.
The existing connection/routes/image-capability integration tests and OpenAI-compatible/llama.cpp provider tests also pass: 150 passed. Those integration fixtures use stand-in HTTP servers; the separate probe below uses actual model inference. The current streamed-error fix also passes a real-socket error-envelope check, so there is no duplicate bug report for that.
This is Linux host backend/runtime evidence. Docker image construction, Caddy, arm64, GPU execution, preset-watcher restart, container memory fit and end-to-end document retrieval are still outside this result. The original #2104 implementation remains available in the earlier patch; this comment adds verification rather than replacing it or completing #2107.
Run the same real-model probe from surfsense_local/backend
Save the Python block below as cpu-smoke.py in a temporary directory, and set PROBE to that directory. After installing this checkout's backend dependencies:
curl -fL https://github.com/ggml-org/llama.cpp/releases/download/b11050/llama-b11050-bin-ubuntu-vulkan-x64.tar.gz -o "$PROBE/llama.tar.gz"
curl -fL https://huggingface.co/unsloth/Qwen3-0.6B-GGUF/resolve/50968a4468ef4233ed78cd7c3de230dd1d61a56b/Qwen3-0.6B-Q4_K_M.gguf -o "$PROBE/Qwen3-0.6B-Q4_K_M.gguf"
(cd "$PROBE" && printf '%s\n' 'eba230a6c76dee7422d1851651d7c4634fb6a39aed57e524a3612e9ed2bd1d89 llama.tar.gz' 'ac2d97712095a558e31573f62f466a3f9d93990898b0ec79d7c974c1780d524a Qwen3-0.6B-Q4_K_M.gguf' | sha256sum -c -)
mkdir -p "$PROBE/runtime"
tar -xzf "$PROBE/llama.tar.gz" -C "$PROBE/runtime"
PYTHONPATH=. SURFSENSE_LOCAL_DATA_DIR="$PROBE/data" SURFSENSE_LOCAL_SECRET="$(python -c 'import secrets; print(secrets.token_hex(32))')" uv run --no-sync python "$PROBE/cpu-smoke.py"
"""Exercise the checked-out SurfSense adapter against the pinned real runtime."""
import asyncio
import dataclasses
import json
import os
from pathlib import Path
import signal
import socket
import subprocess
import time
import httpx
from modules.llm.providers.llamacpp.provider import LlamaCppProvider
from modules.llm.providers.llamacpp.router_client import RouterClient
from modules.llm.providers.types import Message
P = Path(__file__).resolve().parent
MODEL = 'Qwen3-0.6B-Q4_K_M'
BINARY = P / 'runtime/llama-b11050/llama-server'
RESULT = {'runtime': 'b11050/60b06ab9a', 'model': MODEL, 'cases': [], 'real_model': True}
def note(name, value):
RESULT['cases'].append({'name': name, 'result': value})
print(name, json.dumps(value, ensure_ascii=False), flush=True)
(P / 'cpu-evidence.json').write_text(json.dumps(RESULT, ensure_ascii=False, indent=2) + '\n')
async def exercise(url, empty):
router = RouterClient(url)
async with httpx.AsyncClient(base_url=url, timeout=30) as client:
assert await router.health()
assert await router.is_router()
models = await router.models()
note('empty-router' if empty else 'model-inventory', [dataclasses.asdict(m) for m in models])
if empty:
assert models == []
response = await client.post('/v1/chat/completions', json={'model': 'missing', 'messages': [{'role': 'user', 'content': 'hello'}]})
assert response.status_code >= 400
note('missing-model-http', {'status': response.status_code, 'body': response.json()})
return
assert len(models) == 1 and not models[0].loaded
provider = LlamaCppProvider(url, P / 'models')
assert any(m.name == MODEL and m.installed for m in await provider.models())
for case, kwargs, prompt in [
('cold-stream', {'reasoning': False, 'max_tokens': 32}, 'Answer in one short sentence: what is 2 plus 2?'),
('warm-stream', {'reasoning': False, 'max_tokens': 32}, 'Write one short greeting.'),
('constrained-json', {'reasoning': False, 'max_tokens': 64, 'json_schema': {'type': 'object', 'properties': {'answer': {'type': 'integer', 'const': 4}}, 'required': ['answer'], 'additionalProperties': False}}, 'Return an object with answer equal to 4.'),
]:
start = time.monotonic()
deltas = []
async for delta in provider.chat_deltas(MODEL, [Message('user', prompt)], temperature=0, **kwargs):
deltas.append(dataclasses.asdict(delta))
answer = ''.join(d['text'] for d in deltas if not d['reasoning'] and d['progress'] is None)
assert answer.strip(), case
if case == 'constrained-json':
assert json.loads(answer) == {'answer': 4}
note(case, {'answer': answer, 'deltas': deltas, 'elapsed_seconds': round(time.monotonic()-start, 3)})
# Exercise the same runtime through the real API and migrated SQLite DB.
from api.main import create_app
from shared.db import create_db_engine, create_session_factory, import_models
from shared.migrations import upgrade_to_head
from modules.embedding.bundled import BGE
from modules.embedding.lock import lock_index
import_models()
engine = create_db_engine(P / f'api-cpu-{time.time_ns()}.db')
upgrade_to_head(engine)
factory = create_session_factory(engine)
with factory() as session:
lock_index(session, BGE)
session.commit()
app = create_app()
app.state.session_factory = factory
try:
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test', timeout=60) as api:
created = await api.post('/llm/connections', json={'label': 'CPU fixture', 'provider': 'openai_compatible', 'base_url': url+'/v1'})
assert created.status_code == 201, created.text
connection_id = created.json()['id']
listed = await api.get(f'/llm/connections/{connection_id}/models')
assert listed.status_code == 200, listed.text
assert any(m['name'] == MODEL for m in listed.json()), listed.text
note('real-api-discovery', {'create_status': created.status_code, 'models': listed.json()})
answer = await api.post(f'/llm/connections/{connection_id}/chat-test', json={'model': MODEL, 'prompt': 'Say hello. /no_think'})
assert answer.status_code == 200 and answer.json()['reply'].strip(), answer.text
note('real-api-chat-test', {'status': answer.status_code, 'body': answer.json()})
missing = await api.post(f'/llm/connections/{connection_id}/chat-test', json={'model': 'missing', 'prompt': 'hello'})
assert missing.status_code == 502, missing.text
note('real-api-missing-model', {'status': missing.status_code, 'body': missing.json()})
finally:
engine.dispose()
token_count = await provider.token_count(MODEL, 'hello world')
assert isinstance(token_count, int) and token_count > 0
# Resolve a fresh adapter as the app does after a model load.
loaded_provider = LlamaCppProvider(url, P / 'models')
actual_context = await loaded_provider.context_tokens(MODEL)
assert actual_context == 2048, actual_context
note('tokenizer-context', {'tokens': token_count, 'context': actual_context})
note('loaded-worker', [dataclasses.asdict(m) for m in await router.models()])
await router.unload(MODEL)
unload_started = time.monotonic()
for _ in range(100):
if not (await router.models())[0].loaded:
break
await asyncio.sleep(0.1)
else:
raise AssertionError('model still loaded 10 seconds after unload')
note('unload', {'observed_unloaded': True, 'seconds': round(time.monotonic()-unload_started, 3)})
# The next real adapter call must auto-load it again, without a separate load call.
again = ''.join([chunk async for chunk in LlamaCppProvider(url, P/'models').chat(MODEL, [Message('user', 'Say hello.')], reasoning=False, max_tokens=24, temperature=0)])
assert again.strip()
assert (await router.models())[0].loaded
note('reload-after-unload', {'answer': again})
def run(empty):
folder = P / ('empty-models' if empty else 'models')
folder.mkdir(exist_ok=True)
if not empty:
weights = P / f'{MODEL}.gguf'
target = folder / weights.name
if not target.exists():
os.link(weights, target)
(folder / 'models.ini').write_text(f'[{MODEL}]\nmodel = {target}\nctx-size = 2048\nparallel = 1\nthreads = 2\nthreads-batch = 2\ncache-ram = 0\nfit-target = 256\n')
with socket.socket() as s:
s.bind(('127.0.0.1', 0))
port = s.getsockname()[1]
argv = [str(BINARY), '--models-dir', str(folder), '--host', '127.0.0.1', '--port', str(port), '--models-max', '1', '--models-autoload', '--no-ui', '--jinja', '--reasoning-format', 'deepseek']
if not empty:
argv += ['--models-preset', str(folder / 'models.ini')]
log = (P / ('runtime-empty.log' if empty else 'runtime-model.log')).open('w')
proc = subprocess.Popen(argv, stdout=log, stderr=subprocess.STDOUT, start_new_session=True, cwd=BINARY.parent)
url = f'http://127.0.0.1:{port}'
try:
for _ in range(100):
if proc.poll() is not None:
raise RuntimeError(f'runtime exited {proc.returncode}')
try:
if httpx.get(url + '/health', timeout=0.3).status_code == 200:
break
except httpx.HTTPError:
pass
time.sleep(0.1)
else:
raise RuntimeError('router readiness timeout')
asyncio.run(exercise(url, empty))
finally:
os.killpg(proc.pid, signal.SIGTERM)
try:
proc.wait(timeout=15)
except subprocess.TimeoutExpired:
os.killpg(proc.pid, signal.SIGKILL)
proc.wait(timeout=5)
log.close()
RESULT['runtime_stopped'] = proc.poll() is not None
(P / 'cpu-evidence.json').write_text(json.dumps(RESULT, ensure_ascii=False, indent=2)+'\n')
if __name__ == '__main__':
run(True)
run(False)
RESULT['passed'] = True
(P / 'cpu-evidence.json').write_text(json.dumps(RESULT, ensure_ascii=False, indent=2)+'\n')
Step 4 is done in #2353, which closes this issue when it merges.
- The supervisor moved out of
electron/first (ADR 0072):sidecars/,runtimes/, and the headless entry insurfsense_local/headless/. - The headless entry builds on the patch posted above, updated for today's
boot.ts(three workers, opencode, transcription). - It settles the secret before boot, gives every sidecar the container's environment, and stops cleanly on SIGTERM/SIGINT.
Thanks for integrating the headless handoff into #2353 and updating it for the three-worker boot. I independently checked merged dev 7c3a6950c on Linux:
pnpm test: 584 passed, 10 skipped, 0 failed (594 total);pnpm typecheckpassed.python3 scripts/check_docs.py: 171 files, 0 problems.- Real Python backend, isolated data directory, no staged model runtimes: both SIGTERM and SIGINT runs reached
/health200 with the API plus ingest, studio and plugins workers. Each stopped with exit 0, no surviving direct children, andapi-urlremoved. A second launch reused the same secret; its file remained mode 0600.
The existing venv's editable manifest dependency still pointed at the pre-move plugins/bundles/core/manifest directory: the API could answer health while workers failed to import it. For the smoke check I selected the currently declared backend/plugins/bundles/core/manifest source through subprocess PYTHONPATH, without changing the venv. This is a lifecycle check against the real backend, not a fresh dependency installation, Docker image, GPU or retrieval acceptance test.