server.test.js 15 KB

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