server.test.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. const { spawn } = require('child_process');
  2. const http = require('http');
  3. const WebSocket = require('ws');
  4. const fs = require('fs');
  5. const path = require('path');
  6. const assert = require('assert');
  7. const SERVER_PATH = path.join(__dirname, '../../lib/brainstorm-server/index.js');
  8. const TEST_PORT = 3334;
  9. const TEST_DIR = '/tmp/brainstorm-test';
  10. function cleanup() {
  11. if (fs.existsSync(TEST_DIR)) {
  12. fs.rmSync(TEST_DIR, { recursive: true });
  13. }
  14. }
  15. async function sleep(ms) {
  16. return new Promise(resolve => setTimeout(resolve, ms));
  17. }
  18. async function fetch(url) {
  19. return new Promise((resolve, reject) => {
  20. http.get(url, (res) => {
  21. let data = '';
  22. res.on('data', chunk => data += chunk);
  23. res.on('end', () => resolve({ status: res.statusCode, body: data }));
  24. }).on('error', reject);
  25. });
  26. }
  27. function startServer() {
  28. return spawn('node', [SERVER_PATH], {
  29. env: { ...process.env, BRAINSTORM_PORT: TEST_PORT, BRAINSTORM_DIR: TEST_DIR }
  30. });
  31. }
  32. async function runTests() {
  33. cleanup();
  34. fs.mkdirSync(TEST_DIR, { recursive: true });
  35. const server = startServer();
  36. let stdout = '';
  37. let stderr = '';
  38. server.stdout.on('data', (data) => { stdout += data.toString(); });
  39. server.stderr.on('data', (data) => { stderr += data.toString(); });
  40. // Wait for server to start (up to 3 seconds)
  41. for (let i = 0; i < 30; i++) {
  42. if (stdout.includes('server-started')) break;
  43. await sleep(100);
  44. }
  45. if (stderr) console.error('Server stderr:', stderr);
  46. try {
  47. // Test 1: Server starts and outputs JSON
  48. console.log('Test 1: Server startup message');
  49. assert(stdout.includes('server-started'), 'Should output server-started');
  50. assert(stdout.includes(TEST_PORT.toString()), 'Should include port');
  51. console.log(' PASS');
  52. // Test 2: GET / returns waiting page with helper injected when no screens exist
  53. console.log('Test 2: Serves waiting page with helper injected');
  54. const res = await fetch(`http://localhost:${TEST_PORT}/`);
  55. assert.strictEqual(res.status, 200);
  56. assert(res.body.includes('Waiting for Claude'), 'Should show waiting message');
  57. assert(res.body.includes('WebSocket'), 'Should have helper.js injected');
  58. console.log(' PASS');
  59. // Test 3: WebSocket connection and event relay
  60. console.log('Test 3: WebSocket relays events to stdout');
  61. stdout = '';
  62. const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);
  63. await new Promise(resolve => ws.on('open', resolve));
  64. ws.send(JSON.stringify({ type: 'click', text: 'Test Button' }));
  65. await sleep(300);
  66. assert(stdout.includes('"source":"user-event"'), 'Should relay user events with source field');
  67. assert(stdout.includes('Test Button'), 'Should include event data');
  68. ws.close();
  69. console.log(' PASS');
  70. // Test 4: File change triggers reload notification
  71. console.log('Test 4: File change notifies browsers');
  72. const ws2 = new WebSocket(`ws://localhost:${TEST_PORT}`);
  73. await new Promise(resolve => ws2.on('open', resolve));
  74. let gotReload = false;
  75. ws2.on('message', (data) => {
  76. const msg = JSON.parse(data.toString());
  77. if (msg.type === 'reload') gotReload = true;
  78. });
  79. fs.writeFileSync(path.join(TEST_DIR, 'test-screen.html'), '<html><body>Full doc</body></html>');
  80. await sleep(500);
  81. assert(gotReload, 'Should send reload message on file change');
  82. ws2.close();
  83. console.log(' PASS');
  84. // Test: Choice events written to .events file
  85. console.log('Test: Choice events written to .events file');
  86. const ws3 = new WebSocket(`ws://localhost:${TEST_PORT}`);
  87. await new Promise(resolve => ws3.on('open', resolve));
  88. ws3.send(JSON.stringify({ type: 'click', choice: 'a', text: 'Option A' }));
  89. await sleep(300);
  90. const eventsFile = path.join(TEST_DIR, '.events');
  91. assert(fs.existsSync(eventsFile), '.events file should exist after choice click');
  92. const lines = fs.readFileSync(eventsFile, 'utf-8').trim().split('\n');
  93. const event = JSON.parse(lines[lines.length - 1]);
  94. assert.strictEqual(event.choice, 'a', 'Event should contain choice');
  95. assert.strictEqual(event.text, 'Option A', 'Event should contain text');
  96. ws3.close();
  97. console.log(' PASS');
  98. // Test: .events cleared on new screen
  99. console.log('Test: .events cleared on new screen');
  100. // .events file should still exist from previous test
  101. assert(fs.existsSync(path.join(TEST_DIR, '.events')), '.events should exist before new screen');
  102. fs.writeFileSync(path.join(TEST_DIR, 'new-screen.html'), '<h2>New screen</h2>');
  103. await sleep(500);
  104. assert(!fs.existsSync(path.join(TEST_DIR, '.events')), '.events should be cleared after new screen');
  105. console.log(' PASS');
  106. // Test 5: Full HTML document served as-is (not wrapped)
  107. console.log('Test 5: Full HTML document served without frame wrapping');
  108. const fullDoc = '<!DOCTYPE html>\n<html><head><title>Custom</title></head><body><h1>Custom Page</h1></body></html>';
  109. fs.writeFileSync(path.join(TEST_DIR, 'full-doc.html'), fullDoc);
  110. await sleep(300);
  111. const fullRes = await fetch(`http://localhost:${TEST_PORT}/`);
  112. assert(fullRes.body.includes('<h1>Custom Page</h1>'), 'Should contain original content');
  113. assert(fullRes.body.includes('WebSocket'), 'Should still inject helper.js');
  114. // Should NOT have the frame template's indicator bar
  115. assert(!fullRes.body.includes('indicator-bar') || fullDoc.includes('indicator-bar'),
  116. 'Should not wrap full documents in frame template');
  117. console.log(' PASS');
  118. // Test 6: Bare HTML fragment gets wrapped in frame template
  119. console.log('Test 6: Content fragment wrapped in frame template');
  120. const fragment = '<h2>Pick a layout</h2>\n<p class="subtitle">Choose one</p>\n<div class="options"><div class="option" data-choice="a"><div class="letter">A</div><div class="content"><h3>Simple</h3></div></div></div>';
  121. fs.writeFileSync(path.join(TEST_DIR, 'fragment.html'), fragment);
  122. await sleep(300);
  123. const fragRes = await fetch(`http://localhost:${TEST_PORT}/`);
  124. // Should have the frame template structure
  125. assert(fragRes.body.includes('indicator-bar'), 'Fragment should get indicator bar from frame');
  126. assert(!fragRes.body.includes('<!-- CONTENT -->'), 'Content placeholder should be replaced');
  127. // Should have the original content inside
  128. assert(fragRes.body.includes('Pick a layout'), 'Fragment content should be present');
  129. assert(fragRes.body.includes('data-choice="a"'), 'Fragment content should be intact');
  130. // Should have helper.js injected
  131. assert(fragRes.body.includes('WebSocket'), 'Fragment should have helper.js injected');
  132. console.log(' PASS');
  133. // Test 7: Helper.js includes toggleSelect and send functions
  134. console.log('Test 7: Helper.js provides toggleSelect and send');
  135. const helperContent = fs.readFileSync(
  136. path.join(__dirname, '../../lib/brainstorm-server/helper.js'), 'utf-8'
  137. );
  138. assert(helperContent.includes('toggleSelect'), 'helper.js should define toggleSelect');
  139. assert(helperContent.includes('sendEvent'), 'helper.js should define sendEvent');
  140. assert(helperContent.includes('selectedChoice'), 'helper.js should track selectedChoice');
  141. assert(helperContent.includes('brainstorm'), 'helper.js should expose brainstorm API');
  142. assert(!helperContent.includes('sendToClaude'), 'helper.js should not contain sendToClaude');
  143. console.log(' PASS');
  144. // Test 8: Indicator bar uses CSS variables (theme support)
  145. console.log('Test 8: Indicator bar uses CSS variables');
  146. const templateContent = fs.readFileSync(
  147. path.join(__dirname, '../../lib/brainstorm-server/frame-template.html'), 'utf-8'
  148. );
  149. assert(templateContent.includes('indicator-bar'), 'Template should have indicator bar');
  150. assert(templateContent.includes('indicator-text'), 'Template should have indicator text element');
  151. console.log(' PASS');
  152. console.log('\nAll tests passed!');
  153. } finally {
  154. server.kill();
  155. cleanup();
  156. }
  157. }
  158. runTests().catch(err => {
  159. console.error('Test failed:', err);
  160. process.exit(1);
  161. });