import assert from "node:assert/strict" import test from "node:test" import ts from "typescript" import { readFile } from "node:fs/promises" import vm from "node:vm" async function loadSetupAPI(request) { const source = await readFile(new URL("./setup-readiness.ts", import.meta.url), "utf8") const compiled = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2017, module: ts.ModuleKind.CommonJS }, fileName: "setup-readiness.ts", }) const sandbox = { exports: {}, module: { exports: {} }, require(name) { assert.equal(name, "@/lib/api/client") return { request } }, } sandbox.exports = sandbox.module.exports vm.runInNewContext(compiled.outputText, sandbox) return sandbox.module.exports } test("simulation normalizes null or absent arrays from older servers", async () => { for (const response of [{ candidate_operators: null, hops: null }, {}]) { const api = await loadSetupAPI(async () => response) const result = await api.simulateSetupRoute({ channel_id: 7 }) assert.equal(Array.isArray(result.candidate_operators), true) assert.equal(result.candidate_operators.length, 0) assert.equal(Array.isArray(result.hops), true) assert.equal(result.hops.length, 0) } }) test("simulation preserves returned candidates", async () => { const candidates = [{ user_id: 17, display_name: "Operator", eligible: true }] const api = await loadSetupAPI(async () => ({ candidate_operators: candidates, hops: [] })) const result = await api.simulateSetupRoute({ channel_id: 7 }) assert.equal(result.candidate_operators, candidates) }) test("quick fix preview does not manufacture apply intent", async () => { const calls = [] const api = await loadSetupAPI(async (url, options) => { calls.push({ url, body: JSON.parse(options.body) }) return { applied: false, changes: [], preview_token: "reviewed" } }) await api.applySetupQuickFix({ action: "fix_ai_agent_handoff", entity_id: 17 }) assert.equal(calls[0].url, "/api/dashboard/setup/quick_fix") assert.equal(calls[0].body.entity_id, 17) assert.equal("apply" in calls[0].body, false) assert.equal("preview_token" in calls[0].body, false) }) test("explicit apply carries the reviewed target and fingerprint", async () => { let sent const api = await loadSetupAPI(async (_url, options) => { sent = JSON.parse(options.body) return { applied: true, changes: [], applied_actions: [] } }) await api.applySetupQuickFix({ action: "fix_ai_agent_handoff", entity_id: 17, apply: true, preview_token: "current-preview" }) assert.equal(sent.apply, true) assert.equal(sent.entity_id, 17) assert.equal(sent.preview_token, "current-preview") })