Files
pipelines/app/tool/runs_probe_server.mjs
T
alan 266916f92a Runs: multi-select delete, run sizes and Largest-first sort
- Select mode (bar Select or long-press): per-row checkboxes, per-day
  Select all/Deselect all over finished runs only, "N selected" with the
  selection size, Delete and Done. Active runs get a disabled checkbox
  whose semantics give the reason.
- Native destructive confirmation, then delete_runs {run_ids} (batched by
  1000); the nested runs_deleted reply removes deleted rows and reports
  "Deleted N runs, freed X" plus refusals verbatim. runs_removed pushes
  remove rows and close an open detail; a deleted open run closes too.
  Delete run in the row and detail menus.
- size_bytes shown compactly in rows (0/absent = unknown, nothing shown),
  updated from run_event frames that carry it; Largest first sort (flat,
  unknowns last); the sort choice persists.
- Shared AppListRow gains selectionControl and onLongPress.
- Browser probe tool/runs_delete_probe.mjs; fixture server implements
  delete_runs/runs_removed.
2026-10-31 22:19:36 +00:00

712 lines
24 KiB
JavaScript

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: 'canceled', executing: false,
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, runDetail, files = {}, chatMessages, chatSessions, chatShells = [], chatShellOutput = '', chatHistoryDelayMs = 0, onChatHistory }) {
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 = [];
// `delete_runs` removes finished runs from later `list_runs` replies and
// broadcasts `runs_removed`, as the server's contract describes.
const deleted = new Set();
const deleteRequests = [];
let decisionAccepted = false;
const decisionRequests = [];
let chatSubscribed = 0;
let chatHistory = 0;
const chatPrompts = [];
const chatCreateRequests = [];
const createdChats = [];
const shellOutputRequests = [];
const fileReads = [];
let chatRunning = false;
let chatInterrupts = 0;
const searchRequests = [];
const CHAT_SESSION = {
id: 'ses_probechat',
title: 'Probe conversation',
kind: 'operator',
directory: '/srv/probe',
updated_at: '2026-10-21T12:00:00Z',
backend: 'claude',
mode: 'default',
mode_name: 'Ask for permission',
};
const CHAT_MODES = [
{ id: 'default', name: 'Ask for permission', description: 'Ask before edits and commands.' },
{ id: 'acceptEdits', name: 'Accept edits', description: 'Make file edits without asking; ask for other actions.' },
{ id: 'plan', name: 'Plan', description: 'Explore and plan without changing anything.' },
{ id: 'auto', name: 'Auto', description: "Act without asking, with Claude Code's safety checks." },
{ id: 'bypassPermissions', name: 'Bypass permissions', description: 'Never ask. Everything runs without checks.' },
];
const chatModeRequests = [];
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/chat-event' && req.method === 'POST') {
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
const event = JSON.parse(Buffer.concat(chunks).toString('utf8'));
if (event.kind === 'step') chatRunning = event.step?.status !== 'ended';
if (event.kind === 'shell' && event.shell?.id) {
chatShells = [...chatShells.filter(shell => shell.id !== event.shell.id), event.shell];
}
broadcast({ type: 'chat_event', chat_event: {
session_id: CHAT_SESSION.id, ...event,
} });
res.writeHead(200, { 'content-type': 'application/json' }).end('{"ok":true}');
return;
}
if (Object.hasOwn(files, pathname)) {
fileReads.push(pathname);
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' }).end(files[pathname]);
return;
}
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,
chatModeRequests,
live,
connections: connections.size,
refuse,
dropped,
listRuns,
getRun,
cancelRequests,
decisionRequests,
chatSubscribed,
chatHistory,
chatPrompts,
chatCreateRequests,
shellOutputRequests,
chatRunning,
chatInterrupts,
fileReads,
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: async (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.filter((run) => !deleted.has(run.id)).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++;
if (runDetail) {
client.send({ id: request.id, type: 'run', run_detail: runDetail });
return;
}
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 === 'delete_runs') {
const ids = Array.isArray(request.run_ids) ? request.run_ids : [];
deleteRequests.push({ run_ids: ids });
const done = [];
const refused = [];
let freed = 0;
for (const id of ids) {
const run = runs.find((item) => item.id === id);
if (!run || deleted.has(id)) {
refused.push({ run_id: id, reason: 'run not found' });
} else if (run.executing || ['running', 'waiting', 'queued', 'pending'].includes(run.status)) {
refused.push({ run_id: id, reason: 'run is still active' });
} else {
deleted.add(id);
done.push(id);
freed += run.size_bytes ?? 0;
}
}
client.send({ id: request.id, type: 'runs_deleted', runs_deleted: { deleted: done, refused, freed_bytes: freed } });
if (done.length) {
for (const other of connections) other.send({ type: 'runs_removed', run_ids: done });
}
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: [...(chatSessions ?? [CHAT_SESSION]), ...createdChats] });
return;
}
if (request.type === 'chat_directories') {
client.send({ id: request.id, type: 'chat_directories', chat_directories: ['/home/fixture', '/srv/probe'] });
return;
}
if (request.type === 'chat_backends') {
client.send({ id: request.id, type: 'chat_backends', chat_backends: ['opencode', 'claude'] });
return;
}
if (request.type === 'chat_create') {
const body = request.chat_create ?? {};
chatCreateRequests.push(body);
const session = { id: 'fixture_created_' + chatCreateRequests.length,
title: body.title, directory: body.directory, backend: body.backend };
createdChats.push(session);
client.send({ id: request.id, type: 'chat_create', chat_session: 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', chat_queued: chatRunning }), 300);
return;
}
if (request.type === 'chat_modes') {
client.send({ id: request.id, type: 'chat_modes', chat_modes: CHAT_MODES,
chat_mode: { session_id: CHAT_SESSION.id, mode: CHAT_SESSION.mode } });
return;
}
if (request.type === 'chat_mode') {
const mode = CHAT_MODES.find((entry) => entry.id === request.chat_mode?.mode);
chatModeRequests.push(request.chat_mode);
if (!mode) {
client.send({ id: request.id, type: 'error', error: 'unknown Claude permission mode' });
return;
}
CHAT_SESSION.mode = mode.id;
CHAT_SESSION.mode_name = mode.name;
client.send({ id: request.id, type: 'chat_mode', chat_mode: { session_id: CHAT_SESSION.id, mode: mode.id } });
return;
}
if (request.type === 'chat_shells') {
client.send({ id: request.id, type: 'chat_shells', chat_shells: chatShells });
return;
}
if (request.type === 'chat_shell_output') {
const query = request.chat_shell_output_query ?? {};
shellOutputRequests.push(query);
const shell = chatShells.find(shell => shell.id === query.shell_id);
client.send({ id: request.id, type: 'chat_shell_output', chat_shell_output:
shell ? { shell, output: chatShellOutput } : { unavailable: true } });
return;
}
if (request.type === 'chat_interrupt') {
chatInterrupts++;
client.send({ id: request.id, type: 'chat_interrupt' });
return;
}
if (request.type === 'chat_messages') {
chatHistory++;
onChatHistory?.('request');
// Optional loopback latency for a probe that separates the history
// read from rendering; the default replies immediately as before.
if (chatHistoryDelayMs > 0) await new Promise((r) => setTimeout(r, chatHistoryDelayMs));
onChatHistory?.('reply');
client.send({
id: request.id, type: 'chat_history',
chat_history: {
messages: chatMessages ?? [
{ 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;
},
get deleteRequests() {
return deleteRequests;
},
close: () =>
new Promise((resolveClose) => {
for (const connection of connections) connection.close();
server.close(() => resolveClose());
for (const socket of sockets) socket.destroy();
}),
};
}