import { test, expect } from "vitest"; import { spawn as nodeSpawn } from "node:child_process"; import path from "node:path"; import os from "node:os"; import { chmodSync, unlinkSync, writeFileSync } from "node:fs"; import { buildApp } from "../src/app.js"; import { loadConfig } from "../src/config.js"; const FAKE = path.resolve("../harness/tests/fake_pi/fake_pi_rpc.mjs"); const SCRIPT = path.resolve("../harness/tests/fake_pi/scripts/f1_disambiguation.json"); function mutApp(thtRunner: any) { return buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { thtRunner: { ollamaEnsure: async () => ({ ok: true }), ...thtRunner }, getSettings: () => ({ workspace: "w" }) as any, spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any, }); } test("POST /sessions usa i settings (workspace/provider/model/thinking) e crea+avvia", async () => { const modelKey = path.join(os.tmpdir(), `thoth-model-key-${process.pid}`); writeFileSync(modelKey, "test-model-key", { mode: 0o600 }); chmodSync(modelKey, 0o600); let sessionNewArg: any; let spawnArg: any; const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness", THT_MODEL_API_KEY_FILE: modelKey, }), { thtRunner: { ollamaEnsure: async () => ({ ok: true }), searchPack: async () => {}, sessionNew: async (o: any) => { sessionNewArg = o; return { id: "s1" }; }, sessionList: async () => [{ id: "s1" }], } as any, getSettings: () => ({ workspace: "w", provider: "zai", model: "glm-5.2", thinking: "high" }), spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any, }); const created = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); expect(created.json()).toEqual({ id: "s1" }); expect(sessionNewArg.workspace).toBe("w"); expect(sessionNewArg.provider).toBe("zai"); expect(sessionNewArg.model).toBe("glm-5.2"); expect(sessionNewArg.thinking).toBe("high"); expect(sessionNewArg.question).toBe("q"); const list = await app.inject({ method: "GET", url: "/sessions" }); expect(list.json()).toEqual([{ id: "s1" }]); unlinkSync(modelKey); }); test("POST /sessions configura Pi con il thinking globale selezionato", async () => { let configured: any; const bridge = { onClientEvent: () => {}, emitClientEvent: () => {} }; const runtime = { bridge } as any; const mgr = { createFor: () => runtime, configure: async (_rt: any, options: any) => { configured = options; }, start: () => {}, teardown: () => {}, } as any; const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { mgr, thtRunner: { ollamaEnsure: async () => ({ ok: true }), searchPack: async () => {}, sessionNew: async () => ({ id: "s-thinking" }), } as any, getSettings: () => ({ workspace: "psd", provider: "zai", model: "glm-5.2", thinking: "high" }) as any, }); await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); await new Promise((resolve) => setImmediate(resolve)); expect(configured.thinking).toBe("high"); }); test("POST /sessions/:id/resume configura Pi con il thinking persistito", async () => { let configured: any; const bridge = { onClientEvent: () => {}, emitClientEvent: () => {} }; const runtime = { bridge } as any; const mgr = { get: () => undefined, createFor: () => runtime, configure: async (_rt: any, options: any) => { configured = options; }, start: () => {}, teardown: () => {}, } as any; const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { mgr, thtRunner: { ollamaEnsure: async () => ({ ok: true }), sessionShow: async () => ({ status: "open", archived: false, provider: "zai", model: "glm-5.2", thinking: "medium", }), reopenSession: async () => {}, } as any, getSettings: () => ({ workspace: "psd", thinking: "low" }) as any, }); await app.inject({ method: "POST", url: "/sessions/s-thinking/resume" }); await new Promise((resolve) => setImmediate(resolve)); expect(configured.thinking).toBe("medium"); }); test("POST /sessions/:id/resume usa il thinking globale se manca nel manifest", async () => { let configured: any; const bridge = { onClientEvent: () => {}, emitClientEvent: () => {} }; const runtime = { bridge } as any; const mgr = { get: () => undefined, createFor: () => runtime, configure: async (_rt: any, options: any) => { configured = options; }, start: () => {}, teardown: () => {}, } as any; const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { mgr, thtRunner: { ollamaEnsure: async () => ({ ok: true }), sessionShow: async () => ({ status: "open", archived: false }), reopenSession: async () => {}, } as any, getSettings: () => ({ workspace: "psd", thinking: "low" }) as any, }); await app.inject({ method: "POST", url: "/sessions/s-thinking/resume" }); await new Promise((resolve) => setImmediate(resolve)); expect(configured.thinking).toBe("low"); }); test.each(["running", "waiting"])( "POST resume preserves a %s runtime", async (state) => { let tornDown = false; let cleared = false; const existing = { bridge: { turnState: () => state } } as any; const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { mgr: { get: () => existing, teardown: () => { tornDown = true; }, } as any, hub: { clear: () => { cleared = true; } } as any, thtRunner: {} as any, getSettings: () => ({ workspace: "psd" }) as any, }); const response = await app.inject({ method: "POST", url: "/sessions/s1/resume" }); expect(response.json()).toEqual({ id: "s1", alreadyActive: true }); expect(tornDown).toBe(false); expect(cleared).toBe(false); }, ); test.each(["idle", "failed"])( "POST resume replaces a %s runtime and starts the persisted session", async (state) => { const order: string[] = []; const oldRuntime = { bridge: { turnState: () => state } } as any; const newRuntime = { bridge: { onClientEvent: () => {}, emitClientEvent: () => {} } } as any; const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { mgr: { get: () => oldRuntime, teardown: (id: string) => order.push(`teardown:${id}`), createFor: () => { order.push("create"); return newRuntime; }, configure: async () => {}, start: () => order.push("start"), } as any, hub: { clear: (id: string) => order.push(`clear:${id}`), publish: () => {}, } as any, thtRunner: { sessionShow: async () => ({ status: "open", archived: false, provider: "local-qwen", model: "qwen3.6-35b-a3b", thinking: "low", }), reopenSession: async () => order.push("reopen"), } as any, readiness: { ensure: async () => ({ ok: true }) } as any, getSettings: () => ({ workspace: "local", thinking: "medium" }) as any, }); const response = await app.inject({ method: "POST", url: "/sessions/s1/resume" }); await new Promise((resolve) => setImmediate(resolve)); expect(response.json()).toEqual({ id: "s1" }); expect(order).toEqual(["teardown:s1", "clear:s1", "reopen", "create", "start"]); }, ); test("POST resume without a runtime clears stale SSE state before cold start", async () => { const order: string[] = []; let createOptions: any; const newRuntime = { bridge: { onClientEvent: () => {}, emitClientEvent: () => {} } } as any; const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { mgr: { get: () => undefined, createFor: (_id: string, options: any) => { createOptions = options; order.push("create"); return newRuntime; }, configure: async () => {}, start: () => order.push("start"), } as any, hub: { clear: (id: string) => order.push(`clear:${id}`), publish: () => {}, } as any, thtRunner: { sessionShow: async () => ({ status: "open", archived: false, provider: "local-qwen", model: "qwen3.6-35b-a3b", thinking: "low", }), reopenSession: async () => order.push("reopen"), } as any, readiness: { ensure: async () => ({ ok: true }) } as any, getSettings: () => ({ workspace: "local", thinking: "medium" }) as any, }); const response = await app.inject({ method: "POST", url: "/sessions/crashed/resume" }); await new Promise((resolve) => setImmediate(resolve)); expect(response.json()).toEqual({ id: "crashed" }); expect(order).toEqual(["clear:crashed", "reopen", "create", "start"]); expect(createOptions).toMatchObject({ provider: "local-qwen", model: "qwen3.6-35b-a3b", thinking: "low", mode: "resume", }); }); test("POST resume keeps an idle runtime stream attached when the manifest is read-only", async () => { let tornDown = false; let cleared = false; const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { mgr: { get: () => ({ bridge: { turnState: () => "idle" } }), teardown: () => { tornDown = true; }, } as any, hub: { clear: () => { cleared = true; } } as any, thtRunner: { sessionShow: async () => ({ status: "finalized", archived: false }), } as any, getSettings: () => ({ workspace: "local" }) as any, }); const response = await app.inject({ method: "POST", url: "/sessions/s1/resume" }); expect(response.statusCode).toBe(409); expect(tornDown).toBe(false); expect(cleared).toBe(false); }); test("POST resume keeps a failed runtime stream attached when readiness fails", async () => { let tornDown = false; let cleared = false; const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { mgr: { get: () => ({ bridge: { turnState: () => "failed" } }), teardown: () => { tornDown = true; }, } as any, hub: { clear: () => { cleared = true; } } as any, thtRunner: { sessionShow: async () => ({ status: "open", archived: false }), } as any, readiness: { ensure: async () => ({ ok: false, error: "not ready" }) } as any, getSettings: () => ({ workspace: "local" }) as any, }); const response = await app.inject({ method: "POST", url: "/sessions/s1/resume" }); expect(response.statusCode).toBe(503); expect(tornDown).toBe(false); expect(cleared).toBe(false); }); test("POST /sessions/:id/response inoltra al bridge (no error)", async () => { const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { thtRunner: { ollamaEnsure: async () => ({ ok: true }), searchPack: async () => {}, sessionNew: async () => ({ id: "s1" }), sessionList: async () => [], } as any, getSettings: () => ({ workspace: "w" }), spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any, }); await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); const res = await app.inject({ method: "POST", url: "/sessions/s1/response", payload: { ui_response: { id: "u1", choices: ["a"] } } }); expect(res.statusCode).toBe(204); }); test("POST /sessions/:id/rename calls setName", async () => { let arg: any; const app = mutApp({ setName: async (id: string, name: string) => { arg = { id, name }; } }); const res = await app.inject({ method: "POST", url: "/sessions/s1/rename", payload: { name: "N" } }); expect(res.statusCode).toBe(204); expect(arg).toEqual({ id: "s1", name: "N" }); }); test("POST /sessions/:id/group calls setGroup", async () => { let arg: any; const app = mutApp({ setGroup: async (id: string, group: string) => { arg = { id, group }; } }); const res = await app.inject({ method: "POST", url: "/sessions/s1/group", payload: { group: "G" } }); expect(res.statusCode).toBe(204); expect(arg).toEqual({ id: "s1", group: "G" }); }); test("POST archive / unarchive call the runner", async () => { const seen: string[] = []; const app = mutApp({ archive: async (id: string) => { seen.push(`a:${id}`); }, unarchive: async (id: string) => { seen.push(`u:${id}`); }, }); expect((await app.inject({ method: "POST", url: "/sessions/s1/archive" })).statusCode).toBe(204); expect((await app.inject({ method: "POST", url: "/sessions/s1/unarchive" })).statusCode).toBe(204); expect(seen).toEqual(["a:s1", "u:s1"]); }); test("DELETE /sessions/:id calls deleteSession", async () => { let deleted: string | null = null; const app = mutApp({ deleteSession: async (id: string) => { deleted = id; } }); const res = await app.inject({ method: "DELETE", url: "/sessions/s1" }); expect(res.statusCode).toBe(204); expect(deleted).toBe("s1"); }); test("DELETE /sessions/:id tears down the runtime before deleting on disk", async () => { const order: string[] = []; const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { thtRunner: { deleteSession: async (id: string) => { order.push(`del:${id}`); } } as any, mgr: { teardown: (id: string) => { order.push(`teardown:${id}`); } } as any, getSettings: () => ({ workspace: "w" }) as any, spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any, }); const res = await app.inject({ method: "DELETE", url: "/sessions/s1" }); expect(res.statusCode).toBe(204); expect(order).toEqual(["teardown:s1", "del:s1"]); }); test("GET /sessions/:id/documents returns the runner output", async () => { const app = mutApp({ documents: async () => [{ phase: "—", key: "question", title: "t", format: "text", content: "q" }] }); const res = await app.inject({ method: "GET", url: "/sessions/s1/documents" }); expect(res.statusCode).toBe(200); expect(res.json()[0].key).toBe("question"); }); test("POST resume on a finalized session is refused with 409", async () => { const app = mutApp({ sessionShow: async () => ({ status: "finalized", archived: false }) }); const res = await app.inject({ method: "POST", url: "/sessions/s1/resume" }); expect(res.statusCode).toBe(409); }); test("POST resume on an archived session is refused with 409", async () => { const app = mutApp({ sessionShow: async () => ({ status: "open", archived: true }) }); const res = await app.inject({ method: "POST", url: "/sessions/s1/resume" }); expect(res.statusCode).toBe(409); }); test("POST /sessions refuses with 503 when ollamaEnsure fails (no session created)", async () => { let createdCalled = false; const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { thtRunner: { ollamaEnsure: async () => ({ ok: false, stage: "model", error: "modello non installato" }), searchPack: async () => {}, sessionNew: async () => { createdCalled = true; return { id: "s1" }; }, } as any, getSettings: () => ({ workspace: "psd" }) as any, spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any, }); const res = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); expect(res.statusCode).toBe(503); expect(res.json().error).toContain("non installato"); expect(createdCalled).toBe(false); }); test("POST /sessions proceeds when ollamaEnsure succeeds", async () => { let ensureWs: string | undefined; const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { thtRunner: { ollamaEnsure: async (ws: string) => { ensureWs = ws; return { ok: true }; }, searchPack: async () => {}, sessionNew: async () => ({ id: "s1" }), } as any, getSettings: () => ({ workspace: "psd" }) as any, spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any, }); const res = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); expect(res.json()).toEqual({ id: "s1" }); expect(ensureWs).toBe("psd"); }); test("POST /sessions/:id/resume returns 409 for a read-only session without calling ollamaEnsure", async () => { let ensureCalled = false; const app = mutApp({ sessionShow: async () => ({ status: "finalized", archived: false }), ollamaEnsure: async () => { ensureCalled = true; return { ok: false, error: "down" }; }, }); const res = await app.inject({ method: "POST", url: "/sessions/s1/resume" }); expect(res.statusCode).toBe(409); expect(ensureCalled).toBe(false); }); test("POST /sessions/:id/resume refuses with 503 when ollamaEnsure fails", async () => { const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { thtRunner: { ollamaEnsure: async () => ({ ok: false, error: "Ollama down" }), sessionShow: async () => ({ status: "open", archived: false }), } as any, getSettings: () => ({ workspace: "psd" }) as any, spawnFn: () => nodeSpawn("node", [FAKE, SCRIPT]) as any, }); const res = await app.inject({ method: "POST", url: "/sessions/s1/resume" }); expect(res.statusCode).toBe(503); }); test("POST /runtime/prewarm returns 202 without awaiting readiness", async () => { let workspace: string | undefined; let finish!: (value: any) => void; const pending = new Promise((resolve) => { finish = resolve; }); const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { thtRunner: {} as any, readiness: { ensure: (ws: string) => { workspace = ws; return pending; }, } as any, getSettings: () => ({ workspace: "psd" }) as any, }); const res = await app.inject({ method: "POST", url: "/runtime/prewarm" }); expect(res.statusCode).toBe(202); expect(res.json()).toEqual({ status: "warming" }); expect(workspace).toBe("psd"); finish({ ok: true }); }); test("POST /sessions returns after bridge attachment but starts only after retrieval", async () => { let finishPack!: () => void; const pack = new Promise((resolve) => { finishPack = resolve; }); let bridgeAttached = false; let started = false; const bridge = { onClientEvent: () => { bridgeAttached = true; }, emitClientEvent: () => {}, }; const runtime = { bridge } as any; const mgr = { createFor: () => runtime, configure: async () => {}, start: () => { expect(bridgeAttached).toBe(true); started = true; }, teardown: () => {}, } as any; const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { mgr, thtRunner: { ollamaEnsure: async () => ({ ok: true }), sessionNew: async () => ({ id: "s-early" }), searchPack: async () => pack, } as any, getSettings: () => ({ workspace: "psd" }) as any, }); const res = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" } }); expect(res.json()).toEqual({ id: "s-early" }); expect(bridgeAttached).toBe(true); expect(started).toBe(false); finishPack(); await new Promise((resolve) => setImmediate(resolve)); expect(started).toBe(true); }); test("POST /sessions bootstrap failure emits only a fixed recovery message", async () => { const published: Array<{ event: string; data: any }> = []; let listener: ((event: any) => void) | undefined; const bridge = { onClientEvent: (callback: (event: any) => void) => { listener = callback; }, emitClientEvent: (event: any) => listener?.(event), }; const runtime = { bridge } as any; const rawFailure = "connect https://secret.invalid/bootstrap?token=DO_NOT_LEAK using /srv/private/model-key"; const app = buildApp(loadConfig({ THT_HARNESS_DIR: "../harness" }), { mgr: { createFor: () => runtime, configure: async () => { throw new Error(rawFailure); }, start: () => {}, teardown: () => {}, } as any, hub: { publish: (_id: string, event: string, data: any) => published.push({ event, data }), } as any, thtRunner: { ollamaEnsure: async () => ({ ok: true }), sessionNew: async () => ({ id: "s-bootstrap" }), searchPack: async () => {}, failSession: async () => {}, } as any, getSettings: () => ({ workspace: "psd" }) as any, }); const response = await app.inject({ method: "POST", url: "/sessions", payload: { question: "q" }, }); await new Promise((resolve) => setImmediate(resolve)); expect(response.json()).toEqual({ id: "s-bootstrap" }); expect(published.map(({ data }) => data)).toContainEqual({ type: "info", level: "error", text: "Session startup failed. Check configuration and connectivity, then Resume the session.", }); const clientOutput = JSON.stringify(published); expect(clientOutput).not.toContain("secret.invalid"); expect(clientOutput).not.toContain("DO_NOT_LEAK"); expect(clientOutput).not.toContain("/srv/private/model-key"); });