Visual Brainstorming Companion Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
Goal: Give Claude a browser-based visual companion for brainstorming sessions - show mockups, prototypes, and interactive choices alongside terminal conversation.
Architecture: Claude writes HTML to a temp file. A local Node.js server watches that file and serves it with an auto-injected helper library. User interactions flow via WebSocket to server stdout, which Claude sees in background task output.
Tech Stack: Node.js, Express, ws (WebSocket), chokidar (file watching)
Task 1: Create the Server Foundation
Files:
- Create:
lib/brainstorm-server/index.js - Create:
lib/brainstorm-server/package.json
Step 1: Create package.json
1{
2 "name": "brainstorm-server",
3 "version": "1.0.0",
4 "description": "Visual brainstorming companion server for Claude Code",
5 "main": "index.js",
6 "dependencies": {
7 "chokidar": "^3.5.3",
8 "express": "^4.18.2",
9 "ws": "^8.14.2"
10 }
11}
Step 2: Create minimal server that starts
1const express = require('express');
2const http = require('http');
3const WebSocket = require('ws');
4const chokidar = require('chokidar');
5const fs = require('fs');
6const path = require('path');
7
8const PORT = process.env.BRAINSTORM_PORT || 3333;
9const SCREEN_FILE = process.env.BRAINSTORM_SCREEN || '/tmp/brainstorm/screen.html';
10const SCREEN_DIR = path.dirname(SCREEN_FILE);
11
12// Ensure screen directory exists
13if (!fs.existsSync(SCREEN_DIR)) {
14 fs.mkdirSync(SCREEN_DIR, { recursive: true });
15}
16
17// Create default screen if none exists
18if (!fs.existsSync(SCREEN_FILE)) {
19 fs.writeFileSync(SCREEN_FILE, `<!DOCTYPE html>
20<html>
21<head>
22 <title>Brainstorm Companion</title>
23 <style>
24 body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
25 h1 { color: #333; }
26 p { color: #666; }
27 </style>
28</head>
29<body>
30 <h1>Brainstorm Companion</h1>
31 <p>Waiting for Claude to push a screen...</p>
32</body>
33</html>`);
34}
35
36const app = express();
37const server = http.createServer(app);
38const wss = new WebSocket.Server({ server });
39
40// Track connected browsers for reload notifications
41const clients = new Set();
42
43wss.on('connection', (ws) => {
44 clients.add(ws);
45 ws.on('close', () => clients.delete(ws));
46
47 ws.on('message', (data) => {
48 // User interaction event - write to stdout for Claude
49 const event = JSON.parse(data.toString());
50 console.log(JSON.stringify({ type: 'user-event', ...event }));
51 });
52});
53
54// Serve current screen with helper.js injected
55app.get('/', (req, res) => {
56 let html = fs.readFileSync(SCREEN_FILE, 'utf-8');
57
58 // Inject helper script before </body>
59 const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
60 const injection = `<script>\n${helperScript}\n</script>`;
61
62 if (html.includes('</body>')) {
63 html = html.replace('</body>', `${injection}\n</body>`);
64 } else {
65 html += injection;
66 }
67
68 res.type('html').send(html);
69});
70
71// Watch for screen file changes
72chokidar.watch(SCREEN_FILE).on('change', () => {
73 console.log(JSON.stringify({ type: 'screen-updated', file: SCREEN_FILE }));
74 // Notify all browsers to reload
75 clients.forEach(ws => {
76 if (ws.readyState === WebSocket.OPEN) {
77 ws.send(JSON.stringify({ type: 'reload' }));
78 }
79 });
80});
81
82server.listen(PORT, '127.0.0.1', () => {
83 console.log(JSON.stringify({ type: 'server-started', port: PORT, url: `http://localhost:${PORT}` }));
84});
Step 3: Run npm install
Run: cd lib/brainstorm-server && npm install
Expected: Dependencies installed
Step 4: Test server starts
Run: cd lib/brainstorm-server && timeout 3 node index.js || true
Expected: See JSON with server-started and port info
Step 5: Commit
1git add lib/brainstorm-server/
2git commit -m "feat: add brainstorm server foundation"
Task 2: Create the Helper Library
Files:
- Create:
lib/brainstorm-server/helper.js
Step 1: Create helper.js with event auto-capture
1(function() {
2 const WS_URL = 'ws://' + window.location.host;
3 let ws = null;
4 let eventQueue = [];
5
6 function connect() {
7 ws = new WebSocket(WS_URL);
8
9 ws.onopen = () => {
10 // Send any queued events
11 eventQueue.forEach(e => ws.send(JSON.stringify(e)));
12 eventQueue = [];
13 };
14
15 ws.onmessage = (msg) => {
16 const data = JSON.parse(msg.data);
17 if (data.type === 'reload') {
18 window.location.reload();
19 }
20 };
21
22 ws.onclose = () => {
23 // Reconnect after 1 second
24 setTimeout(connect, 1000);
25 };
26 }
27
28 function send(event) {
29 event.timestamp = Date.now();
30 if (ws && ws.readyState === WebSocket.OPEN) {
31 ws.send(JSON.stringify(event));
32 } else {
33 eventQueue.push(event);
34 }
35 }
36
37 // Auto-capture clicks on interactive elements
38 document.addEventListener('click', (e) => {
39 const target = e.target.closest('button, a, [data-choice], [role="button"], input[type="submit"]');
40 if (!target) return;
41
42 // Don't capture regular link navigation
43 if (target.tagName === 'A' && !target.dataset.choice) return;
44
45 e.preventDefault();
46
47 send({
48 type: 'click',
49 text: target.textContent.trim(),
50 choice: target.dataset.choice || null,
51 id: target.id || null,
52 className: target.className || null
53 });
54 });
55
56 // Auto-capture form submissions
57 document.addEventListener('submit', (e) => {
58 e.preventDefault();
59 const form = e.target;
60 const formData = new FormData(form);
61 const data = {};
62 formData.forEach((value, key) => { data[key] = value; });
63
64 send({
65 type: 'submit',
66 formId: form.id || null,
67 formName: form.name || null,
68 data: data
69 });
70 });
71
72 // Auto-capture input changes (debounced)
73 let inputTimeout = null;
74 document.addEventListener('input', (e) => {
75 const target = e.target;
76 if (!target.matches('input, textarea, select')) return;
77
78 clearTimeout(inputTimeout);
79 inputTimeout = setTimeout(() => {
80 send({
81 type: 'input',
82 name: target.name || null,
83 id: target.id || null,
84 value: target.value,
85 inputType: target.type || target.tagName.toLowerCase()
86 });
87 }, 500); // 500ms debounce
88 });
89
90 // Expose for explicit use if needed
91 window.brainstorm = {
92 send: send,
93 choice: (value, metadata = {}) => send({ type: 'choice', value, ...metadata })
94 };
95
96 connect();
97})();
Step 2: Verify helper.js is syntactically valid
Run: node -c lib/brainstorm-server/helper.js
Expected: No syntax errors
Step 3: Commit
1git add lib/brainstorm-server/helper.js
2git commit -m "feat: add browser helper library for event capture"
Task 3: Write Tests for the Server
Files:
- Create:
tests/brainstorm-server/server.test.js - Create:
tests/brainstorm-server/package.json
Step 1: Create test package.json
1{
2 "name": "brainstorm-server-tests",
3 "version": "1.0.0",
4 "scripts": {
5 "test": "node server.test.js"
6 }
7}
Step 2: Write server tests
1const { spawn } = require('child_process');
2const http = require('http');
3const WebSocket = require('ws');
4const fs = require('fs');
5const path = require('path');
6const assert = require('assert');
7
8const SERVER_PATH = path.join(__dirname, '../../lib/brainstorm-server/index.js');
9const TEST_PORT = 3334;
10const TEST_SCREEN = '/tmp/brainstorm-test/screen.html';
11
12// Clean up test directory
13function cleanup() {
14 if (fs.existsSync(path.dirname(TEST_SCREEN))) {
15 fs.rmSync(path.dirname(TEST_SCREEN), { recursive: true });
16 }
17}
18
19async function sleep(ms) {
20 return new Promise(resolve => setTimeout(resolve, ms));
21}
22
23async function fetch(url) {
24 return new Promise((resolve, reject) => {
25 http.get(url, (res) => {
26 let data = '';
27 res.on('data', chunk => data += chunk);
28 res.on('end', () => resolve({ status: res.statusCode, body: data }));
29 }).on('error', reject);
30 });
31}
32
33async function runTests() {
34 cleanup();
35
36 // Start server
37 const server = spawn('node', [SERVER_PATH], {
38 env: { ...process.env, BRAINSTORM_PORT: TEST_PORT, BRAINSTORM_SCREEN: TEST_SCREEN }
39 });
40
41 let stdout = '';
42 server.stdout.on('data', (data) => { stdout += data.toString(); });
43 server.stderr.on('data', (data) => { console.error('Server stderr:', data.toString()); });
44
45 await sleep(1000); // Wait for server to start
46
47 try {
48 // Test 1: Server starts and outputs JSON
49 console.log('Test 1: Server startup message');
50 assert(stdout.includes('server-started'), 'Should output server-started');
51 assert(stdout.includes(TEST_PORT.toString()), 'Should include port');
52 console.log(' PASS');
53
54 // Test 2: GET / returns HTML with helper injected
55 console.log('Test 2: Serves HTML with helper injected');
56 const res = await fetch(`http://localhost:${TEST_PORT}/`);
57 assert.strictEqual(res.status, 200);
58 assert(res.body.includes('brainstorm'), 'Should include brainstorm content');
59 assert(res.body.includes('WebSocket'), 'Should have helper.js injected');
60 console.log(' PASS');
61
62 // Test 3: WebSocket connection and event relay
63 console.log('Test 3: WebSocket relays events to stdout');
64 stdout = ''; // Reset stdout capture
65 const ws = new WebSocket(`ws://localhost:${TEST_PORT}`);
66 await new Promise(resolve => ws.on('open', resolve));
67
68 ws.send(JSON.stringify({ type: 'click', text: 'Test Button' }));
69 await sleep(100);
70
71 assert(stdout.includes('user-event'), 'Should relay user events');
72 assert(stdout.includes('Test Button'), 'Should include event data');
73 ws.close();
74 console.log(' PASS');
75
76 // Test 4: File change triggers reload notification
77 console.log('Test 4: File change notifies browsers');
78 const ws2 = new WebSocket(`ws://localhost:${TEST_PORT}`);
79 await new Promise(resolve => ws2.on('open', resolve));
80
81 let gotReload = false;
82 ws2.on('message', (data) => {
83 const msg = JSON.parse(data.toString());
84 if (msg.type === 'reload') gotReload = true;
85 });
86
87 // Modify the screen file
88 fs.writeFileSync(TEST_SCREEN, '<html><body>Updated</body></html>');
89 await sleep(500);
90
91 assert(gotReload, 'Should send reload message on file change');
92 ws2.close();
93 console.log(' PASS');
94
95 console.log('\nAll tests passed!');
96
97 } finally {
98 server.kill();
99 cleanup();
100 }
101}
102
103runTests().catch(err => {
104 console.error('Test failed:', err);
105 process.exit(1);
106});
Step 3: Run tests
Run: cd tests/brainstorm-server && npm install ws && node server.test.js
Expected: All tests pass
Step 4: Commit
1git add tests/brainstorm-server/
2git commit -m "test: add brainstorm server integration tests"
Task 4: Add Visual Companion to Brainstorming Skill
Files:
- Modify:
skills/brainstorming/SKILL.md - Create:
skills/brainstorming/visual-companion.md(supporting doc)
Step 1: Create the supporting documentation
Create skills/brainstorming/visual-companion.md:
1# Visual Companion Reference
2
3## Starting the Server
4
5Run as a background job:
6
7```bash
8node ${PLUGIN_ROOT}/lib/brainstorm-server/index.js
Tell the user: "I've started a visual companion at http://localhost:3333 - open it in a browser."
Pushing Screens
Write HTML to /tmp/brainstorm/screen.html. The server watches this file and auto-refreshes the browser.
Reading User Responses
Check the background task output for JSON events:
1{"type":"user-event","type":"click","text":"Option A","choice":"optionA","timestamp":1234567890}
2{"type":"user-event","type":"submit","data":{"notes":"My feedback"},"timestamp":1234567891}
Event types:
- click: User clicked button or
data-choiceelement - submit: User submitted form (includes all form data)
- input: User typed in field (debounced 500ms)
HTML Patterns
Choice Cards
1<div class="options">
2 <button data-choice="optionA">
3 <h3>Option A</h3>
4 <p>Description</p>
5 </button>
6 <button data-choice="optionB">
7 <h3>Option B</h3>
8 <p>Description</p>
9 </button>
10</div>
Interactive Mockup
1<div class="mockup">
2 <header data-choice="header">App Header</header>
3 <nav data-choice="nav">Navigation</nav>
4 <main data-choice="main">Content</main>
5</div>
Form with Notes
1<form>
2 <label>Priority: <input type="range" name="priority" min="1" max="5"></label>
3 <textarea name="notes" placeholder="Additional thoughts..."></textarea>
4 <button type="submit">Submit</button>
5</form>
Explicit JavaScript
1<button onclick="brainstorm.choice('custom', {extra: 'data'})">Custom</button>
**Step 2: Add visual companion section to brainstorming skill**
Add after "Key Principles" in `skills/brainstorming/SKILL.md`:
```markdown
## Visual Companion (Optional)
When brainstorming involves visual elements - UI mockups, wireframes, interactive prototypes - use the browser-based visual companion.
**When to use:**
- Presenting UI/UX options that benefit from visual comparison
- Showing wireframes or layout options
- Gathering structured feedback (ratings, forms)
- Prototyping click interactions
**How it works:**
1. Start the server as a background job
2. Tell user to open http://localhost:3333
3. Write HTML to `/tmp/brainstorm/screen.html` (auto-refreshes)
4. Check background task output for user interactions
The terminal remains the primary conversation interface. The browser is a visual aid.
**Reference:** See `visual-companion.md` in this skill directory for HTML patterns and API details.
Step 3: Verify the edits
Run: grep -A5 "Visual Companion" skills/brainstorming/SKILL.md
Expected: Shows the new section
Step 4: Commit
1git add skills/brainstorming/
2git commit -m "feat: add visual companion to brainstorming skill"
Task 5: Add Server to Plugin Ignore (Optional Cleanup)
Files:
- Check if
.gitignoreneeds node_modules exclusion for lib/brainstorm-server
Step 1: Check current gitignore
Run: cat .gitignore 2>/dev/null || echo "No .gitignore"
Step 2: Add node_modules if needed
If not already present, add:
lib/brainstorm-server/node_modules/
Step 3: Commit if changed
1git add .gitignore
2git commit -m "chore: ignore brainstorm-server node_modules"
Summary
After completing all tasks:
- Server at
lib/brainstorm-server/- Node.js server that watches HTML file and relays events - Helper library auto-injected - captures clicks, forms, inputs
- Tests at
tests/brainstorm-server/- verifies server behavior - Brainstorming skill updated with visual companion section and
visual-companion.mdreference doc
To use:
- Start server as background job:
node lib/brainstorm-server/index.js & - Tell user to open
http://localhost:3333 - Write HTML to
/tmp/brainstorm/screen.html - Check task output for user events