import { createHash } from 'node:crypto'; import { createServer } from 'node:http'; import { readFile, realpath, stat } from 'node:fs/promises'; import { extname, join, resolve, sep } from 'node:path'; import { once } from 'node:events'; const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8', '.wasm': 'application/wasm', '.css': 'text/css; charset=utf-8', '.png': 'image/png', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.ttf': 'font/ttf', '.otf': 'font/otf', '.woff': 'font/woff', '.woff2': 'font/woff2', }; const RUNS = [ { id: 1, title: 'Fixture live run', name: 'fixture-live', status: 'running', created_at: '2026-10-21T12:00:00Z', pipeline_id: 10, }, { id: 2, title: 'Fixture pending run', name: 'fixture-pending', status: 'running', created_at: '2026-10-21T11:00:00Z', pipeline_id: 10, }, { id: 3, title: 'Fixture failing run', name: 'fixture-failing', status: 'failed', created_at: '2026-10-21T10:00:00Z', pipeline_id: 10, }, { id: 4, title: 'Fixture cancel run', name: 'fixture-cancel', status: 'running', executing: true, created_at: '2026-10-21T09:00:00Z', pipeline_id: 10, }, { id: 5, title: 'Fixture human run', name: 'fixture-human', status: 'waiting', executing: false, created_at: '2026-10-21T08:00:00Z', pipeline_id: 10, }, ]; function humanDetail(accepted, runs = RUNS) { return { ...runs.find((run) => run.id === 5), status: accepted ? 'succeeded' : 'waiting', current_stage: 'gate', input: { prompt: 'Fixture human decision' }, graph: { stages: [{ key: 'gate', type: 'human', edges: { approve: '#success' } }] }, steps: [{ sequence: 1, stage: 'gate', status: accepted ? 'completed' : 'waiting', output: { prompt: 'Please review this recorded checkpoint.', options: ['approve'] }, }], }; } const LIVE_EVENT = { type: 'run_event', run_id: 1, status: 'succeeded', outcome: 'success', completed_steps: 2, current_stage: 'test', finished_at: '2026-10-21T12:05:00Z', }; function detail(id, live, canceled = false, runs = RUNS) { const status = canceled ? 'canceled' : id === 1 && live ? 'succeeded' : id === 3 ? 'failed' : 'running'; return { id, title: runs.find((run) => run.id === id)?.title ?? `Run ${id}`, name: 'fixture-pipeline', status, executing: status === 'running', input: { prompt: ' fixture prompt with spaces ', note: 'input payload', }, output: { answer: 42, nested: { ok: true } }, usage: { stages: 2, tokens_total: 120, tokens_known_stages: 2, tokens_in: 70, tokens_out: 50, split_known: true, cost_known_stages: 2, cost_usd: 0.25, }, steps: [ { stage: 'build', sequence: 3, status: 'completed', outcome: 'success', target: '#success', file_changes: { status: 'complete', scope: 'Git tracked and nonignored files in the run directory', files: [ { path: 'lib/features/fixture.dart', kind: 'modified', patch: '--- a/lib/features/fixture.dart\n' + '+++ b/lib/features/fixture.dart\n' + '@@ -1,2 +1,2 @@\n' + ' context line\n' + '-removed fixture line\n' + '+added fixture line\n', }, ], skipped: 0, omitted: 0, diagnostic: '', }, artifacts: [ { name: 'build-report.html', size_bytes: 2048, content_type: 'text/html; charset=utf-8', url: '/artifacts/1/3/build-report.html', }, ], }, { stage: 'test', sequence: 4, status: status === 'failed' ? 'failed' : 'completed', outcome: status === 'failed' ? 'failure' : 'success', target: status === 'failed' ? '#failure' : '#success', artifacts: [ { name: 'result.csv', size_bytes: 4096, content_type: 'text/csv', url: '/artifacts/1/4/result.csv', }, ], }, ], }; } function accept(key) { return createHash('sha1') .update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`) .digest('base64'); } function frame(opcode, payload) { const length = payload.length; let header; if (length < 126) { header = Buffer.from([0x80 | opcode, length]); } else if (length < 65536) { header = Buffer.alloc(4); header[0] = 0x80 | opcode; header[1] = 126; header.writeUInt16BE(length, 2); } else { header = Buffer.alloc(10); header[0] = 0x80 | opcode; header[1] = 127; header.writeBigUInt64BE(BigInt(length), 2); } return Buffer.concat([header, payload]); } class Connection { constructor(socket, owner) { this.socket = socket; this.owner = owner; this.buffer = Buffer.alloc(0); this.fragments = []; this.fragmentOpcode = 0; } push(chunk) { if (chunk?.length) this.buffer = Buffer.concat([this.buffer, chunk]); this.parse(); } parse() { while (this.buffer.length >= 2) { const first = this.buffer[0]; const second = this.buffer[1]; const fin = (first & 0x80) !== 0; const opcode = first & 0x0f; const masked = (second & 0x80) !== 0; let length = second & 0x7f; let offset = 2; if (length === 126) { if (this.buffer.length < 4) return; length = this.buffer.readUInt16BE(2); offset = 4; } else if (length === 127) { if (this.buffer.length < 10) return; const big = this.buffer.readBigUInt64BE(2); if (big > BigInt(Number.MAX_SAFE_INTEGER)) return this.close(); length = Number(big); offset = 10; } const maskOffset = offset; if (masked) { if (this.buffer.length < offset + 4) return; offset += 4; } if (this.buffer.length < offset + length) return; let payload = Buffer.from(this.buffer.subarray(offset, offset + length)); if (masked) { const mask = this.buffer.subarray(maskOffset, maskOffset + 4); for (let index = 0; index < payload.length; index++) { payload[index] ^= mask[index % 4]; } } this.buffer = this.buffer.subarray(offset + length); this.handleFrame(fin, opcode, payload); } } handleFrame(fin, opcode, payload) { if (opcode === 0x8) return this.close(); if (opcode === 0x9) return void this.socket.write(frame(0x0a, payload)); if (opcode === 0x0a) return; if (opcode === 0x0) { this.fragments.push(payload); if (fin) { const data = Buffer.concat(this.fragments); this.fragments = []; this.message(this.fragmentOpcode, data); } return; } if (opcode !== 0x1) return; if (!fin) { this.fragmentOpcode = opcode; this.fragments = [payload]; return; } this.message(opcode, payload); } message(_opcode, payload) { let request; try { request = JSON.parse(payload.toString('utf8')); } catch { return; } this.owner.onMessage(this, request); } send(value) { if (this.socket.destroyed) return; this.socket.write(frame(0x1, Buffer.from(JSON.stringify(value)))); } close() { if (!this.socket.destroyed) this.socket.end(); } } async function staticFile(base, pathname, req, res) { let file = resolve(base, `.${pathname}`); if (file !== base && !file.startsWith(base + sep)) { res.writeHead(403).end(); return; } try { if ((await stat(file)).isDirectory()) file = join(file, 'index.html'); } catch { if (extname(pathname)) { res.writeHead(404).end('not found'); return; } file = join(base, 'index.html'); } try { const body = await readFile(file); res .writeHead(200, { 'content-type': MIME[extname(file)] ?? 'application/octet-stream', 'cache-control': 'no-store', }) .end(req.method === 'HEAD' ? undefined : body); } catch { res.writeHead(404).end('not found'); } } /** * A deterministic, isolated Pipelines protocol fixture for the browser probe. * It serves the built probe bundle and upgrades /connect on the same origin, so * the normal web composition infers this server from Uri.base. */ export async function startFixture({ root, runs = RUNS }) { const base = await realpath(root); const connections = new Set(); const sockets = new Set(); let subscribed = 0; let live = false; let refuse = false; let dropped = 0; let listRuns = 0; let getRun = 0; const canceled = new Set(); const cancelRequests = []; let decisionAccepted = false; const decisionRequests = []; let chatSubscribed = 0; let chatHistory = 0; const chatPrompts = []; const searchRequests = []; const CHAT_SESSION = { id: 'ses_probechat', title: 'Probe conversation', kind: 'operator', directory: '/srv/probe', updated_at: '2026-10-21T12:00:00Z', }; const dropConnections = () => { for (const connection of connections) connection.close(); connections.clear(); dropped++; }; const broadcast = (value) => { for (const connection of connections) connection.send(value); }; const server = createServer(async (req, res) => { const pathname = new URL(req.url, 'http://fixture').pathname; if (pathname === '/fixture/live' && req.method === 'POST') { live = true; broadcast(LIVE_EVENT); res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}'); return; } if (pathname === '/fixture/drop' && req.method === 'POST') { dropConnections(); res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}'); return; } if (pathname === '/fixture/refuse' && req.method === 'POST') { refuse = true; dropConnections(); res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}'); return; } if (pathname === '/fixture/accept' && req.method === 'POST') { refuse = false; res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}'); return; } if (pathname === '/fixture/state') { res .writeHead(200, { 'content-type': 'application/json' }) .end(JSON.stringify({ subscribed, live, connections: connections.size, refuse, dropped, listRuns, getRun, cancelRequests, decisionRequests, chatSubscribed, chatHistory, chatPrompts, searchRequests, })); return; } if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405).end(); return; } await staticFile(base, pathname, req, res); }); server.on('upgrade', (req, socket, head) => { if (refuse) { socket.end('HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\n'); return; } const url = new URL(req.url, 'http://fixture'); if ( url.pathname !== '/connect' || req.headers.upgrade?.toLowerCase() !== 'websocket' || !req.headers['sec-websocket-key'] ) { socket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n'); return; } socket.write( 'HTTP/1.1 101 Switching Protocols\r\n' + 'Upgrade: websocket\r\n' + 'Connection: Upgrade\r\n' + `Sec-WebSocket-Accept: ${accept(req.headers['sec-websocket-key'])}\r\n\r\n`, ); const connection = new Connection(socket, { onMessage: (client, request) => { if (request.type === 'subscribe') { // The real server may not acknowledge `subscribe`; keep it silent so // the app's send-only path is exercised. subscribed++; return; } if (request.type === 'unsubscribe') return; if (request.type === 'ping') { client.send({ id: request.id, type: 'pong', build: { version: 'Fixture settings build' }, time: '2026-10-21T12:00:00Z', }); return; } if (request.type === 'list_runs') { listRuns++; client.send({ id: request.id, type: 'runs', runs: runs.map((run) => canceled.has(run.id) ? { ...run, status: 'canceled', executing: false } : run.id === 5 && decisionAccepted ? { ...run, status: 'succeeded' } : run), usage: null }); return; } if (request.type === 'get_run') { getRun++; const id = request.run_id; if (id === 2) { // Deliberately slow so the browser sees the pending/Back state; // it must still answer so the serialized request queue continues. setTimeout(() => { client.send({ id: request.id, type: 'run', run_detail: detail(2, live, false, runs) }); }, 2500); return; } if (id === 3) { client.send({ id: request.id, type: 'error', error: 'Fixture detail failure: run 3 is unavailable', }); return; } client.send({ id: request.id, type: 'run', run_detail: id === 5 ? humanDetail(decisionAccepted, runs) : detail(id, live, canceled.has(id), runs) }); return; } if (request.type === 'cancel_run' && request.run_id === 4) { cancelRequests.push({ run_id: request.run_id }); canceled.add(4); client.send({ id: request.id, type: 'run', run_detail: detail(4, live, true, runs) }); return; } if (request.type === 'decide_run' && request.run_id === 5 && request.stage === 'gate' && request.option === 'approve') { decisionRequests.push({ run_id: request.run_id, stage: request.stage, option: request.option, ...(request.feedback ? { feedback: request.feedback } : {}) }); decisionAccepted = true; client.send({ id: request.id, type: 'run', run_detail: humanDetail(true, runs) }); return; } if (request.type === 'search') { // Deterministic wire fixture for the Search page probe: the app's // exact request body is recorded and answered with one hit per kind // it can target. No production server or operator data is involved. const search = request.search ?? {}; searchRequests.push(search); const query = String(search.query ?? ''); client.send({ id: request.id, type: 'search_results', search_results: { query, kind: search.kind ?? '', results: query.trim() ? [ { kind: 'run', target: 'run:1', run: { id: 1, pipeline_name: 'Fixture live run', status: 'running', workspace: '/srv/probe', created_at: '2026-10-21T12:00:00Z' } }, { kind: 'pipeline', target: 'pipeline:10', pipeline: { id: 10, name: 'Fixture pipeline', version: 1, stages: 2 } }, ] : [], truncated: false, scanned_steps: 4, scanned_bytes: 512, cap: 50, scan_bound_bytes: 1048576, }, }); return; } if (request.type === 'chat_sessions') { client.send({ id: request.id, type: 'chat_sessions', chat_sessions: [CHAT_SESSION] }); return; } if (request.type === 'chat_subscribe') { chatSubscribed++; client.send({ id: request.id, type: 'chat_subscribe' }); return; } if (request.type === 'chat_prompt') { const body = request.chat_prompt ?? {}; chatPrompts.push({ session_id: body.session_id, text: body.text, operation_id: body.operation_id, native_message_id: body.native_message_id }); setTimeout(() => client.send({ id: request.id, type: 'chat_prompt' }), 300); return; } if (request.type === 'chat_messages') { chatHistory++; client.send({ id: request.id, type: 'chat_history', chat_history: { messages: [ { id: 'm1', session_id: CHAT_SESSION.id, role: 'user', parts: [{ type: 'text', text: 'Read-only probe question.' }] }, { id: 'm2', session_id: CHAT_SESSION.id, role: 'assistant', parts: [{ type: 'text', text: 'Stored probe answer.' }] }, ], next_cursor: '', has_more: false, }, }); return; } client.send({ id: request.id, type: 'error', error: `Fixture does not implement ${request.type}`, }); }, }); connections.add(connection); socket.on('data', (chunk) => connection.push(chunk)); socket.on('close', () => connections.delete(connection)); socket.on('error', () => connections.delete(connection)); connection.push(head); }); server.listen(0, '127.0.0.1'); await once(server, 'listening'); server.on('connection', (socket) => { sockets.add(socket); socket.on('close', () => sockets.delete(socket)); }); const port = server.address().port; return { server, port, url: `http://127.0.0.1:${port}`, get subscribed() { return subscribed; }, close: () => new Promise((resolveClose) => { for (const connection of connections) connection.close(); server.close(() => resolveClose()); for (const socket of sockets) socket.destroy(); }), }; }