1 +import assert from 'node:assert/strict';
2 +import crypto from 'node:crypto';
3 +import fs from 'node:fs';
4 +import http from 'node:http';
5 +import os from 'node:os';
6 +import path from 'node:path';
7 +import { execFile, spawn } from 'node:child_process';
8 +import { promisify } from 'node:util';
9 +import test from 'node:test';
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(process.execPath, [path.join(scriptDir, script), ...args], {
17 + timeout: options.timeout ?? 10_000,
18 + maxBuffer: 1024 * 1024,
19 + env: { ...process.env, ...(options.env ?? {}) },
23 +function tmpProject() {
24 + return fs.mkdtempSync(path.join(os.tmpdir(), 'brainstorm-companion-'));
27 +async function start(projectDir) {
28 + const first = path.join(projectDir, 'first.html');
29 + fs.writeFileSync(first, '<h2>Ready</h2>');
30 + const { stdout } = await runNode('companion.mjs', ['start-screen', '--project-dir', projectDir, '--name', 'ready', '--html-file', first]);
31 + const info = JSON.parse(stdout.trim());
32 + return { ...info, session_dir: info.session_dir ?? path.dirname(info.screen_dir) };
35 +async function stop(sessionDir) {
36 + return runNode('companion.mjs', ['stop', sessionDir]).catch(() => {});
39 +async function withSession(fn) {
40 + const projectDir = tmpProject();
43 + info = await start(projectDir);
44 + await fn(info, projectDir);
46 + if (info) await stop(info.session_dir);
47 + fs.rmSync(projectDir, { recursive: true, force: true });
51 +function encodeClientTextFrame(value) {
52 + const payload = Buffer.from(JSON.stringify(value));
53 + const header = payload.length < 126 ? Buffer.alloc(2) : Buffer.alloc(4);
54 + header[0] = 0x80 | OPCODES.TEXT;
55 + if (payload.length < 126) header[1] = 0x80 | payload.length;
57 + header[1] = 0x80 | 126;
58 + header.writeUInt16BE(payload.length, 2);
60 + const mask = crypto.randomBytes(4);
61 + const masked = Buffer.alloc(payload.length);
62 + for (let i = 0; i < payload.length; i++) masked[i] = payload[i] ^ mask[i % 4];
63 + return Buffer.concat([header, mask, masked]);
66 +function decodeServerTextFrame(buffer) {
67 + if (buffer.length < 2) return null;
68 + const opcode = buffer[0] & 0x0F;
69 + let payloadLen = buffer[1] & 0x7F;
71 + if (payloadLen === 126) {
72 + if (buffer.length < 4) return null;
73 + payloadLen = buffer.readUInt16BE(2);
76 + const end = offset + payloadLen;
77 + if (buffer.length < end) return null;
78 + return { opcode, payload: buffer.subarray(offset, end) };
81 +function wsSendText(port, event) {
82 + return new Promise((resolve, reject) => {
83 + const key = crypto.randomBytes(16).toString('base64');
84 + const req = http.request({
88 + Connection: 'Upgrade',
89 + Upgrade: 'websocket',
90 + 'Sec-WebSocket-Version': '13',
91 + 'Sec-WebSocket-Key': key,
95 + req.on('upgrade', (_res, socket) => {
96 + socket.write(encodeClientTextFrame(event));
102 + req.on('error', reject);
107 +function wsListenForReload(port) {
108 + return new Promise((resolve, reject) => {
109 + const key = crypto.randomBytes(16).toString('base64');
110 + const req = http.request({
114 + Connection: 'Upgrade',
115 + Upgrade: 'websocket',
116 + 'Sec-WebSocket-Version': '13',
117 + 'Sec-WebSocket-Key': key,
121 + req.on('upgrade', (_res, socket) => {
122 + let buffer = Buffer.alloc(0);
123 + socket.on('data', chunk => {
124 + buffer = Buffer.concat([buffer, chunk]);
125 + const frame = decodeServerTextFrame(buffer);
126 + if (frame?.opcode === OPCODES.TEXT) {
128 + resolve(JSON.parse(frame.payload.toString()));
132 + req.on('error', reject);
133 + setTimeout(() => reject(new Error('timed out waiting for reload')), 3000).unref();
138 +test('visual companion launchers are pure Node scripts', () => {
139 + assert.equal(fs.existsSync(path.join(scriptDir, 'companion.mjs')), true);
140 + assert.equal(fs.existsSync(path.join(scriptDir, 'start-server.mjs')), true);
141 + assert.equal(fs.existsSync(path.join(scriptDir, 'stop-server.mjs')), true);
142 + assert.equal(fs.existsSync(path.join(scriptDir, 'start-server.sh')), false);
143 + assert.equal(fs.existsSync(path.join(scriptDir, 'stop-server.sh')), false);
146 +test('internal start-server CLI is rejected to avoid empty browser sessions', async () => {
147 + await assert.rejects(
148 + runNode('start-server.mjs', ['--project-dir', tmpProject()]),
150 + assert.match(error.stdout, /start-server\.mjs is internal/);
151 + assert.match(error.stdout, /start-choice/);
157 +test('human-agent workflow: script renders choices, UI event arrives while agent waits', async () => {
158 + await withSession(async info => {
159 + await runNode('companion.mjs', [
160 + 'choice-screen', info.session_dir,
161 + '--name', 'approaches',
162 + '--title', 'Which approach?',
163 + '--subtitle', 'Pick one direction',
164 + '--option', 'a|Small|Minimal change',
165 + '--option', 'b|Large|Broad redesign',
168 + const html = await (await fetch(info.url)).text();
169 + assert.match(html, /Which approach\?/);
170 + assert.match(html, /data-choice="a"/);
171 + assert.match(html, /Minimal change/);
172 + assert.match(html, /function\(\) \{/);
174 + const waiting = runNode('companion.mjs', ['wait-choice', info.session_dir, '--timeout-ms', '3000']);
175 + await wsSendText(info.port, { type: 'click', choice: 'b', text: 'Large', id: 'option-b' });
176 + const result = JSON.parse((await waiting).stdout.trim());
178 + assert.equal(result.choice, 'b');
179 + assert.equal(result.text, 'Large');
180 + assert.equal(result.id, 'option-b');
184 +test('companion has help for deterministic workflow commands', async () => {
185 + const { stdout } = await runNode('companion.mjs', ['--help']);
186 + assert.match(stdout, /start-choice/);
187 + assert.match(stdout, /start-screen/);
188 + assert.match(stdout, /open-choice/);
189 + assert.match(stdout, /open-screen/);
190 + assert.match(stdout, /ask-choice/);
191 + assert.match(stdout, /ask-screen/);
192 + assert.match(stdout, /--html-file/);
193 + assert.match(stdout, /cleanup/);
194 + assert.doesNotMatch(stdout, /\n start --project-dir/);
197 +test('companion start without a first screen is rejected', async () => {
198 + await assert.rejects(
199 + runNode('companion.mjs', ['start', '--project-dir', tmpProject()]),
201 + assert.match(error.stdout, /Use start-choice or start-screen/);
207 +test('start-choice starts server with first browser screen already loaded', async () => {
208 + const projectDir = tmpProject();
212 + const { stdout } = await runNode('companion.mjs', [
214 + '--project-dir', projectDir,
215 + '--name', 'first-layout',
216 + '--title', 'First visual question',
217 + '--subtitle', 'Browser must not show waiting page',
218 + '--option', 'a|Left rail|Tree on left',
219 + '--option', 'b|Graph first|Session graph center',
221 + const info = JSON.parse(stdout.trim());
222 + sessionDir = info.session_dir;
224 + assert.equal(info.type, 'server-started');
225 + assert.match(info.url, /^http:\/\/localhost:\d+$/);
226 + assert.equal(fs.existsSync(info.screen_file), true);
228 + const html = await (await fetch(info.url)).text();
229 + assert.match(html, /First visual question/);
230 + assert.match(html, /Browser must not show waiting page/);
231 + assert.match(html, /data-choice="b"/);
232 + assert.doesNotMatch(html, /Waiting for the agent to push a screen/);
234 + if (sessionDir) await stop(sessionDir);
235 + fs.rmSync(projectDir, { recursive: true, force: true });
239 +test('start-screen starts server with first custom HTML screen already loaded', async () => {
240 + const projectDir = tmpProject();
244 + const htmlFile = path.join(projectDir, 'first.html');
245 + fs.writeFileSync(htmlFile, '<h2>First custom screen</h2>');
246 + const { stdout } = await runNode('companion.mjs', [
248 + '--project-dir', projectDir,
249 + '--name', 'first-custom',
250 + '--html-file', htmlFile,
252 + const info = JSON.parse(stdout.trim());
253 + sessionDir = info.session_dir;
255 + assert.equal(fs.existsSync(info.screen_file), true);
256 + const html = await (await fetch(info.url)).text();
257 + assert.match(html, /First custom screen/);
258 + assert.doesNotMatch(html, /Waiting for the agent to push a screen/);
260 + if (sessionDir) await stop(sessionDir);
261 + fs.rmSync(projectDir, { recursive: true, force: true });
265 +test('visual wait commands reject slow timeouts above 30 seconds', async () => {
266 + const projectDir = tmpProject();
270 + const first = path.join(projectDir, 'first.html');
271 + fs.writeFileSync(first, '<h2>Timeout Cap</h2>');
272 + const { stdout } = await runNode('companion.mjs', ['start-screen', '--project-dir', projectDir, '--name', 'timeout-cap', '--html-file', first]);
273 + sessionDir = JSON.parse(stdout.trim()).session_dir;
275 + await assert.rejects(
276 + runNode('companion.mjs', ['ask-choice', sessionDir, '--name', 'too-slow', '--title', 'Too slow', '--option', 'a|A|A', '--timeout-ms', '300001']),
278 + assert.match(error.stdout, /--timeout-ms max is 30000ms/);
283 + if (sessionDir) await stop(sessionDir);
284 + fs.rmSync(projectDir, { recursive: true, force: true });
288 +test('open-choice starts with first screen, waits, and returns click without terminal reply', async () => {
289 + const projectDir = tmpProject();
293 + const asking = runNode('companion.mjs', [
295 + '--project-dir', projectDir,
296 + '--name', 'first-open-choice',
297 + '--title', 'Choose first layout',
298 + '--option', 'map|Map|Mission map',
299 + '--option', 'queue|Queue|Decision queue',
300 + '--timeout-ms', '3000',
301 + ], { env: { BRAINSTORM_NO_OPEN: '1' } });
304 + for (let i = 0; i < 50; i++) {
305 + const files = fs.globSync(`${projectDir}/.superpowers/brainstorm/*/state/server-info`);
306 + if (files.length) {
307 + info = JSON.parse(fs.readFileSync(files[0], 'utf8'));
308 + sessionDir = path.dirname(info.screen_dir);
311 + await new Promise(resolve => setTimeout(resolve, 50));
316 + for (let i = 0; i < 50; i++) {
317 + html = await (await fetch(info.url)).text();
318 + if (html.includes('Choose first layout')) break;
319 + await new Promise(resolve => setTimeout(resolve, 50));
321 + assert.match(html, /Choose first layout/);
322 + assert.doesNotMatch(html, /Waiting for the agent to push a screen/);
324 + await wsSendText(info.port, { type: 'click', choice: 'queue', text: 'Queue', id: 'option-queue' });
325 + const result = JSON.parse((await asking).stdout.trim());
326 + assert.equal(result.choice, 'queue');
327 + assert.equal(result.session_dir, sessionDir);
328 + assert.equal(result.url, info.url);
330 + if (sessionDir) await stop(sessionDir);
331 + fs.rmSync(projectDir, { recursive: true, force: true });
335 +test('open-screen starts with first custom screen, waits, and returns click', async () => {
336 + const projectDir = tmpProject();
340 + const htmlFile = path.join(projectDir, 'open-screen.html');
341 + fs.writeFileSync(htmlFile, '<h2>Open custom</h2><div data-choice="x" onclick="toggleSelect(this)">X</div>');
342 + const asking = runNode('companion.mjs', [
344 + '--project-dir', projectDir,
345 + '--name', 'open-custom',
346 + '--html-file', htmlFile,
347 + '--timeout-ms', '3000',
348 + ], { env: { BRAINSTORM_NO_OPEN: '1' } });
351 + for (let i = 0; i < 50; i++) {
352 + const files = fs.globSync(`${projectDir}/.superpowers/brainstorm/*/state/server-info`);
353 + if (files.length) {
354 + info = JSON.parse(fs.readFileSync(files[0], 'utf8'));
355 + sessionDir = path.dirname(info.screen_dir);
358 + await new Promise(resolve => setTimeout(resolve, 50));
363 + for (let i = 0; i < 50; i++) {
364 + html = await (await fetch(info.url)).text();
365 + if (html.includes('Open custom')) break;
366 + await new Promise(resolve => setTimeout(resolve, 50));
368 + assert.match(html, /Open custom/);
369 + await wsSendText(info.port, { type: 'click', choice: 'x', text: 'X', id: null });
370 + const result = JSON.parse((await asking).stdout.trim());
371 + assert.equal(result.choice, 'x');
373 + if (sessionDir) await stop(sessionDir);
374 + fs.rmSync(projectDir, { recursive: true, force: true });
378 +test('ask-choice writes a choice screen and returns the browser click without terminal reply', async () => {
379 + await withSession(async info => {
380 + const asking = runNode('companion.mjs', [
381 + 'ask-choice', info.session_dir,
382 + '--name', 'ask-style',
383 + '--title', 'Pick a mode',
384 + '--subtitle', 'No terminal reply needed',
385 + '--option', 'fast|Fast|Shortest path',
386 + '--option', 'deep|Deep|More detail',
387 + '--timeout-ms', '3000',
390 + for (let i = 0; i < 50; i++) {
391 + const html = await (await fetch(info.url)).text();
392 + if (html.includes('Pick a mode') && html.includes('data-choice="deep"')) break;
393 + await new Promise(resolve => setTimeout(resolve, 50));
396 + await wsSendText(info.port, { type: 'click', choice: 'deep', text: 'Deep', id: 'option-deep' });
397 + const result = JSON.parse((await asking).stdout.trim());
399 + assert.equal(result.choice, 'deep');
400 + assert.equal(result.text, 'Deep');
401 + assert.equal(result.id, 'option-deep');
405 +test('ask-screen reads custom HTML from file and returns browser click without shell quoting', async () => {
406 + await withSession(async (info, projectDir) => {
407 + const htmlFile = path.join(projectDir, 'mockups.html');
408 + fs.writeFileSync(htmlFile, `
409 +<h2>Custom mockups</h2>
411 + <div class="card" data-choice="a" onclick="toggleSelect(this)"><div class="card-body"><h3>A</h3><p>Alpha</p></div></div>
412 + <div class="card" data-choice="b" onclick="toggleSelect(this)"><div class="card-body"><h3>B</h3><p>Beta</p></div></div>
416 + const asking = runNode('companion.mjs', [
417 + 'ask-screen', info.session_dir,
418 + '--name', 'custom-mockups',
419 + '--html-file', htmlFile,
420 + '--timeout-ms', '3000',
423 + for (let i = 0; i < 50; i++) {
424 + const html = await (await fetch(info.url)).text();
425 + if (html.includes('Custom mockups') && html.includes('data-choice="b"')) break;
426 + await new Promise(resolve => setTimeout(resolve, 50));
429 + await wsSendText(info.port, { type: 'click', choice: 'b', text: 'B Beta', id: null });
430 + const result = JSON.parse((await asking).stdout.trim());
431 + assert.equal(result.choice, 'b');
432 + assert.equal(result.text, 'B Beta');
436 +test('write-screen reads custom HTML from file', async () => {
437 + await withSession(async (info, projectDir) => {
438 + const htmlFile = path.join(projectDir, 'screen.html');
439 + fs.writeFileSync(htmlFile, '<h2>File Screen</h2>');
440 + await runNode('companion.mjs', ['write-screen', info.session_dir, '--name', 'file-screen', '--html-file', htmlFile]);
441 + assert.match(await (await fetch(info.url)).text(), /File Screen/);
445 +test('scripted workflow supports waiting screen, event listing, clearing, and per-screen event reset', async () => {
446 + await withSession(async info => {
447 + await runNode('companion.mjs', ['choice-screen', info.session_dir, '--name', 'first', '--title', 'First?', '--option', 'a|Alpha|A']);
448 + await wsSendText(info.port, { type: 'click', choice: 'a', text: 'Alpha' });
450 + const listed = JSON.parse((await runNode('companion.mjs', ['events', info.session_dir])).stdout.trim());
451 + assert.equal(listed.length, 1);
452 + assert.equal(listed[0].choice, 'a');
454 + await runNode('companion.mjs', ['choice-screen', info.session_dir, '--name', 'second', '--title', 'Second?', '--option', 'b|Beta|B']);
455 + assert.deepEqual(JSON.parse((await runNode('companion.mjs', ['events', info.session_dir])).stdout.trim()), []);
457 + await wsSendText(info.port, { type: 'click', choice: 'b', text: 'Beta' });
458 + assert.equal(JSON.parse((await runNode('companion.mjs', ['events', info.session_dir, '--clear'])).stdout.trim()).length, 1);
459 + assert.deepEqual(JSON.parse((await runNode('companion.mjs', ['events', info.session_dir])).stdout.trim()), []);
461 + await runNode('companion.mjs', ['waiting-screen', info.session_dir, '--name', 'terminal']);
462 + const html = await (await fetch(info.url)).text();
463 + assert.match(html, /Continuing in terminal/);
467 +test('browser gets reload when agent pushes a new screen', async () => {
468 + await withSession(async info => {
469 + const reload = wsListenForReload(info.port);
470 + await runNode('companion.mjs', ['choice-screen', info.session_dir, '--name', 'reload', '--title', 'Reload?', '--option', 'y|Yes|Y']);
471 + assert.deepEqual(await reload, { type: 'reload' });
475 +test('server serves wrapped fragments, full documents, and content assets', async () => {
476 + await withSession(async info => {
477 + await runNode('companion.mjs', ['write-screen', info.session_dir, '--name', 'fragment', '--html', '<h2>Fragment</h2>']);
478 + const fragment = await (await fetch(info.url)).text();
479 + assert.match(fragment, /Superpowers Brainstorming/);
480 + assert.match(fragment, /<h2>Fragment<\/h2>/);
482 + await runNode('companion.mjs', ['write-screen', info.session_dir, '--name', 'full', '--html', '<!DOCTYPE html><html><body><main>Full Doc</main></body></html>']);
483 + const full = await (await fetch(info.url)).text();
484 + assert.doesNotMatch(full, /Superpowers Brainstorming/);
485 + assert.match(full, /<main>Full Doc<\/main>/);
486 + assert.match(full, /const WS_URL/);
488 + fs.writeFileSync(path.join(info.screen_dir, 'asset.json'), '{"ok":true}');
489 + const asset = await fetch(`${info.url}/files/asset.json`);
490 + assert.equal(asset.headers.get('content-type'), 'application/json');
491 + assert.deepEqual(await asset.json(), { ok: true });
495 +test('cleanup stops servers whose owner pid is gone', async () => {
496 + const projectDir = tmpProject();
501 + const first = path.join(projectDir, 'first.html');
502 + fs.writeFileSync(first, '<h2>Owned</h2>');
503 + owner = spawn(process.execPath, ['-e', 'console.log(process.pid); setInterval(() => {}, 1000);'], { stdio: ['ignore', 'pipe', 'ignore'] });
504 + const ownerPid = await new Promise(resolve => owner.stdout.once('data', chunk => resolve(Number(chunk.toString().trim()))));
505 + assert.equal(Number.isInteger(ownerPid), true);
507 + const { stdout } = await runNode('companion.mjs', ['start-screen', '--project-dir', projectDir, '--owner-pid', String(ownerPid), '--name', 'owned', '--html-file', first]);
508 + const info = JSON.parse(stdout.trim());
509 + sessionDir = info.session_dir;
511 + owner.kill('SIGTERM');
512 + await new Promise(resolve => owner.once('exit', resolve));
514 + const cleaned = JSON.parse((await runNode('companion.mjs', ['cleanup'])).stdout.trim());
515 + assert.equal(cleaned.stopped.length, 1);
516 + assert.equal(cleaned.stopped[0].session_dir, sessionDir);
517 + assert.equal(cleaned.stopped[0].reason, 'owner_dead');
518 + assert.equal(fs.existsSync(path.join(sessionDir, 'state', 'server.pid')), false);
520 + if (owner && owner.exitCode === null) owner.kill('SIGTERM');
521 + if (sessionDir) await stop(sessionDir);
522 + fs.rmSync(projectDir, { recursive: true, force: true });
526 +test('server exits after browser disconnect timeout', async () => {
527 + const projectDir = tmpProject();
531 + const first = path.join(projectDir, 'first.html');
532 + fs.writeFileSync(first, '<h2>Disconnect</h2>');
533 + const { stdout } = await runNode('companion.mjs', ['start-screen', '--project-dir', projectDir, '--no-browser-timeout-ms', '200', '--name', 'disconnect', '--html-file', first]);
534 + const info = JSON.parse(stdout.trim());
535 + sessionDir = info.session_dir;
537 + await new Promise((resolve, reject) => {
538 + const key = crypto.randomBytes(16).toString('base64');
539 + const req = http.request({
543 + Connection: 'Upgrade',
544 + Upgrade: 'websocket',
545 + 'Sec-WebSocket-Version': '13',
546 + 'Sec-WebSocket-Key': key,
549 + req.on('upgrade', (_res, socket) => {
553 + req.on('error', reject);
557 + const stoppedFile = path.join(sessionDir, 'state', 'server-stopped');
558 + for (let i = 0; i < 50 && !fs.existsSync(stoppedFile); i++) await new Promise(resolve => setTimeout(resolve, 50));
559 + assert.equal(fs.existsSync(stoppedFile), true);
560 + assert.match(fs.readFileSync(stoppedFile, 'utf8'), /no browser clients/);
562 + if (sessionDir) await stop(sessionDir);
563 + fs.rmSync(projectDir, { recursive: true, force: true });
567 +test('server module exports websocket helpers without side effects', async () => {
568 + const server = await import('./server.mjs');
569 + assert.deepEqual(Object.keys(server).sort(), ['OPCODES', 'computeAcceptKey', 'decodeFrame', 'encodeFrame']);