server.test.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /**
  2. * Integration tests for the brainstorm server.
  3. *
  4. * Tests the full server behavior: HTTP serving, WebSocket communication,
  5. * file watching, and the brainstorming workflow.
  6. *
  7. * Uses the `ws` npm package as a test client (test-only dependency,
  8. * not shipped to end users).
  9. */
  10. const { spawn } = require('child_process');
  11. const http = require('http');
  12. const WebSocket = require('ws');
  13. const fs = require('fs');
  14. const path = require('path');
  15. const assert = require('assert');
  16. const SERVER_PATH = path.join(__dirname, '../../skills/brainstorming/scripts/server.cjs');
  17. const TEST_PORT = 3334;
  18. const TEST_DIR = '/tmp/brainstorm-test';
  19. const CONTENT_DIR = path.join(TEST_DIR, 'content');
  20. const STATE_DIR = path.join(TEST_DIR, 'state');
  21. // Fixed session key so the test client can authenticate (see auth.test.js for
  22. // the security behavior itself; here we just need authorized requests).
  23. const TOKEN = 'testtoken-server-0123456789abcdef';
  24. function cleanup() {
  25. if (fs.existsSync(TEST_DIR)) {
  26. fs.rmSync(TEST_DIR, { recursive: true });
  27. }
  28. }
  29. async function sleep(ms) {
  30. return new Promise(resolve => setTimeout(resolve, ms));
  31. }
  32. async function fetch(url) {
  33. const authed = url + (url.includes('?') ? '&' : '?') + 'key=' + TOKEN;
  34. return new Promise((resolve, reject) => {
  35. http.get(authed, (res) => {
  36. let data = '';
  37. res.on('data', chunk => data += chunk);
  38. res.on('end', () => resolve({
  39. status: res.statusCode,
  40. headers: res.headers,
  41. body: data
  42. }));
  43. }).on('error', reject);
  44. });
  45. }
  46. function startServer() {
  47. return spawn('node', [SERVER_PATH], {
  48. env: { ...process.env, BRAINSTORM_PORT: TEST_PORT, BRAINSTORM_DIR: TEST_DIR, BRAINSTORM_TOKEN: TOKEN }
  49. });
  50. }
  51. async function waitForServer(server) {
  52. let stdout = '';
  53. let stderr = '';
  54. return new Promise((resolve, reject) => {
  55. server.stdout.on('data', (data) => {
  56. stdout += data.toString();
  57. if (stdout.includes('server-started')) {
  58. resolve({ stdout, stderr, getStdout: () => stdout });
  59. }
  60. });
  61. server.stderr.on('data', (data) => { stderr += data.toString(); });
  62. server.on('error', reject);
  63. setTimeout(() => reject(new Error(`Server didn't start. stderr: ${stderr}`)), 5000);
  64. });
  65. }
  66. async function runTests() {
  67. cleanup();
  68. const server = startServer();
  69. let stdoutAccum = '';
  70. server.stdout.on('data', (data) => { stdoutAccum += data.toString(); });
  71. const { stdout: initialStdout } = await waitForServer(server);
  72. let passed = 0;
  73. let failed = 0;
  74. function test(name, fn) {
  75. return fn().then(() => {
  76. console.log(` PASS: ${name}`);
  77. passed++;
  78. }).catch(e => {
  79. console.log(` FAIL: ${name}`);
  80. console.log(` ${e.message}`);
  81. failed++;
  82. });
  83. }
  84. try {
  85. // ========== Server Startup ==========
  86. console.log('\n--- Server Startup ---');
  87. await test('outputs server-started JSON on startup', () => {
  88. const msg = JSON.parse(initialStdout.trim());
  89. assert.strictEqual(msg.type, 'server-started');
  90. assert.strictEqual(msg.port, TEST_PORT);
  91. assert(msg.url, 'Should include URL');
  92. assert(msg.screen_dir, 'Should include screen_dir');
  93. return Promise.resolve();
  94. });
  95. await test('writes server-info to state/', () => {
  96. const infoPath = path.join(STATE_DIR, 'server-info');
  97. assert(fs.existsSync(infoPath), 'state/server-info should exist');
  98. const info = JSON.parse(fs.readFileSync(infoPath, 'utf-8').trim());
  99. assert.strictEqual(info.type, 'server-started');
  100. assert.strictEqual(info.port, TEST_PORT);
  101. assert.strictEqual(info.screen_dir, CONTENT_DIR, 'screen_dir should point to content/');
  102. assert.strictEqual(info.state_dir, STATE_DIR, 'state_dir should point to state/');
  103. return Promise.resolve();
  104. });
  105. // ========== HTTP Serving ==========
  106. console.log('\n--- HTTP Serving ---');
  107. await test('serves waiting page when no screens exist', async () => {
  108. const res = await fetch(`http://localhost:${TEST_PORT}/`);
  109. assert.strictEqual(res.status, 200);
  110. assert(res.body.includes('Waiting for the agent'), 'Should show waiting message');
  111. });
  112. await test('injects helper.js into waiting page', async () => {
  113. const res = await fetch(`http://localhost:${TEST_PORT}/`);
  114. assert(res.body.includes('WebSocket'), 'Should have helper.js injected');
  115. assert(res.body.includes('toggleSelect'), 'Should have toggleSelect from helper');
  116. assert(res.body.includes('brainstorm'), 'Should have brainstorm API from helper');
  117. });
  118. await test('returns Content-Type text/html', async () => {
  119. const res = await fetch(`http://localhost:${TEST_PORT}/`);
  120. assert(res.headers['content-type'].includes('text/html'), 'Should be text/html');
  121. });
  122. await test('serves full HTML documents as-is (not wrapped)', async () => {
  123. const fullDoc = '<!DOCTYPE html>\n<html><head><title>Custom</title></head><body><h1>Custom Page</h1></body></html>';
  124. fs.writeFileSync(path.join(CONTENT_DIR, 'full-doc.html'), fullDoc);
  125. await sleep(300);
  126. const res = await fetch(`http://localhost:${TEST_PORT}/`);
  127. assert(res.body.includes('<h1>Custom Page</h1>'), 'Should contain original content');
  128. assert(res.body.includes('WebSocket'), 'Should still inject helper.js');
  129. assert(!res.body.includes('indicator-bar'), 'Should NOT wrap in frame template');
  130. });
  131. await test('wraps content fragments in frame template', async () => {
  132. const fragment = '<h2>Pick a layout</h2>\n<div class="options"><div class="option" data-choice="a"><div class="letter">A</div></div></div>';
  133. fs.writeFileSync(path.join(CONTENT_DIR, 'fragment.html'), fragment);
  134. await sleep(300);
  135. const res = await fetch(`http://localhost:${TEST_PORT}/`);
  136. assert(res.body.includes('indicator-bar'), 'Fragment should get indicator bar');
  137. assert(!res.body.includes('<!-- CONTENT -->'), 'Placeholder should be replaced');
  138. assert(res.body.includes('Pick a layout'), 'Fragment content should be present');
  139. assert(res.body.includes('data-choice="a"'), 'Fragment interactive elements intact');
  140. });
  141. await test('serves newest file by mtime', async () => {
  142. fs.writeFileSync(path.join(CONTENT_DIR, 'older.html'), '<h2>Older</h2>');
  143. await sleep(100);
  144. fs.writeFileSync(path.join(CONTENT_DIR, 'newer.html'), '<h2>Newer</h2>');
  145. await sleep(300);
  146. const res = await fetch(`http://localhost:${TEST_PORT}/`);
  147. assert(res.body.includes('Newer'), 'Should serve newest file');
  148. });
  149. await test('ignores non-html files for serving', async () => {
  150. // Write a newer non-HTML file — should still serve newest .html
  151. fs.writeFileSync(path.join(CONTENT_DIR, 'data.json'), '{"not": "html"}');
  152. await sleep(300);
  153. const res = await fetch(`http://localhost:${TEST_PORT}/`);
  154. assert(res.body.includes('Newer'), 'Should still serve newest HTML');
  155. assert(!res.body.includes('"not"'), 'Should not serve JSON');
  156. });
  157. await test('ignores macOS resource-fork dotfiles (._*.html) when serving', async () => {
  158. // On macOS/ExFAT/SMB, the OS writes ._name.html sidecar files holding
  159. // binary metadata. They end with .html but must never be served as a screen.
  160. fs.writeFileSync(path.join(CONTENT_DIR, 'real-screen.html'), '<h2>Real Screen Content</h2>');
  161. await sleep(100);
  162. fs.writeFileSync(path.join(CONTENT_DIR, '._real-screen.html'), 'Mac OS X resource fork garbage');
  163. await sleep(300);
  164. const res = await fetch(`http://localhost:${TEST_PORT}/`);
  165. assert(res.body.includes('Real Screen Content'), 'should serve the real screen, not the newer ._ sidecar');
  166. assert(!res.body.includes('resource fork garbage'), 'must not serve ._*.html dotfile content');
  167. });
  168. await test('does not serve dotfiles via /files/', async () => {
  169. fs.writeFileSync(path.join(CONTENT_DIR, '._secret.html'), 'dotfile body should not be served');
  170. const res = await fetch(`http://localhost:${TEST_PORT}/files/._secret.html`);
  171. assert.strictEqual(res.status, 404, '/files/ must 404 on dotfiles');
  172. });
  173. await test('returns 404 for non-root paths', async () => {
  174. const res = await fetch(`http://localhost:${TEST_PORT}/other`);
  175. assert.strictEqual(res.status, 404);
  176. });
  177. // ========== WebSocket Communication ==========
  178. console.log('\n--- WebSocket Communication ---');
  179. await test('accepts WebSocket upgrade on /', async () => {
  180. const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
  181. await new Promise((resolve, reject) => {
  182. ws.on('open', resolve);
  183. ws.on('error', reject);
  184. });
  185. ws.close();
  186. });
  187. await test('relays user events to stdout with source field', async () => {
  188. stdoutAccum = '';
  189. const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
  190. await new Promise(resolve => ws.on('open', resolve));
  191. ws.send(JSON.stringify({ type: 'click', text: 'Test Button' }));
  192. await sleep(300);
  193. assert(stdoutAccum.includes('"source":"user-event"'), 'Should tag with source');
  194. assert(stdoutAccum.includes('Test Button'), 'Should include event data');
  195. ws.close();
  196. });
  197. await test('writes choice events to state/events', async () => {
  198. // Clean up events from prior tests
  199. const eventsFile = path.join(STATE_DIR, 'events');
  200. if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
  201. const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
  202. await new Promise(resolve => ws.on('open', resolve));
  203. ws.send(JSON.stringify({ type: 'click', choice: 'b', text: 'Option B' }));
  204. await sleep(300);
  205. assert(fs.existsSync(eventsFile), '.events should exist');
  206. const lines = fs.readFileSync(eventsFile, 'utf-8').trim().split('\n');
  207. const event = JSON.parse(lines[lines.length - 1]);
  208. assert.strictEqual(event.choice, 'b');
  209. assert.strictEqual(event.text, 'Option B');
  210. ws.close();
  211. });
  212. await test('does NOT write non-choice events to state/events', async () => {
  213. const eventsFile = path.join(STATE_DIR, 'events');
  214. if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
  215. const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
  216. await new Promise(resolve => ws.on('open', resolve));
  217. ws.send(JSON.stringify({ type: 'hover', text: 'Something' }));
  218. await sleep(300);
  219. // Non-choice events should not create .events file
  220. assert(!fs.existsSync(eventsFile), '.events should not exist for non-choice events');
  221. ws.close();
  222. });
  223. await test('handles multiple concurrent WebSocket clients', async () => {
  224. const ws1 = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
  225. const ws2 = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
  226. await Promise.all([
  227. new Promise(resolve => ws1.on('open', resolve)),
  228. new Promise(resolve => ws2.on('open', resolve))
  229. ]);
  230. let ws1Reload = false;
  231. let ws2Reload = false;
  232. ws1.on('message', (data) => {
  233. if (JSON.parse(data.toString()).type === 'reload') ws1Reload = true;
  234. });
  235. ws2.on('message', (data) => {
  236. if (JSON.parse(data.toString()).type === 'reload') ws2Reload = true;
  237. });
  238. fs.writeFileSync(path.join(CONTENT_DIR, 'multi-client.html'), '<h2>Multi</h2>');
  239. await sleep(500);
  240. assert(ws1Reload, 'Client 1 should receive reload');
  241. assert(ws2Reload, 'Client 2 should receive reload');
  242. ws1.close();
  243. ws2.close();
  244. });
  245. await test('cleans up closed clients from broadcast list', async () => {
  246. const ws1 = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
  247. await new Promise(resolve => ws1.on('open', resolve));
  248. ws1.close();
  249. await sleep(100);
  250. // This should not throw even though ws1 is closed
  251. fs.writeFileSync(path.join(CONTENT_DIR, 'after-close.html'), '<h2>After</h2>');
  252. await sleep(300);
  253. // If we got here without error, the test passes
  254. });
  255. await test('handles malformed JSON from client gracefully', async () => {
  256. const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
  257. await new Promise(resolve => ws.on('open', resolve));
  258. // Send invalid JSON — server should not crash
  259. ws.send('not json at all {{{');
  260. await sleep(300);
  261. // Verify server is still responsive
  262. const res = await fetch(`http://localhost:${TEST_PORT}/`);
  263. assert.strictEqual(res.status, 200, 'Server should still be running');
  264. ws.close();
  265. });
  266. // ========== File Watching ==========
  267. console.log('\n--- File Watching ---');
  268. await test('sends reload on new .html file', async () => {
  269. const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
  270. await new Promise(resolve => ws.on('open', resolve));
  271. let gotReload = false;
  272. ws.on('message', (data) => {
  273. if (JSON.parse(data.toString()).type === 'reload') gotReload = true;
  274. });
  275. fs.writeFileSync(path.join(CONTENT_DIR, 'watch-new.html'), '<h2>New</h2>');
  276. await sleep(500);
  277. assert(gotReload, 'Should send reload on new file');
  278. ws.close();
  279. });
  280. await test('sends reload on .html file change', async () => {
  281. const filePath = path.join(CONTENT_DIR, 'watch-change.html');
  282. fs.writeFileSync(filePath, '<h2>Original</h2>');
  283. await sleep(500);
  284. const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
  285. await new Promise(resolve => ws.on('open', resolve));
  286. let gotReload = false;
  287. ws.on('message', (data) => {
  288. if (JSON.parse(data.toString()).type === 'reload') gotReload = true;
  289. });
  290. fs.writeFileSync(filePath, '<h2>Modified</h2>');
  291. await sleep(500);
  292. assert(gotReload, 'Should send reload on file change');
  293. ws.close();
  294. });
  295. await test('does NOT send reload for non-.html files', async () => {
  296. const ws = new WebSocket(`ws://localhost:${TEST_PORT}/?key=${TOKEN}`);
  297. await new Promise(resolve => ws.on('open', resolve));
  298. let gotReload = false;
  299. ws.on('message', (data) => {
  300. if (JSON.parse(data.toString()).type === 'reload') gotReload = true;
  301. });
  302. fs.writeFileSync(path.join(CONTENT_DIR, 'data.txt'), 'not html');
  303. await sleep(500);
  304. assert(!gotReload, 'Should NOT reload for non-HTML files');
  305. ws.close();
  306. });
  307. await test('does NOT send reload for ._*.html resource-fork dotfiles', async () => {
  308. const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);
  309. await new Promise(resolve => ws.on('open', resolve));
  310. let gotReload = false;
  311. ws.on('message', (data) => {
  312. if (JSON.parse(data.toString()).type === 'reload') gotReload = true;
  313. });
  314. fs.writeFileSync(path.join(CONTENT_DIR, '._sidecar.html'), 'resource fork');
  315. await sleep(500);
  316. assert(!gotReload, 'a ._ dotfile appearing must not trigger a reload');
  317. ws.close();
  318. });
  319. await test('clears state/events on new screen', async () => {
  320. // Create an events file
  321. const eventsFile = path.join(STATE_DIR, 'events');
  322. fs.writeFileSync(eventsFile, '{"choice":"a"}\n');
  323. assert(fs.existsSync(eventsFile));
  324. fs.writeFileSync(path.join(CONTENT_DIR, 'clear-events.html'), '<h2>New screen</h2>');
  325. await sleep(500);
  326. assert(!fs.existsSync(eventsFile), 'state/events should be cleared on new screen');
  327. });
  328. await test('logs screen-added on new file', async () => {
  329. stdoutAccum = '';
  330. fs.writeFileSync(path.join(CONTENT_DIR, 'log-test.html'), '<h2>Log</h2>');
  331. await sleep(500);
  332. assert(stdoutAccum.includes('screen-added'), 'Should log screen-added');
  333. });
  334. await test('logs screen-updated on file change', async () => {
  335. const filePath = path.join(CONTENT_DIR, 'log-update.html');
  336. fs.writeFileSync(filePath, '<h2>V1</h2>');
  337. await sleep(500);
  338. stdoutAccum = '';
  339. fs.writeFileSync(filePath, '<h2>V2</h2>');
  340. await sleep(500);
  341. assert(stdoutAccum.includes('screen-updated'), 'Should log screen-updated');
  342. });
  343. // ========== Helper.js Content ==========
  344. console.log('\n--- Helper.js Verification ---');
  345. await test('helper.js defines required APIs', () => {
  346. const helperContent = fs.readFileSync(
  347. path.join(__dirname, '../../skills/brainstorming/scripts/helper.js'), 'utf-8'
  348. );
  349. assert(helperContent.includes('toggleSelect'), 'Should define toggleSelect');
  350. assert(helperContent.includes('sendEvent'), 'Should define sendEvent');
  351. assert(helperContent.includes('selectedChoice'), 'Should track selectedChoice');
  352. assert(helperContent.includes('brainstorm'), 'Should expose brainstorm API');
  353. return Promise.resolve();
  354. });
  355. // ========== Frame Template ==========
  356. console.log('\n--- Frame Template Verification ---');
  357. await test('frame template has required structure', () => {
  358. const template = fs.readFileSync(
  359. path.join(__dirname, '../../skills/brainstorming/scripts/frame-template.html'), 'utf-8'
  360. );
  361. assert(template.includes('indicator-bar'), 'Should have indicator bar');
  362. assert(template.includes('indicator-text'), 'Should have indicator text');
  363. assert(template.includes('<!-- CONTENT -->'), 'Should have content placeholder');
  364. assert(template.includes('frame-content'), 'Should have content container');
  365. return Promise.resolve();
  366. });
  367. // ========== Summary ==========
  368. console.log(`\n--- Results: ${passed} passed, ${failed} failed ---`);
  369. if (failed > 0) process.exit(1);
  370. } finally {
  371. server.kill();
  372. await sleep(100);
  373. cleanup();
  374. }
  375. }
  376. runTests().catch(err => {
  377. console.error('Test failed:', err);
  378. process.exit(1);
  379. });