| 1 | import { test } from "node:test"; |
| 2 | import assert from "node:assert/strict"; |
| 3 | import fs from "node:fs"; |
| 4 | import os from "node:os"; |
| 5 | import path from "node:path"; |
| 6 | import { spawn } from "node:child_process"; |
| 7 | import { fileURLToPath } from "node:url"; |
| 8 | import { setTimeout as delay } from "node:timers/promises"; |
| 9 | import { Duplex } from "node:stream"; |
| 10 | import { appRequest } from "../src/app-socket.mjs"; |
| 11 | |
| 12 | function controlClient(stream, { timeoutMs = 5_000, signal, diagnostics = () => "" } = {}) { |
| 13 | let seq = 0, buffer = "", failure; |
| 14 | const pending = new Map(); |
| 15 | const fail = message => { |
| 16 | if (failure) return; |
| 17 | failure = new Error(`FD3 control: ${message}${diagnostics() ? `\n${diagnostics()}` : ""}`); |
| 18 | for (const { reject, timer } of pending.values()) { clearTimeout(timer); reject(failure); } |
| 19 | pending.clear(); |
| 20 | stream.destroy(); |
| 21 | }; |
| 22 | stream.setEncoding("utf8"); |
| 23 | stream.on("error", error => fail(error.message)); |
| 24 | stream.on("close", () => fail("channel closed before a reply")); |
| 25 | stream.on("end", () => fail("channel ended before a reply")); |
| 26 | const abort = () => fail("test cancelled"); |
| 27 | signal?.addEventListener("abort", abort, { once: true }); |
| 28 | stream.once("close", () => signal?.removeEventListener("abort", abort)); |
| 29 | if (signal?.aborted) abort(); |
| 30 | stream.on("data", chunk => { |
| 31 | buffer += chunk; |
| 32 | if (buffer.length > 8192) return fail("reply exceeds 8192 bytes"); |
| 33 | let newline; |
| 34 | while ((newline = buffer.indexOf("\n")) >= 0) { |
| 35 | const line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1); |
| 36 | let state; |
| 37 | try { state = JSON.parse(line); } catch { return fail("malformed JSON reply"); } |
| 38 | if (!state || typeof state !== "object") return fail("malformed control state"); |
| 39 | const waiting = pending.get(state.id); |
| 40 | if (!waiting) continue; |
| 41 | if (state.error) return fail(`${waiting.command} failed: ${state.error}`); |
| 42 | clearTimeout(waiting.timer); pending.delete(state.id); waiting.resolve(state); |
| 43 | } |
| 44 | }); |
| 45 | return command => { |
| 46 | if (failure) return Promise.reject(failure); |
| 47 | const id = ++seq; |
| 48 | return new Promise((resolve, reject) => { |
| 49 | const timer = setTimeout(() => fail(`${command} timed out after ${timeoutMs}ms`), timeoutMs); |
| 50 | pending.set(id, { command, resolve, reject, timer }); |
| 51 | try { stream.write(JSON.stringify({ id, command }) + "\n", error => { if (error) fail(error.message); }); } |
| 52 | catch (error) { fail(error.message); } |
| 53 | }); |
| 54 | }; |
| 55 | } |
| 56 | |
| 57 | const root = fileURLToPath(new URL("../", import.meta.url)); |
| 58 | test("human Pause and Stop cannot be bypassed; a lost owner exits and can reopen stopped", { timeout: 20_000 }, async t => { |
| 59 | const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cu-control-")); |
| 60 | const log = path.join(dir, "calls.jsonl"); |
| 61 | const endpoint = process.platform === "win32" |
| 62 | ? `\\\\.\\pipe\\cu-control-${process.pid}-${path.basename(dir)}` |
| 63 | : path.join(dir, "app.sock"); |
| 64 | const daemonOptions = { env: { ...process.env, |
| 65 | CODEWHALE_CU_STATE_DIR: dir, CODEWHALE_CU_APP_SOCKET: endpoint, CODEWHALE_CU_APP_WARM: "off", |
| 66 | CODEWHALE_CU_TEST_BACKEND: path.join(root, "tests/fixtures/session-backend.mjs"), CU_SESSION_CALLS: log, CODEWHALE_CU_CONTROL_FD: "3" }, stdio: ["ignore", "ignore", "pipe", "overlapped"] }; |
| 67 | let errors = "", daemon, exited; |
| 68 | function launch() { |
| 69 | daemon = spawn(process.execPath, [path.join(root, "app/daemon.mjs")], daemonOptions); |
| 70 | daemon.stderr.on("data", chunk => { errors += chunk; }); |
| 71 | exited = new Promise(resolve => { daemon.once("exit", resolve); daemon.once("error", error => { errors += error.message; resolve(); }); }); |
| 72 | } |
| 73 | launch(); |
| 74 | const sockets = []; |
| 75 | const previousSocket = process.env.CODEWHALE_CU_APP_SOCKET; |
| 76 | process.env.CODEWHALE_CU_APP_SOCKET = endpoint; |
| 77 | t.after(async () => { |
| 78 | if (previousSocket === undefined) delete process.env.CODEWHALE_CU_APP_SOCKET; |
| 79 | else process.env.CODEWHALE_CU_APP_SOCKET = previousSocket; |
| 80 | sockets.forEach(socket => socket.destroy()); daemon.stdio[3].destroy(); |
| 81 | let deadline; |
| 82 | const forceKill = setTimeout(() => daemon.kill("SIGKILL"), 3_000); |
| 83 | try { |
| 84 | if (daemon.exitCode === null && daemon.signalCode === null) daemon.kill("SIGTERM"); |
| 85 | await Promise.race([exited, new Promise((_, reject) => { deadline = setTimeout(() => reject(new Error("Daemon did not exit after SIGKILL")), 4_000); })]); |
| 86 | } finally { clearTimeout(forceKill); clearTimeout(deadline); fs.rmSync(dir, { recursive: true, force: true }); } |
| 87 | }); |
| 88 | async function until(predicate) { for(let i=0;i<250;i++) { if(predicate()) return; if (daemon.exitCode !== null || daemon.signalCode !== null) throw new Error(`Daemon exited: ${errors}`); await delay(20, undefined, { signal: t.signal }); } throw new Error(`Timed out: ${errors}`); } |
| 89 | // Named pipes on Windows have no filesystem entry; both transports publish |
| 90 | // the same run receipt only after the listener is ready. |
| 91 | await until(() => fs.existsSync(path.join(dir, "app-run.json"))); |
| 92 | function request(payload, keepOpen = false) { |
| 93 | return appRequest(payload, { keepOpen, timeoutMs: 5_000, signal: t.signal }).then(result => { |
| 94 | if (!keepOpen) return result; |
| 95 | sockets.push(result.socket); return result.reply; |
| 96 | }); |
| 97 | } |
| 98 | const control = controlClient(daemon.stdio[3], { signal: t.signal, diagnostics: () => errors + (fs.existsSync(log) ? fs.readFileSync(log,"utf8") : "") }); |
| 99 | assert.equal((await control("status")).mode, "ready", "human-control channel responds before input starts"); |
| 100 | assert.equal((await request({tool:"hello"})).app.controlOwner,true); |
| 101 | const sessionId="human-controls"; |
| 102 | const { leaseToken }=await request({tool:"open_session",sessionId},true); |
| 103 | const call=(tool,args={})=>request({tool,args,sessionId,leaseToken}); |
| 104 | assert.equal((await call("get_app_state",{app_ref:{name:"Practice"}})).ok,true); |
| 105 | const held=call("hold_key",{text:"must be cancelled"}); |
| 106 | held.catch(() => {}); // The result is asserted below; avoid orphan rejections if control fails first. |
| 107 | await until(()=>fs.existsSync(log)&&fs.readFileSync(log,"utf8").includes("child_started")); |
| 108 | const queued=call("type",{text:"must not replay"}); |
| 109 | queued.catch(() => {}); |
| 110 | t.diagnostic("control while input runs: " + JSON.stringify(await control("status"))); |
| 111 | const pausing = control("pause"); pausing.catch(() => {}); |
| 112 | await delay(200); |
| 113 | t.diagnostic("control after pause: " + JSON.stringify(await control("status"))); |
| 114 | const paused=await pausing; |
| 115 | assert.equal(paused.mode,"paused"); assert.equal(paused.cleanupPending,false); |
| 116 | assert.equal((await held).ok,false); assert.equal((await queued).ok,false); |
| 117 | assert.equal((await call("type",{text:"while paused"})).error.code,"control_paused"); |
| 118 | for(const tool of ["resume","set_control_mode","control","updates"]) assert.equal((await call(tool)).error.code,"tool_not_allowed"); |
| 119 | assert.equal((await control("resume")).mode,"ready"); |
| 120 | assert.equal((await call("type",{text:"allowed again"})).ok,true); |
| 121 | assert.equal((await control("stop")).mode,"stopped"); |
| 122 | await control("resume"); |
| 123 | assert.equal((await call("type",{text:"old stopped owner"})).error.code,"control_stopped"); |
| 124 | const records=fs.readFileSync(log,"utf8").trim().split("\n").map(JSON.parse); |
| 125 | assert.ok(records.some(record=>record.method==="child_released")); |
| 126 | assert.deepEqual(records.filter(record=>record.method==="type").map(record=>record.text),["allowed again"]); |
| 127 | // Owner loss must release input and retire the listener, so relaunching |
| 128 | // restores the menu controls without silently authorizing new input. |
| 129 | daemon.stdio[3].destroy(); |
| 130 | await until(() => daemon.exitCode !== null); |
| 131 | assert.equal(daemon.exitCode,0,errors); |
| 132 | assert.equal(JSON.parse(fs.readFileSync(path.join(dir,"control.json"))).mode,"stopped"); |
| 133 | assert.equal(fs.existsSync(path.join(dir,"app-run.json")),false); |
| 134 | await assert.rejects(request({tool:"hello"}),error=>error.code==="app_unavailable"); |
| 135 | launch(); |
| 136 | await until(() => fs.existsSync(path.join(dir,"app-run.json"))); |
| 137 | const reopened = controlClient(daemon.stdio[3], { signal: t.signal, diagnostics: () => errors + (fs.existsSync(log) ? fs.readFileSync(log,"utf8") : "") }); |
| 138 | assert.equal((await reopened("status")).mode,"stopped"); |
| 139 | assert.equal((await request({tool:"hello"})).app.controlOwner,true); |
| 140 | const fresh=await request({tool:"open_session",sessionId:"fresh"},true); |
| 141 | assert.equal((await request({tool:"get_app_state",sessionId:"fresh",leaseToken:fresh.leaseToken})).error.code,"control_stopped"); |
| 142 | assert.equal((await reopened("resume")).mode,"ready"); |
| 143 | assert.equal((await request({tool:"get_app_state",args:{app_ref:{name:"Reopened"}},sessionId:"fresh",leaseToken:fresh.leaseToken})).ok,true); |
| 144 | assert.equal((await call("type",{text:"old lease after reopen"})).error.code,"session_owner_required"); |
| 145 | }); |
| 146 | |
| 147 | test("silent FD3 peer rejects every pending command and closes the channel", { timeout: 2_000 }, async () => { |
| 148 | const stream = new Duplex({ read() {}, write(_chunk, _encoding, done) { done(); } }); |
| 149 | const control = controlClient(stream, { timeoutMs: 30, diagnostics: () => "fixture daemon stderr" }); |
| 150 | const results = await Promise.allSettled([control("pause"), control("status")]); |
| 151 | for (const result of results) { |
| 152 | assert.equal(result.status, "rejected"); |
| 153 | assert.match(result.reason.message, /pause timed out after 30ms\nfixture daemon stderr/); |
| 154 | } |
| 155 | assert.equal(stream.destroyed, true); |
| 156 | await assert.rejects(control("resume"), /timed out/); |
| 157 | }); |
| 158 | |
| 159 | for (const [name, respond, expected] of [ |
| 160 | ["EOF", stream => stream.push(null), /channel ended/], |
| 161 | ["close", stream => stream.destroy(), /channel closed/], |
| 162 | ["error", stream => stream.destroy(new Error("broken pipe")), /broken pipe/], |
| 163 | ["invalid JSON", stream => stream.push("not json\n"), /malformed JSON/], |
| 164 | ["invalid state", stream => stream.push("null\n"), /malformed control state/], |
| 165 | ["oversized reply", stream => stream.push("x".repeat(8193)), /exceeds 8192/], |
| 166 | ["command failure", stream => stream.push('{"id":1,"error":"disk full"}\n'), /pause failed: disk full/], |
| 167 | ]) { |
| 168 | test(`FD3 ${name} rejects a waiting control command`, { timeout: 2_000 }, async () => { |
| 169 | const stream = new Duplex({ read() {}, write(_chunk, _encoding, done) { done(); queueMicrotask(() => respond(this)); } }); |
| 170 | const control = controlClient(stream); |
| 171 | await assert.rejects(control("pause"), expected); |
| 172 | assert.equal(stream.destroyed, true); |
| 173 | }); |
| 174 | } |
| 175 | |
| 176 | test("FD3 test cancellation rejects pending commands", { timeout: 2_000 }, async () => { |
| 177 | const stream = new Duplex({ read() {}, write(_chunk, _encoding, done) { done(); } }); |
| 178 | const abort = new AbortController(); |
| 179 | const control = controlClient(stream, { signal: abort.signal }); |
| 180 | const rejected = assert.rejects(control("pause"), /test cancelled/); |
| 181 | abort.abort(); await rejected; |
| 182 | assert.equal(stream.destroyed, true); |
| 183 | }); |
| 184 | |
| 185 | test("FD3 matches fragmented replies to their command IDs", { timeout: 2_000 }, async () => { |
| 186 | const requests = []; |
| 187 | const stream = new Duplex({ read() {}, write(chunk, _encoding, done) { requests.push(JSON.parse(chunk)); done(); } }); |
| 188 | const control = controlClient(stream); |
| 189 | const replies = Promise.all([control("status"), control("pause")]); |
| 190 | stream.push('{"id":2,"mode":"pau'); |
| 191 | stream.push('sed"}\n{"id":1,"mode":"ready"}\n'); |
| 192 | assert.deepEqual(await replies, [{ id: 1, mode: "ready" }, { id: 2, mode: "paused" }]); |
| 193 | assert.deepEqual(requests.map(request => request.command), ["status", "pause"]); |
| 194 | stream.destroy(); |
| 195 | }); |
| 196 |