1 -import assert from "node:assert/strict";
2 -import { execFile, spawn } from "node:child_process";
3 -import crypto from "node:crypto";
4 -import fs from "node:fs";
5 -import http from "node:http";
6 -import os from "node:os";
7 -import path from "node:path";
8 -import test from "node:test";
9 -import { promisify } from "node:util";
10 -import { OPCODES } from "./server.mjs";
12 -const execFileAsync = promisify(execFile);
13 -const scriptDir = import.meta.dirname;
15 -async function runNode(script, args = [], options = {}) {
16 - return execFileAsync(
18 - [path.join(scriptDir, script), ...args],
20 - timeout: options.timeout ?? 10_000,
21 - maxBuffer: 1024 * 1024,
22 - env: { ...process.env, ...(options.env ?? {}) },
27 -function tmpProject() {
28 - return fs.mkdtempSync(path.join(os.tmpdir(), "brainstorm-companion-"));
31 -async function start(projectDir) {
32 - const first = path.join(projectDir, "first.html");
33 - fs.writeFileSync(first, "<h2>Ready</h2>");
34 - const { stdout } = await runNode("companion.mjs", [
43 - const info = JSON.parse(stdout.trim());
46 - session_dir: info.session_dir ?? path.dirname(info.screen_dir),
50 -async function stop(sessionDir) {
51 - return runNode("companion.mjs", ["stop", sessionDir]).catch(() => {});
54 -async function withSession(fn) {
55 - const projectDir = tmpProject();
58 - info = await start(projectDir);
59 - await fn(info, projectDir);
61 - if (info) await stop(info.session_dir);
62 - fs.rmSync(projectDir, { recursive: true, force: true });
66 -function encodeClientTextFrame(value) {
67 - const payload = Buffer.from(JSON.stringify(value));
68 - const header = payload.length < 126 ? Buffer.alloc(2) : Buffer.alloc(4);
69 - header[0] = 0x80 | OPCODES.TEXT;
70 - if (payload.length < 126) header[1] = 0x80 | payload.length;
72 - header[1] = 0x80 | 126;
73 - header.writeUInt16BE(payload.length, 2);
75 - const mask = crypto.randomBytes(4);
76 - const masked = Buffer.alloc(payload.length);
77 - for (let i = 0; i < payload.length; i++) masked[i] = payload[i] ^ mask[i % 4];
78 - return Buffer.concat([header, mask, masked]);
81 -function decodeServerTextFrame(buffer) {
82 - if (buffer.length < 2) return null;
83 - const opcode = buffer[0] & 0x0f;
84 - let payloadLen = buffer[1] & 0x7f;
86 - if (payloadLen === 126) {
87 - if (buffer.length < 4) return null;
88 - payloadLen = buffer.readUInt16BE(2);
91 - const end = offset + payloadLen;
92 - if (buffer.length < end) return null;
93 - return { opcode, payload: buffer.subarray(offset, end) };
96 -function wsSendText(port, event) {
97 - return new Promise((resolve, reject) => {
98 - const key = crypto.randomBytes(16).toString("base64");
99 - const req = http.request({
103 - Connection: "Upgrade",
104 - Upgrade: "websocket",
105 - "Sec-WebSocket-Version": "13",
106 - "Sec-WebSocket-Key": key,
110 - req.on("upgrade", (_res, socket) => {
111 - socket.write(encodeClientTextFrame(event));
117 - req.on("error", reject);
122 -function wsListenForReload(port) {
123 - return new Promise((resolve, reject) => {
124 - const key = crypto.randomBytes(16).toString("base64");
125 - const req = http.request({
129 - Connection: "Upgrade",
130 - Upgrade: "websocket",
131 - "Sec-WebSocket-Version": "13",
132 - "Sec-WebSocket-Key": key,
136 - req.on("upgrade", (_res, socket) => {
137 - let buffer = Buffer.alloc(0);
138 - socket.on("data", (chunk) => {
139 - buffer = Buffer.concat([buffer, chunk]);
140 - const frame = decodeServerTextFrame(buffer);
141 - if (frame?.opcode === OPCODES.TEXT) {
143 - resolve(JSON.parse(frame.payload.toString()));
147 - req.on("error", reject);
149 - () => reject(new Error("timed out waiting for reload")),
156 -test("visual companion launchers are pure Node scripts", () => {
157 - assert.equal(fs.existsSync(path.join(scriptDir, "companion.mjs")), true);
158 - assert.equal(fs.existsSync(path.join(scriptDir, "start-server.mjs")), true);
159 - assert.equal(fs.existsSync(path.join(scriptDir, "stop-server.mjs")), true);
160 - assert.equal(fs.existsSync(path.join(scriptDir, "start-server.sh")), false);
161 - assert.equal(fs.existsSync(path.join(scriptDir, "stop-server.sh")), false);
164 -test("internal start-server CLI is rejected to avoid empty browser sessions", async () => {
165 - await assert.rejects(
166 - runNode("start-server.mjs", ["--project-dir", tmpProject()]),
168 - assert.match(error.stdout, /start-server\.mjs is internal/);
169 - assert.match(error.stdout, /start-choice/);
175 -test("human-agent workflow: script renders choices, UI event arrives while agent waits", async () => {
176 - await withSession(async (info) => {
177 - await runNode("companion.mjs", [
185 - "Pick one direction",
187 - "a|Small|Minimal change",
189 - "b|Large|Broad redesign",
192 - const html = await (await fetch(info.url)).text();
193 - assert.match(html, /Which approach\?/);
194 - assert.match(html, /data-choice="a"/);
195 - assert.match(html, /Minimal change/);
196 - assert.match(html, /window\.toggleSelect = \(el\) => \{/);
198 - const waiting = runNode("companion.mjs", [
204 - await wsSendText(info.port, {
210 - const result = JSON.parse((await waiting).stdout.trim());
212 - assert.equal(result.choice, "b");
213 - assert.equal(result.text, "Large");
214 - assert.equal(result.id, "option-b");
218 -test("companion has help for deterministic workflow commands", async () => {
219 - const { stdout } = await runNode("companion.mjs", ["--help"]);
220 - assert.match(stdout, /start-choice/);
221 - assert.match(stdout, /start-screen/);
222 - assert.match(stdout, /open-choice/);
223 - assert.match(stdout, /open-screen/);
224 - assert.match(stdout, /ask-choice/);
225 - assert.match(stdout, /ask-screen/);
226 - assert.match(stdout, /--html-file/);
227 - assert.match(stdout, /cleanup/);
228 - assert.doesNotMatch(stdout, /\n {2}start --project-dir/);
231 -test("companion start without a first screen is rejected", async () => {
232 - await assert.rejects(
233 - runNode("companion.mjs", ["start", "--project-dir", tmpProject()]),
235 - assert.match(error.stdout, /Use start-choice or start-screen/);
241 -test("start-choice starts server with first browser screen already loaded", async () => {
242 - const projectDir = tmpProject();
246 - const { stdout } = await runNode("companion.mjs", [
253 - "First visual question",
255 - "Browser must not show waiting page",
257 - "a|Left rail|Tree on left",
259 - "b|Graph first|Session graph center",
261 - const info = JSON.parse(stdout.trim());
262 - sessionDir = info.session_dir;
264 - assert.equal(info.type, "server-started");
265 - assert.match(info.url, /^http:\/\/localhost:\d+$/);
266 - assert.equal(fs.existsSync(info.screen_file), true);
268 - const html = await (await fetch(info.url)).text();
269 - assert.match(html, /First visual question/);
270 - assert.match(html, /Browser must not show waiting page/);
271 - assert.match(html, /data-choice="b"/);
272 - assert.doesNotMatch(html, /Waiting for the agent to push a screen/);
274 - if (sessionDir) await stop(sessionDir);
275 - fs.rmSync(projectDir, { recursive: true, force: true });
279 -test("start-screen starts server with first custom HTML screen already loaded", async () => {
280 - const projectDir = tmpProject();
284 - const htmlFile = path.join(projectDir, "first.html");
285 - fs.writeFileSync(htmlFile, "<h2>First custom screen</h2>");
286 - const { stdout } = await runNode("companion.mjs", [
295 - const info = JSON.parse(stdout.trim());
296 - sessionDir = info.session_dir;
298 - assert.equal(fs.existsSync(info.screen_file), true);
299 - const html = await (await fetch(info.url)).text();
300 - assert.match(html, /First custom screen/);
301 - assert.doesNotMatch(html, /Waiting for the agent to push a screen/);
303 - if (sessionDir) await stop(sessionDir);
304 - fs.rmSync(projectDir, { recursive: true, force: true });
308 -test("visual wait commands reject slow timeouts above 30 seconds", async () => {
309 - const projectDir = tmpProject();
313 - const first = path.join(projectDir, "first.html");
314 - fs.writeFileSync(first, "<h2>Timeout Cap</h2>");
315 - const { stdout } = await runNode("companion.mjs", [
324 - sessionDir = JSON.parse(stdout.trim()).session_dir;
326 - await assert.rejects(
327 - runNode("companion.mjs", [
340 - assert.match(error.stdout, /--timeout-ms max is 30000ms/);
345 - if (sessionDir) await stop(sessionDir);
346 - fs.rmSync(projectDir, { recursive: true, force: true });
350 -test("open-choice starts with first screen, waits, and returns click without terminal reply", async () => {
351 - const projectDir = tmpProject();
355 - const asking = runNode(
362 - "first-open-choice",
364 - "Choose first layout",
366 - "map|Map|Mission map",
368 - "queue|Queue|Decision queue",
372 - { env: { BRAINSTORM_NO_OPEN: "1" } },
376 - for (let i = 0; i < 50; i++) {
377 - const files = fs.globSync(
378 - `${projectDir}/.super/brainstorm/*/state/server-info`,
380 - if (files.length) {
381 - info = JSON.parse(fs.readFileSync(files[0], "utf8"));
382 - sessionDir = path.dirname(info.screen_dir);
385 - await new Promise((resolve) => setTimeout(resolve, 50));
390 - for (let i = 0; i < 50; i++) {
391 - html = await (await fetch(info.url)).text();
392 - if (html.includes("Choose first layout")) break;
393 - await new Promise((resolve) => setTimeout(resolve, 50));
395 - assert.match(html, /Choose first layout/);
396 - assert.doesNotMatch(html, /Waiting for the agent to push a screen/);
398 - await wsSendText(info.port, {
402 - id: "option-queue",
404 - const result = JSON.parse((await asking).stdout.trim());
405 - assert.equal(result.choice, "queue");
406 - assert.equal(result.session_dir, sessionDir);
407 - assert.equal(result.url, info.url);
409 - if (sessionDir) await stop(sessionDir);
410 - fs.rmSync(projectDir, { recursive: true, force: true });
414 -test("open-screen starts with first custom screen, waits, and returns click", async () => {
415 - const projectDir = tmpProject();
419 - const htmlFile = path.join(projectDir, "open-screen.html");
422 - '<h2>Open custom</h2><div data-choice="x" onclick="toggleSelect(this)">X</div>',
424 - const asking = runNode(
437 - { env: { BRAINSTORM_NO_OPEN: "1" } },
441 - for (let i = 0; i < 50; i++) {
442 - const files = fs.globSync(
443 - `${projectDir}/.super/brainstorm/*/state/server-info`,
445 - if (files.length) {
446 - info = JSON.parse(fs.readFileSync(files[0], "utf8"));
447 - sessionDir = path.dirname(info.screen_dir);
450 - await new Promise((resolve) => setTimeout(resolve, 50));
455 - for (let i = 0; i < 50; i++) {
456 - html = await (await fetch(info.url)).text();
457 - if (html.includes("Open custom")) break;
458 - await new Promise((resolve) => setTimeout(resolve, 50));
460 - assert.match(html, /Open custom/);
461 - await wsSendText(info.port, {
467 - const result = JSON.parse((await asking).stdout.trim());
468 - assert.equal(result.choice, "x");
470 - if (sessionDir) await stop(sessionDir);
471 - fs.rmSync(projectDir, { recursive: true, force: true });
475 -test("ask-choice writes a choice screen and returns the browser click without terminal reply", async () => {
476 - await withSession(async (info) => {
477 - const asking = runNode("companion.mjs", [
485 - "No terminal reply needed",
487 - "fast|Fast|Shortest path",
489 - "deep|Deep|More detail",
494 - for (let i = 0; i < 50; i++) {
495 - const html = await (await fetch(info.url)).text();
496 - if (html.includes("Pick a mode") && html.includes('data-choice="deep"'))
498 - await new Promise((resolve) => setTimeout(resolve, 50));
501 - await wsSendText(info.port, {
507 - const result = JSON.parse((await asking).stdout.trim());
509 - assert.equal(result.choice, "deep");
510 - assert.equal(result.text, "Deep");
511 - assert.equal(result.id, "option-deep");
515 -test("ask-screen reads custom HTML from file and returns browser click without shell quoting", async () => {
516 - await withSession(async (info, projectDir) => {
517 - const htmlFile = path.join(projectDir, "mockups.html");
521 -<h2>Custom mockups</h2>
523 - <div class="card" data-choice="a" onclick="toggleSelect(this)"><div class="card-body"><h3>A</h3><p>Alpha</p></div></div>
524 - <div class="card" data-choice="b" onclick="toggleSelect(this)"><div class="card-body"><h3>B</h3><p>Beta</p></div></div>
529 - const asking = runNode("companion.mjs", [
540 - for (let i = 0; i < 50; i++) {
541 - const html = await (await fetch(info.url)).text();
542 - if (html.includes("Custom mockups") && html.includes('data-choice="b"'))
544 - await new Promise((resolve) => setTimeout(resolve, 50));
547 - await wsSendText(info.port, {
553 - const result = JSON.parse((await asking).stdout.trim());
554 - assert.equal(result.choice, "b");
555 - assert.equal(result.text, "B Beta");
559 -test("write-screen reads custom HTML from file", async () => {
560 - await withSession(async (info, projectDir) => {
561 - const htmlFile = path.join(projectDir, "screen.html");
562 - fs.writeFileSync(htmlFile, "<h2>File Screen</h2>");
563 - await runNode("companion.mjs", [
571 - assert.match(await (await fetch(info.url)).text(), /File Screen/);
575 -test("scripted workflow supports waiting screen, event listing, clearing, and per-screen event reset", async () => {
576 - await withSession(async (info) => {
577 - await runNode("companion.mjs", [
587 - await wsSendText(info.port, { type: "click", choice: "a", text: "Alpha" });
589 - const listed = JSON.parse(
591 - await runNode("companion.mjs", ["events", info.session_dir])
594 - assert.equal(listed.length, 1);
595 - assert.equal(listed[0].choice, "a");
597 - await runNode("companion.mjs", [
610 - await runNode("companion.mjs", ["events", info.session_dir])
616 - await wsSendText(info.port, { type: "click", choice: "b", text: "Beta" });
620 - await runNode("companion.mjs", [
632 - await runNode("companion.mjs", ["events", info.session_dir])
638 - await runNode("companion.mjs", [
644 - const html = await (await fetch(info.url)).text();
645 - assert.match(html, /Continuing in terminal/);
649 -test("browser gets reload when agent pushes a new screen", async () => {
650 - await withSession(async (info) => {
651 - const reload = wsListenForReload(info.port);
652 - await runNode("companion.mjs", [
662 - assert.deepEqual(await reload, { type: "reload" });
666 -test("server serves wrapped fragments, full documents, and content assets", async () => {
667 - await withSession(async (info) => {
668 - await runNode("companion.mjs", [
674 - "<h2>Fragment</h2>",
676 - const fragment = await (await fetch(info.url)).text();
677 - assert.match(fragment, /Super Brainstorming/);
678 - assert.match(fragment, /<h2>Fragment<\/h2>/);
680 - await runNode("companion.mjs", [
686 - "<!DOCTYPE html><html><body><main>Full Doc</main></body></html>",
688 - const full = await (await fetch(info.url)).text();
689 - assert.doesNotMatch(full, /Super Brainstorming/);
690 - assert.match(full, /<main>Full Doc<\/main>/);
691 - assert.match(full, /const WS_URL/);
693 - fs.writeFileSync(path.join(info.screen_dir, "asset.json"), '{"ok":true}');
694 - const asset = await fetch(`${info.url}/files/asset.json`);
695 - assert.equal(asset.headers.get("content-type"), "application/json");
696 - assert.deepEqual(await asset.json(), { ok: true });
700 -test("cleanup stops servers whose owner pid is gone", async () => {
701 - const projectDir = tmpProject();
706 - const first = path.join(projectDir, "first.html");
707 - fs.writeFileSync(first, "<h2>Owned</h2>");
710 - ["-e", "console.log(process.pid); setInterval(() => {}, 1000);"],
711 - { stdio: ["ignore", "pipe", "ignore"] },
713 - const ownerPid = await new Promise((resolve) =>
714 - owner.stdout.once("data", (chunk) =>
715 - resolve(Number(chunk.toString().trim())),
718 - assert.equal(Number.isInteger(ownerPid), true);
720 - const { stdout } = await runNode("companion.mjs", [
731 - const info = JSON.parse(stdout.trim());
732 - sessionDir = info.session_dir;
734 - owner.kill("SIGTERM");
735 - await new Promise((resolve) => owner.once("exit", resolve));
737 - const cleaned = JSON.parse(
738 - (await runNode("companion.mjs", ["cleanup"])).stdout.trim(),
740 - assert.equal(cleaned.stopped.length, 1);
741 - assert.equal(cleaned.stopped[0].session_dir, sessionDir);
742 - assert.equal(cleaned.stopped[0].reason, "owner_dead");
744 - fs.existsSync(path.join(sessionDir, "state", "server.pid")),
748 - if (owner && owner.exitCode === null) owner.kill("SIGTERM");
749 - if (sessionDir) await stop(sessionDir);
750 - fs.rmSync(projectDir, { recursive: true, force: true });
754 -test("server exits after browser disconnect timeout", async () => {
755 - const projectDir = tmpProject();
759 - const first = path.join(projectDir, "first.html");
760 - fs.writeFileSync(first, "<h2>Disconnect</h2>");
761 - const { stdout } = await runNode("companion.mjs", [
765 - "--no-browser-timeout-ms",
772 - const info = JSON.parse(stdout.trim());
773 - sessionDir = info.session_dir;
775 - await new Promise((resolve, reject) => {
776 - const key = crypto.randomBytes(16).toString("base64");
777 - const req = http.request({
781 - Connection: "Upgrade",
782 - Upgrade: "websocket",
783 - "Sec-WebSocket-Version": "13",
784 - "Sec-WebSocket-Key": key,
787 - req.on("upgrade", (_res, socket) => {
791 - req.on("error", reject);
795 - const stoppedFile = path.join(sessionDir, "state", "server-stopped");
796 - for (let i = 0; i < 50 && !fs.existsSync(stoppedFile); i++)
797 - await new Promise((resolve) => setTimeout(resolve, 50));
798 - assert.equal(fs.existsSync(stoppedFile), true);
799 - assert.match(fs.readFileSync(stoppedFile, "utf8"), /no browser clients/);
801 - if (sessionDir) await stop(sessionDir);
802 - fs.rmSync(projectDir, { recursive: true, force: true });
806 -test("server module exports websocket helpers without side effects", async () => {
807 - const server = await import("./server.mjs");
808 - assert.deepEqual(Object.keys(server).sort(), [
810 - "computeAcceptKey",