/** * Integration tests for the brainstorm server. * * Tests the full server behavior: HTTP serving, WebSocket communication, * file watching, and the brainstorming workflow. * * Uses the `ws` npm package as a test client (test-only dependency, * not shipped to end users). */ const { spawn } = require('child_process'); const http = require('http'); const WebSocket = require('ws'); const fs = require('fs'); const path = require('path'); const assert = require('assert'); const SERVER_PATH = path.join(__dirname, '../../skills/brainstorming/scripts/server.cjs'); const TEST_PORT = 3334; const TEST_DIR = '/tmp/brainstorm-test'; const CONTENT_DIR = path.join(TEST_DIR, 'content'); const STATE_DIR = path.join(TEST_DIR, 'state'); // Fixed session key so the test client can authenticate (see auth.test.js for // the security behavior itself; here we just need authorized requests). const TOKEN = 'testtoken-server-0123456789abcdef'; function cleanup() { if (fs.existsSync(TEST_DIR)) { fs.rmSync(TEST_DIR, { recursive: true }); } } async function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // fs.watch delivery latency varies widely by platform: on macOS, FSEvents // has been observed delivering events anywhere from ~100ms to over 2s after // the write. File-watching tests poll for the outcome instead of sleeping a // fixed interval, so a slow event neither fails its own test nor arrives // during the next one. async function waitFor(condition, message, timeoutMs = 5000) { const deadline = Date.now() + timeoutMs; while (!condition()) { if (Date.now() > deadline) throw new Error(message); await sleep(25); } } async function fetch(url) { return new Promise((resolve, reject) => { const headers = { Cookie: `brainstorm-key-${TEST_PORT}=${TOKEN}` }; http.get(url, { headers }, (res) => { let data = ''; res.on('data', chunk => data += chunk); res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body: data })); }).on('error', reject); }); } function startServer() { return spawn('node', [SERVER_PATH], { env: { ...process.env, BRAINSTORM_PORT: TEST_PORT, BRAINSTORM_DIR: TEST_DIR, BRAINSTORM_TOKEN: TOKEN } }); } async function waitForServer(server) { let stdout = ''; let stderr = ''; return new Promise((resolve, reject) => { server.stdout.on('data', (data) => { stdout += data.toString(); if (stdout.includes('server-started')) { resolve({ stdout, stderr, getStdout: () => stdout }); } }); server.stderr.on('data', (data) => { stderr += data.toString(); }); server.on('error', reject); setTimeout(() => reject(new Error(`Server didn't start. stderr: ${stderr}`)), 5000); }); } class SkipTest extends Error { constructor(message) { super(message); this.skip = true; } } function skip(message) { throw new SkipTest(message); } function serverStartedMessage(out) { const line = out.trim().split('\n').find(l => l.includes('server-started')); assert(line, 'server-started JSON should be present'); return JSON.parse(line); } function assertStartedOnExpectedPort(out) { const msg = serverStartedMessage(out); assert.strictEqual( msg.port, TEST_PORT, `server.test.js expected fixed port ${TEST_PORT}, got ${msg.port}; fixed-port tests must not run through fallback` ); return msg; } function ensureSymlinkWorks(target, link) { try { fs.symlinkSync(target, link); fs.unlinkSync(link); } catch (e) { try { fs.unlinkSync(link); } catch (ignore) {} skip(`symlink creation unavailable on this host: ${e.message}`); } } async function runTests() { cleanup(); const server = startServer(); let stdoutAccum = ''; // Unlike stdoutAccum, never reset: lets a test wait until the server has // processed a specific file event. let serverLog = ''; server.stdout.on('data', (data) => { stdoutAccum += data.toString(); serverLog += data.toString(); }); const screenLogged = (type, filePath) => serverLog.includes(JSON.stringify({ type, file: filePath })); // Drains file events still in flight from earlier tests, which can each // trigger a reload and clear state/events. fs.watch delivers events in // order, so once the server has processed a file written now, every // earlier event has been handled too. let barrierCount = 0; async function settleWatcher() { const barrier = path.join(CONTENT_DIR, `barrier-${++barrierCount}.html`); fs.writeFileSync(barrier, '
' + tokens.join(' | ') + '';
fs.writeFileSync(path.join(CONTENT_DIR, 'literal-tokens.html'), fragment);
await sleep(300);
const res = await fetch(`http://localhost:${TEST_PORT}/`);
assert.strictEqual(res.status, 200);
assert(res.body.includes(fragment), 'Fragment must be inserted verbatim');
assert.strictEqual(res.body.split('