server.test.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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('ignores macOS resource-fork dotfiles (._*.html) when serving', async () => {
  154. // On macOS/ExFAT/SMB, the OS writes ._name.html sidecar files holding
  155. // binary metadata. They end with .html but must never be served as a screen.
  156. fs.writeFileSync(path.join(CONTENT_DIR, 'real-screen.html'), '<h2>Real Screen Content</h2>');
  157. await sleep(100);
  158. fs.writeFileSync(path.join(CONTENT_DIR, '._real-screen.html'), 'Mac OS X resource fork garbage');
  159. await sleep(300);
  160. const res = await fetch(`http://localhost:${TEST_PORT}/`);
  161. assert(res.body.includes('Real Screen Content'), 'should serve the real screen, not the newer ._ sidecar');
  162. assert(!res.body.includes('resource fork garbage'), 'must not serve ._*.html dotfile content');
  163. });
  164. await test('does not serve dotfiles via /files/', async () => {
  165. fs.writeFileSync(path.join(CONTENT_DIR, '._secret.html'), 'dotfile body should not be served');
  166. const res = await fetch(`http://localhost:${TEST_PORT}/files/._secret.html`);
  167. assert.strictEqual(res.status, 404, '/files/ must 404 on dotfiles');
  168. });
  169. await test('returns 404 for non-root paths', async () => {
  170. const res = await fetch(`http://localhost:${TEST_PORT}/other`);
  171. assert.strictEqual(res.status, 404);
  172. });
  173. // ========== WebSocket Communication ==========
  174. console.log('\n--- WebSocket Communication ---');
  175. await test('accepts WebSocket upgrade on /', async () => {
  176. const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);
  177. await new Promise((resolve, reject) => {
  178. ws.on('open', resolve);
  179. ws.on('error', reject);
  180. });
  181. ws.close();
  182. });
  183. await test('relays user events to stdout with source field', async () => {
  184. stdoutAccum = '';
  185. const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);
  186. await new Promise(resolve => ws.on('open', resolve));
  187. ws.send(JSON.stringify({ type: 'click', text: 'Test Button' }));
  188. await sleep(300);
  189. assert(stdoutAccum.includes('"source":"user-event"'), 'Should tag with source');
  190. assert(stdoutAccum.includes('Test Button'), 'Should include event data');
  191. ws.close();
  192. });
  193. await test('writes choice events to state/events', async () => {
  194. // Clean up events from prior tests
  195. const eventsFile = path.join(STATE_DIR, 'events');
  196. if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
  197. const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);
  198. await new Promise(resolve => ws.on('open', resolve));
  199. ws.send(JSON.stringify({ type: 'click', choice: 'b', text: 'Option B' }));
  200. await sleep(300);
  201. assert(fs.existsSync(eventsFile), '.events should exist');
  202. const lines = fs.readFileSync(eventsFile, 'utf-8').trim().split('\n');
  203. const event = JSON.parse(lines[lines.length - 1]);
  204. assert.strictEqual(event.choice, 'b');
  205. assert.strictEqual(event.text, 'Option B');
  206. ws.close();
  207. });
  208. await test('does NOT write non-choice events to state/events', async () => {
  209. const eventsFile = path.join(STATE_DIR, 'events');
  210. if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
  211. const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);
  212. await new Promise(resolve => ws.on('open', resolve));
  213. ws.send(JSON.stringify({ type: 'hover', text: 'Something' }));
  214. await sleep(300);
  215. // Non-choice events should not create .events file
  216. assert(!fs.existsSync(eventsFile), '.events should not exist for non-choice events');
  217. ws.close();
  218. });
  219. await test('handles multiple concurrent WebSocket clients', async () => {
  220. const ws1 = new WebSocket(`ws://localhost:${TEST_PORT}`);
  221. const ws2 = new WebSocket(`ws://localhost:${TEST_PORT}`);
  222. await Promise.all([
  223. new Promise(resolve => ws1.on('open', resolve)),
  224. new Promise(resolve => ws2.on('open', resolve))
  225. ]);
  226. let ws1Reload = false;
  227. let ws2Reload = false;
  228. ws1.on('message', (data) => {
  229. if (JSON.parse(data.toString()).type === 'reload') ws1Reload = true;
  230. });
  231. ws2.on('message', (data) => {
  232. if (JSON.parse(data.toString()).type === 'reload') ws2Reload = true;
  233. });
  234. fs.writeFileSync(path.join(CONTENT_DIR, 'multi-client.html'), '<h2>Multi</h2>');
  235. await sleep(500);
  236. assert(ws1Reload, 'Client 1 should receive reload');
  237. assert(ws2Reload, 'Client 2 should receive reload');
  238. ws1.close();
  239. ws2.close();
  240. });
  241. await test('cleans up closed clients from broadcast list', async () => {
  242. const ws1 = new WebSocket(`ws://localhost:${TEST_PORT}`);
  243. await new Promise(resolve => ws1.on('open', resolve));
  244. ws1.close();
  245. await sleep(100);
  246. // This should not throw even though ws1 is closed
  247. fs.writeFileSync(path.join(CONTENT_DIR, 'after-close.html'), '<h2>After</h2>');
  248. await sleep(300);
  249. // If we got here without error, the test passes
  250. });
  251. await test('handles malformed JSON from client gracefully', async () => {
  252. const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);
  253. await new Promise(resolve => ws.on('open', resolve));
  254. // Send invalid JSON — server should not crash
  255. ws.send('not json at all {{{');
  256. await sleep(300);
  257. // Verify server is still responsive
  258. const res = await fetch(`http://localhost:${TEST_PORT}/`);
  259. assert.strictEqual(res.status, 200, 'Server should still be running');
  260. ws.close();
  261. });
  262. // ========== File Watching ==========
  263. console.log('\n--- File Watching ---');
  264. await test('sends reload on new .html file', async () => {
  265. const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);
  266. await new Promise(resolve => ws.on('open', resolve));
  267. let gotReload = false;
  268. ws.on('message', (data) => {
  269. if (JSON.parse(data.toString()).type === 'reload') gotReload = true;
  270. });
  271. fs.writeFileSync(path.join(CONTENT_DIR, 'watch-new.html'), '<h2>New</h2>');
  272. await sleep(500);
  273. assert(gotReload, 'Should send reload on new file');
  274. ws.close();
  275. });
  276. await test('sends reload on .html file change', async () => {
  277. const filePath = path.join(CONTENT_DIR, 'watch-change.html');
  278. fs.writeFileSync(filePath, '<h2>Original</h2>');
  279. await sleep(500);
  280. const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);
  281. await new Promise(resolve => ws.on('open', resolve));
  282. let gotReload = false;
  283. ws.on('message', (data) => {
  284. if (JSON.parse(data.toString()).type === 'reload') gotReload = true;
  285. });
  286. fs.writeFileSync(filePath, '<h2>Modified</h2>');
  287. await sleep(500);
  288. assert(gotReload, 'Should send reload on file change');
  289. ws.close();
  290. });
  291. await test('does NOT send reload for non-.html files', async () => {
  292. const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);
  293. await new Promise(resolve => ws.on('open', resolve));
  294. let gotReload = false;
  295. ws.on('message', (data) => {
  296. if (JSON.parse(data.toString()).type === 'reload') gotReload = true;
  297. });
  298. fs.writeFileSync(path.join(CONTENT_DIR, 'data.txt'), 'not html');
  299. await sleep(500);
  300. assert(!gotReload, 'Should NOT reload for non-HTML files');
  301. ws.close();
  302. });
  303. await test('does NOT send reload for ._*.html resource-fork dotfiles', async () => {
  304. const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);
  305. await new Promise(resolve => ws.on('open', resolve));
  306. let gotReload = false;
  307. ws.on('message', (data) => {
  308. if (JSON.parse(data.toString()).type === 'reload') gotReload = true;
  309. });
  310. fs.writeFileSync(path.join(CONTENT_DIR, '._sidecar.html'), 'resource fork');
  311. await sleep(500);
  312. assert(!gotReload, 'a ._ dotfile appearing must not trigger a reload');
  313. ws.close();
  314. });
  315. await test('clears state/events on new screen', async () => {
  316. // Create an events file
  317. const eventsFile = path.join(STATE_DIR, 'events');
  318. fs.writeFileSync(eventsFile, '{"choice":"a"}\n');
  319. assert(fs.existsSync(eventsFile));
  320. fs.writeFileSync(path.join(CONTENT_DIR, 'clear-events.html'), '<h2>New screen</h2>');
  321. await sleep(500);
  322. assert(!fs.existsSync(eventsFile), 'state/events should be cleared on new screen');
  323. });
  324. await test('logs screen-added on new file', async () => {
  325. stdoutAccum = '';
  326. fs.writeFileSync(path.join(CONTENT_DIR, 'log-test.html'), '<h2>Log</h2>');
  327. await sleep(500);
  328. assert(stdoutAccum.includes('screen-added'), 'Should log screen-added');
  329. });
  330. await test('logs screen-updated on file change', async () => {
  331. const filePath = path.join(CONTENT_DIR, 'log-update.html');
  332. fs.writeFileSync(filePath, '<h2>V1</h2>');
  333. await sleep(500);
  334. stdoutAccum = '';
  335. fs.writeFileSync(filePath, '<h2>V2</h2>');
  336. await sleep(500);
  337. assert(stdoutAccum.includes('screen-updated'), 'Should log screen-updated');
  338. });
  339. // ========== Helper.js Content ==========
  340. console.log('\n--- Helper.js Verification ---');
  341. await test('helper.js defines required APIs', () => {
  342. const helperContent = fs.readFileSync(
  343. path.join(__dirname, '../../skills/brainstorming/scripts/helper.js'), 'utf-8'
  344. );
  345. assert(helperContent.includes('toggleSelect'), 'Should define toggleSelect');
  346. assert(helperContent.includes('sendEvent'), 'Should define sendEvent');
  347. assert(helperContent.includes('selectedChoice'), 'Should track selectedChoice');
  348. assert(helperContent.includes('brainstorm'), 'Should expose brainstorm API');
  349. return Promise.resolve();
  350. });
  351. // ========== Frame Template ==========
  352. console.log('\n--- Frame Template Verification ---');
  353. await test('frame template has required structure', () => {
  354. const template = fs.readFileSync(
  355. path.join(__dirname, '../../skills/brainstorming/scripts/frame-template.html'), 'utf-8'
  356. );
  357. assert(template.includes('indicator-bar'), 'Should have indicator bar');
  358. assert(template.includes('indicator-text'), 'Should have indicator text');
  359. assert(template.includes('<!-- CONTENT -->'), 'Should have content placeholder');
  360. assert(template.includes('frame-content'), 'Should have content container');
  361. return Promise.resolve();
  362. });
  363. // ========== Summary ==========
  364. console.log(`\n--- Results: ${passed} passed, ${failed} failed ---`);
  365. if (failed > 0) process.exit(1);
  366. } finally {
  367. server.kill();
  368. await sleep(100);
  369. cleanup();
  370. }
  371. }
  372. runTests().catch(err => {
  373. console.error('Test failed:', err);
  374. process.exit(1);
  375. });