@firstpick/pi-package-webui 0.7.6 → 0.7.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +60 -4
  2. package/bin/pi-webui-rpc-supervisor.mjs +612 -0
  3. package/bin/pi-webui.mjs +1051 -95
  4. package/lib/WEBUI_TUI_NATIVE_PARITY.json +13 -0
  5. package/lib/rpc-supervisor-client.mjs +317 -0
  6. package/lib/rpc-supervisor-protocol.mjs +245 -0
  7. package/lib/rpc-supervisor-state.mjs +165 -0
  8. package/lib/trust-boundaries.mjs +1 -0
  9. package/package.json +4 -4
  10. package/public/app.js +1986 -170
  11. package/public/index.html +388 -25
  12. package/public/issue-bot-client.mjs +344 -0
  13. package/public/issue-wizard-state.mjs +443 -0
  14. package/public/service-worker.js +8 -1
  15. package/public/styles.css +578 -52
  16. package/public/subagent-gate-visibility.mjs +36 -0
  17. package/public/workflow-status-stack.mjs +69 -0
  18. package/tests/app-runner-process-tree-harness.test.mjs +37 -3
  19. package/tests/boot-failure-diagnostics.test.mjs +180 -0
  20. package/tests/completion-signal-contract.test.mjs +156 -0
  21. package/tests/cwd-footer-reliability-static.test.mjs +107 -0
  22. package/tests/durable-rpc-supervisor-harness.test.mjs +275 -0
  23. package/tests/fast-mode-client-static.test.mjs +2 -2
  24. package/tests/fixtures/fake-pi.mjs +90 -6
  25. package/tests/footer-context-contrast-static.test.mjs +10 -0
  26. package/tests/git-panel-file-preview-static.test.mjs +221 -0
  27. package/tests/git-panel-render-stability-static.test.mjs +11 -1
  28. package/tests/http-endpoints-harness.test.mjs +458 -33
  29. package/tests/issue-bot-client.test.mjs +135 -0
  30. package/tests/issue-wizard-state.test.mjs +126 -0
  31. package/tests/mobile-static.test.mjs +79 -16
  32. package/tests/native-parity-harness.test.mjs +2 -1
  33. package/tests/native-parity.test.mjs +13 -2
  34. package/tests/numpad-decimal-input-static.test.mjs +128 -0
  35. package/tests/open-issue-wizard-static.test.mjs +75 -0
  36. package/tests/prompt-routing-input-clear-static.test.mjs +34 -0
  37. package/tests/prompt-routing-tab-status.test.mjs +108 -0
  38. package/tests/rpc-supervisor-host.test.mjs +408 -0
  39. package/tests/rpc-supervisor-protocol.test.mjs +93 -0
  40. package/tests/rpc-supervisor-state.test.mjs +62 -0
  41. package/tests/run-all.mjs +4 -1
  42. package/tests/streaming-ui-coupling.test.mjs +18 -2
  43. package/tests/subagent-gate-visibility.test.mjs +66 -0
  44. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  45. package/tests/subagents-helper.test.mjs +136 -0
  46. package/tests/terminal-tab-workspace-static.test.mjs +99 -0
  47. package/tests/workflow-status-stack.test.mjs +87 -0
  48. package/webui-rpc-helper.mjs +160 -2
@@ -0,0 +1,408 @@
1
+ import assert from "node:assert/strict";
2
+ import { createConnection, createServer } from "node:net";
3
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { setTimeout as delay } from "node:timers/promises";
8
+ import {
9
+ RPC_SUPERVISOR_CHILD_ARG_LIMIT,
10
+ RPC_SUPERVISOR_EVENT_RING_MAX_BYTES,
11
+ RPC_SUPERVISOR_REQUEST_DEDUPE_LIMIT,
12
+ } from "../lib/rpc-supervisor-protocol.mjs";
13
+ import {
14
+ RpcSupervisorClient,
15
+ discoverStartAttachRpcSupervisor,
16
+ } from "../lib/rpc-supervisor-client.mjs";
17
+ import {
18
+ readSupervisorState,
19
+ removeSupervisorState,
20
+ supervisorPaths,
21
+ writeSupervisorState,
22
+ } from "../lib/rpc-supervisor-state.mjs";
23
+
24
+ const root = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
25
+ const fakePi = path.join(root, "tests", "fixtures", "fake-pi.mjs");
26
+ const work = await mkdtemp(path.join(tmpdir(), "pi-webui-rpc-supervisor-host-"));
27
+ const agentDir = path.join(work, "agent");
28
+ const port = 35000 + Math.floor(Math.random() * 15000);
29
+ const logFile = path.join(work, "commands.jsonl");
30
+ const rawLogFile = path.join(work, "raw-pi.jsonl");
31
+ const rawPiScript = String.raw`
32
+ const { appendFileSync } = require("node:fs");
33
+ const { createInterface } = require("node:readline");
34
+ const log = process.env.RAW_PI_LOG;
35
+ const send = (value) => process.stdout.write(JSON.stringify(value) + "\n");
36
+ createInterface({ input: process.stdin }).on("line", (line) => {
37
+ const command = JSON.parse(line);
38
+ appendFileSync(log, line + "\n");
39
+ if (command.type === "hold") {
40
+ setTimeout(() => process.exit(0), 2500).unref();
41
+ return;
42
+ }
43
+ if (command.type === "pause_stdin") {
44
+ send({ type: "response", id: command.id, data: { paused: true } });
45
+ setInterval(() => {}, 1000);
46
+ process.stdin.pause();
47
+ return;
48
+ }
49
+ if (command.type === "no_response" || command.type === "extension_ui_response") return;
50
+ if (command.type === "flood") {
51
+ send({ type: "response", id: command.id, data: { accepted: true } });
52
+ for (let index = 0; index < 80; index += 1) send({ type: "large_event", index, tokens: { keep: index }, body: "r".repeat(72 * 1024) });
53
+ return;
54
+ }
55
+ if (command.type === "emit_one") {
56
+ send({ type: "response", id: command.id, data: { accepted: true } });
57
+ send({ type: "other_tab_live_event", tokens: { keep: true } });
58
+ return;
59
+ }
60
+ send({ type: "response", id: command.id, data: command });
61
+ });
62
+ `;
63
+
64
+ async function listen(server, socketPath) {
65
+ const connections = new Set();
66
+ server.__testConnections = connections;
67
+ server.on("connection", (socket) => {
68
+ connections.add(socket);
69
+ socket.on("close", () => connections.delete(socket));
70
+ });
71
+ await new Promise((resolve, reject) => {
72
+ server.once("error", reject);
73
+ server.listen(socketPath, () => {
74
+ server.off("error", reject);
75
+ resolve();
76
+ });
77
+ });
78
+ }
79
+
80
+ async function closeServer(server) {
81
+ for (const socket of server.__testConnections || []) socket.destroy();
82
+ await new Promise((resolve) => server.close(() => resolve()));
83
+ }
84
+
85
+ async function rawLines() {
86
+ const text = await readFile(rawLogFile, "utf8").catch(() => "");
87
+ return text.split("\n").filter(Boolean).map((line) => JSON.parse(line));
88
+ }
89
+
90
+ async function waitFor(label, predicate, timeoutMs = 5_000) {
91
+ const deadline = Date.now() + timeoutMs;
92
+ while (Date.now() < deadline) {
93
+ const value = await predicate();
94
+ if (value) return value;
95
+ await delay(20);
96
+ }
97
+ throw new Error(`${label} did not happen within ${timeoutMs}ms`);
98
+ }
99
+
100
+ function pidIsAlive(pid) {
101
+ if (!Number.isInteger(pid) || pid < 1) return false;
102
+ try {
103
+ process.kill(pid, 0);
104
+ return true;
105
+ } catch (error) {
106
+ return error?.code === "EPERM";
107
+ }
108
+ }
109
+
110
+ let client;
111
+ let replacement;
112
+ let replayClient;
113
+ try {
114
+ client = await discoverStartAttachRpcSupervisor({
115
+ agentDir,
116
+ port,
117
+ environment: { ...process.env, FAKE_PI_LOG_FILE: logFile, RAW_PI_LOG: rawLogFile },
118
+ startupTimeoutMs: 10_000,
119
+ });
120
+ const created = await client.createTab({
121
+ tabId: "tab-1",
122
+ metadata: { title: "One", index: 0, cwd: work, sessionFile: path.join(work, "one.jsonl"), apiToken: "never-persist" },
123
+ child: { command: process.execPath, args: [fakePi], cwd: work },
124
+ });
125
+ assert.equal(created.id, "tab-1");
126
+ assert.ok(created.pid > 0);
127
+ await client.createTab({
128
+ tabId: "raw-tab",
129
+ metadata: { title: "Raw", index: 1, cwd: work, sessionFile: path.join(work, "raw.jsonl") },
130
+ child: { command: process.execPath, args: ["-e", rawPiScript], cwd: work },
131
+ });
132
+ await assert.rejects(
133
+ Promise.race([
134
+ client.createTab({
135
+ tabId: "invalid-arg-tab",
136
+ metadata: { title: "Invalid", index: 2, cwd: work },
137
+ child: { command: process.execPath, args: Array.from({ length: RPC_SUPERVISOR_CHILD_ARG_LIMIT + 1 }, () => "x"), cwd: work },
138
+ }),
139
+ delay(1_000).then(() => { throw new Error("validation failure was not correlated to the create request"); }),
140
+ ]),
141
+ /at most 1024 entries/,
142
+ "invalid create frames must reject their matching client request instead of hanging",
143
+ );
144
+
145
+ const response = await Promise.all([
146
+ client.command("tab-1", { type: "prompt", message: "dedupe me" }, { requestId: "prompt-once" }),
147
+ client.command("tab-1", { type: "prompt", message: "dedupe me" }, { requestId: "prompt-once" }),
148
+ ]);
149
+ assert.equal(response[0].data.output, "fake prompt accepted");
150
+ assert.deepEqual(response[0], response[1]);
151
+ await delay(60);
152
+ const logged = (await readFile(logFile, "utf8")).split("\n").filter(Boolean).map(JSON.parse);
153
+ assert.equal(logged.filter((entry) => entry.direction === "command" && entry.message === "dedupe me").length, 1, "duplicate request IDs must not write to Pi twice");
154
+
155
+ const rawCommand = {
156
+ type: "raw_round_trip",
157
+ message: "x".repeat(64 * 1024 + 1),
158
+ tokens: { input: 123, output: 456 },
159
+ entries: Array.from({ length: 257 }, (_, index) => ({ index, token: `token-${index}` })),
160
+ };
161
+ const rawResponse = await client.command("raw-tab", rawCommand, { requestId: "raw-round-trip" });
162
+ assert.equal(rawResponse.data.message.length, rawCommand.message.length, "live Pi responses must preserve long strings");
163
+ assert.equal(rawResponse.data.entries.length, 257, "live Pi responses must preserve arrays beyond metadata limits");
164
+ assert.deepEqual(rawResponse.data.tokens, rawCommand.tokens, "live Pi responses must preserve token-named fields");
165
+
166
+ const rawWrite = { type: "extension_ui_response", id: "ui-no-response", tokens: { private: "keep" }, entries: Array.from({ length: 257 }, (_, index) => index) };
167
+ await Promise.race([
168
+ client.write("raw-tab", rawWrite, { requestId: "raw-write-once" }),
169
+ delay(1_000).then(() => { throw new Error("raw write waited for a Pi response"); }),
170
+ ]);
171
+ const written = await waitFor("raw write log", async () => (await rawLines()).find((line) => line.type === "extension_ui_response"));
172
+ assert.deepEqual(written, rawWrite, "fire-and-forget writes must reach Pi unchanged and without an injected request ID");
173
+
174
+ const pendingCommand = client.command("raw-tab", { type: "no_response" }, { requestId: "pending-before-ui-write", timeoutMs: 700 });
175
+ await waitFor("pending command admission", async () => (await rawLines()).some((line) => line.type === "no_response"));
176
+ const queuedProbe = await Promise.race([
177
+ client.command("raw-tab", { type: "queued_behind_pending_response" }, { requestId: "queued-behind-pending-response", timeoutMs: 500 }),
178
+ delay(300).then(() => { throw new Error("a pending Pi response held the supervisor admission queue"); }),
179
+ ]);
180
+ assert.equal(queuedProbe.data.type, "queued_behind_pending_response", "later commands should be admitted without waiting for an earlier Pi response");
181
+ await Promise.race([
182
+ client.write("raw-tab", { type: "extension_ui_response", id: "ui-behind-pending-command" }, { requestId: "ui-behind-pending-command" }),
183
+ delay(300).then(() => { throw new Error("extension UI response deadlocked behind a pending Pi command"); }),
184
+ ]);
185
+ await waitFor("extension UI response behind pending command", async () => (await rawLines()).some((line) => line.id === "ui-behind-pending-command"));
186
+ await assert.rejects(pendingCommand, /Timed out waiting for RPC response/, "the deliberately unanswered command should retain its own response timeout");
187
+
188
+ const metadataUpdates = [];
189
+ let metadataSerial = 0;
190
+ const metadataFlood = setInterval(() => {
191
+ metadataSerial += 1;
192
+ metadataUpdates.push(client.updateTab("raw-tab", {
193
+ title: `Raw ${metadataSerial}`,
194
+ index: 1,
195
+ cwd: work,
196
+ sessionFile: path.join(work, "raw.jsonl"),
197
+ }));
198
+ }, 1);
199
+ try {
200
+ await delay(40);
201
+ const starvationProbe = await Promise.race([
202
+ client.command("raw-tab", { type: "metadata_starvation_probe" }, { requestId: "metadata-starvation-probe" }),
203
+ delay(3_000).then(() => { throw new Error("RPC command starved behind continuous metadata updates"); }),
204
+ ]);
205
+ assert.equal(starvationProbe.data.type, "metadata_starvation_probe", "commands should take a FIFO admission position instead of chasing a continuously moving metadata tail");
206
+ } finally {
207
+ clearInterval(metadataFlood);
208
+ const updateResults = await Promise.allSettled(metadataUpdates);
209
+ assert.ok(updateResults.length > 0 && updateResults.every((result) => result.status === "fulfilled"), "metadata flood must consist of successful updates");
210
+ }
211
+
212
+ const replacementCwd = path.join(work, "replacement-cwd");
213
+ await mkdir(replacementCwd);
214
+ const originalRawPid = client.snapshot.tabs.find((tab) => tab.id === "raw-tab")?.pid;
215
+ const paused = await client.command("raw-tab", { type: "pause_stdin" }, { requestId: "pause-stdin-before-replace" });
216
+ assert.equal(paused.data.paused, true);
217
+ const blockedWriteResult = client.write("raw-tab", {
218
+ type: "extension_ui_response",
219
+ id: "backpressured-before-replace",
220
+ body: "x".repeat(2 * 1024 * 1024),
221
+ }, { requestId: "backpressured-before-replace" }).then(
222
+ () => ({ status: "fulfilled" }),
223
+ (error) => ({ status: "rejected", error }),
224
+ );
225
+ const replacedRawTab = await Promise.race([
226
+ client.replaceTab({
227
+ tabId: "raw-tab",
228
+ metadata: { title: "Raw", index: 1, cwd: replacementCwd, sessionFile: path.join(work, "raw.jsonl") },
229
+ child: { command: process.execPath, args: ["-e", rawPiScript], cwd: replacementCwd },
230
+ }),
231
+ delay(5_000).then(() => { throw new Error("replacement remained blocked behind a backpressured one-way write"); }),
232
+ ]);
233
+ const blockedWrite = await blockedWriteResult;
234
+ assert.equal(blockedWrite.status, "rejected", "a backpressured one-way write must fail within a bounded interval");
235
+ assert.match(blockedWrite.error?.message || "", /Timed out flushing a one-way Pi RPC write/, "the bounded write failure should explain the queue blockage");
236
+ assert.equal(replacedRawTab.metadata.cwd, replacementCwd, "successful replacement should publish the child cwd atomically");
237
+ assert.notEqual(replacedRawTab.pid, originalRawPid, "successful replacement should expose the replacement child PID");
238
+ const replacedRawResponse = await client.command("raw-tab", { type: "replacement_probe" }, { requestId: "replacement-probe" });
239
+ assert.equal(replacedRawResponse.data.type, "replacement_probe", "replacement child should accept RPC commands after replace resolves");
240
+
241
+ const concurrentCwdA = path.join(work, "concurrent-cwd-a");
242
+ const concurrentCwdB = path.join(work, "concurrent-cwd-b");
243
+ await Promise.all([mkdir(concurrentCwdA), mkdir(concurrentCwdB)]);
244
+ const [concurrentA, concurrentB] = await Promise.all([
245
+ client.replaceTab({
246
+ tabId: "raw-tab",
247
+ metadata: { title: "Raw A", index: 1, cwd: concurrentCwdA, sessionFile: path.join(work, "raw.jsonl") },
248
+ child: { command: process.execPath, args: ["-e", rawPiScript], cwd: concurrentCwdA },
249
+ }),
250
+ client.replaceTab({
251
+ tabId: "raw-tab",
252
+ metadata: { title: "Raw B", index: 1, cwd: concurrentCwdB, sessionFile: path.join(work, "raw.jsonl") },
253
+ child: { command: process.execPath, args: ["-e", rawPiScript], cwd: concurrentCwdB },
254
+ }),
255
+ ]);
256
+ assert.equal(concurrentA.metadata.cwd, concurrentCwdA, "first queued replacement should resolve with its own committed cwd");
257
+ assert.equal(concurrentB.metadata.cwd, concurrentCwdB, "second queued replacement should resolve with its own committed cwd");
258
+ assert.notEqual(concurrentA.pid, concurrentB.pid, "serialized replacements should use distinct child processes");
259
+ await waitFor("superseded replacement child exit", () => !pidIsAlive(concurrentA.pid));
260
+ const concurrentProbe = await client.command("raw-tab", { type: "concurrent_replacement_probe" }, { requestId: "concurrent-replacement-probe" });
261
+ assert.equal(concurrentProbe.data.type, "concurrent_replacement_probe", "commands arriving after queued replacements should reach the final child");
262
+
263
+ const deliveredStartupEvents = [];
264
+ const unsubscribe = client.onEvent((event) => deliveredStartupEvents.push(event));
265
+ await client.command("raw-tab", { type: "emit_one" }, { requestId: "startup-buffer-event" });
266
+ await delay(50);
267
+ assert.equal(deliveredStartupEvents.length, 0, "events arriving during startup must wait for explicit hydration drain");
268
+ const drainedStartupEvents = client.drainStartupEvents();
269
+ assert.ok(drainedStartupEvents.some((event) => event.payload?.type === "other_tab_live_event"), "startup drain must retain other-tab live events");
270
+ assert.deepEqual(deliveredStartupEvents.map((event) => event.seq), drainedStartupEvents.map((event) => event.seq), "startup drain must deliver buffered events in order");
271
+ unsubscribe();
272
+
273
+ const paths = await supervisorPaths({ agentDir, port });
274
+ const state = await readSupervisorState(paths);
275
+ assert.equal(state.tabs.length, 2);
276
+ assert.equal(state.tabs.find((tab) => tab.id === "tab-1").metadata.apiToken, undefined, "private metadata fields must not reach the state snapshot");
277
+
278
+ const failedReplacementCwd = path.join(work, "failed-replacement-cwd");
279
+ await mkdir(failedReplacementCwd);
280
+ await assert.rejects(
281
+ client.replaceTab({
282
+ tabId: "tab-1",
283
+ metadata: { title: "One", index: 0, cwd: failedReplacementCwd, sessionFile: path.join(work, "one.jsonl") },
284
+ child: { command: path.join(work, "missing-pi-executable"), args: [], cwd: failedReplacementCwd },
285
+ }),
286
+ /ENOENT|spawn/i,
287
+ "replace should reject when the replacement child cannot spawn",
288
+ );
289
+ await delay(50);
290
+ const stateAfterFailedReplacement = await readSupervisorState(paths);
291
+ assert.equal(stateAfterFailedReplacement.tabs.find((tab) => tab.id === "tab-1").metadata.cwd, work, "failed replacement must not persist the requested cwd");
292
+
293
+ replacement = await discoverStartAttachRpcSupervisor({ agentDir, port, controllerId: "replacement-controller", startupTimeoutMs: 5_000 });
294
+ await assert.rejects(client.command("tab-1", { type: "get_state" }), /fenced|closed|not attached/i, "newer attachment must fence prior controller writes");
295
+ assert.equal(replacement.snapshot.tabs.find((tab) => tab.id === "tab-1").id, "tab-1");
296
+ assert.equal(replacement.snapshot.gap, true, "a cursor-less attach with managed history must truthfully report a gap");
297
+ assert.ok(replacement.snapshot.replay.length > 0, "a cursor-less attach must replay retained history");
298
+
299
+ await replacement.command("raw-tab", { type: "flood" }, { requestId: "flood-replay-ring" });
300
+ await delay(500);
301
+ replayClient = await discoverStartAttachRpcSupervisor({
302
+ agentDir,
303
+ port,
304
+ controllerId: "replay-controller",
305
+ cursor: { epoch: state.epoch, seq: "0" },
306
+ startupTimeoutMs: 5_000,
307
+ });
308
+ assert.equal(replayClient.snapshot.gap, true, "evicted byte-bounded replay history must report a gap");
309
+ assert.ok(replayClient.snapshot.replay.length > 0, "byte-bounded replay must still attach with a retained suffix");
310
+ const replayBytes = Buffer.byteLength(JSON.stringify(replayClient.snapshot.replay));
311
+ assert.ok(replayBytes <= RPC_SUPERVISOR_EVENT_RING_MAX_BYTES + 1024, "replay payload must remain well below the transport frame limit");
312
+ const replaySequences = replayClient.snapshot.replay.map((event) => BigInt(event.seq));
313
+ assert.deepEqual(replaySequences, [...replaySequences].sort((left, right) => left < right ? -1 : left > right ? 1 : 0), "replay events must be sequence ordered");
314
+
315
+ const pending = Array.from({ length: RPC_SUPERVISOR_REQUEST_DEDUPE_LIMIT }, (_, index) => (
316
+ replayClient.command("raw-tab", { type: "hold" }, { requestId: `hold-${index}`, timeoutMs: 86_400_000 }).catch(() => {})
317
+ ));
318
+ await Promise.race([
319
+ assert.rejects(
320
+ replayClient.command("raw-tab", { type: "hold" }, { requestId: "hold-over-capacity", timeoutMs: 86_400_000 }),
321
+ (error) => error?.code === "RPC_SUPERVISOR_DEDUPE_CAPACITY",
322
+ "unresolved dedupe entries must never be evicted to admit new work",
323
+ ),
324
+ delay(5_000).then(() => { throw new Error("dedupe capacity response timed out"); }),
325
+ ]);
326
+ await Promise.all(pending);
327
+ await replayClient.closeTab("raw-tab");
328
+
329
+ await replayClient.closeTab("tab-1");
330
+ await replayClient.shutdown();
331
+ await delay(200);
332
+ assert.equal(await readSupervisorState(paths), null, "a matching supervisor shutdown must remove private state");
333
+
334
+ // A host that loses its state race must leave the new incarnation untouched.
335
+ const safeAgentDir = path.join(work, "instance-safe-agent");
336
+ const safePort = port + 1;
337
+ const safePaths = await supervisorPaths({ agentDir: safeAgentDir, port: safePort });
338
+ const safeClient = await discoverStartAttachRpcSupervisor({ agentDir: safeAgentDir, port: safePort, startupTimeoutMs: 10_000 });
339
+ await writeSupervisorState(safePaths, { token: "replacement-token", instanceId: "replacement-instance", pid: process.pid, tabs: [] });
340
+ await safeClient.shutdown();
341
+ await delay(150);
342
+ assert.equal((await readSupervisorState(safePaths)).instanceId, "replacement-instance", "old supervisor shutdown must not remove newer state");
343
+ safeClient.close();
344
+ await removeSupervisorState(safePaths, { removeSocket: true, instanceId: "replacement-instance" });
345
+
346
+ // A stale socket path cannot authorize replacement while the recorded PID is alive.
347
+ const liveAgentDir = path.join(work, "live-state-agent");
348
+ const livePort = port + 2;
349
+ const livePaths = await supervisorPaths({ agentDir: liveAgentDir, port: livePort });
350
+ await writeSupervisorState(livePaths, { token: "live-token", instanceId: "live-instance", pid: process.pid, tabs: [] });
351
+ await assert.rejects(
352
+ discoverStartAttachRpcSupervisor({ agentDir: liveAgentDir, port: livePort, startupTimeoutMs: 300 }),
353
+ (error) => error?.code === "RPC_SUPERVISOR_LIVE_STATE",
354
+ "startup must refuse a live recorded supervisor instead of replacing it after a connection failure",
355
+ );
356
+ assert.equal((await readSupervisorState(livePaths)).instanceId, "live-instance");
357
+ await removeSupervisorState(livePaths, { removeSocket: true, instanceId: "live-instance" });
358
+
359
+ // A live state plus a reset pipe is ambiguous and must fail closed rather
360
+ // than launching a duplicate detached owner.
361
+ const resetAgentDir = path.join(work, "reset-state-agent");
362
+ const resetPort = port + 3;
363
+ const resetPaths = await supervisorPaths({ agentDir: resetAgentDir, port: resetPort });
364
+ await writeSupervisorState(resetPaths, { token: "reset-token", instanceId: "reset-instance", pid: process.pid, tabs: [] });
365
+ const resetServer = createServer((socket) => socket.destroy());
366
+ await listen(resetServer, resetPaths.socketPath);
367
+ await assert.rejects(
368
+ discoverStartAttachRpcSupervisor({ agentDir: resetAgentDir, port: resetPort, startupTimeoutMs: 300 }),
369
+ /closed|reset|pipe/i,
370
+ "a transient reset must not trigger stale-state replacement",
371
+ );
372
+ assert.equal((await readSupervisorState(resetPaths)).instanceId, "reset-instance");
373
+ await closeServer(resetServer);
374
+ await removeSupervisorState(resetPaths, { removeSocket: true, instanceId: "reset-instance" });
375
+
376
+ // Untagged pre-attach errors and silent peers must fail a client deterministically.
377
+ const attachErrorPath = path.join(work, "attach-error.sock");
378
+ const attachErrorServer = createServer((socket) => socket.once("data", () => socket.write(`${JSON.stringify({ type: "result", ok: false, code: "RPC_SUPERVISOR_AUTH", error: "denied" })}\n`)));
379
+ await listen(attachErrorServer, attachErrorPath);
380
+ const attachErrorClient = new RpcSupervisorClient({
381
+ socket: createConnection(attachErrorPath),
382
+ state: { scopeId: "a".repeat(64), token: "token" },
383
+ attachTimeoutMs: 500,
384
+ });
385
+ await assert.rejects(attachErrorClient.attach(), (error) => error?.code === "RPC_SUPERVISOR_AUTH");
386
+ attachErrorClient.close();
387
+ await delay(20);
388
+ await closeServer(attachErrorServer);
389
+
390
+ const attachTimeoutPath = path.join(work, "attach-timeout.sock");
391
+ const attachTimeoutServer = createServer(() => {});
392
+ await listen(attachTimeoutServer, attachTimeoutPath);
393
+ const attachTimeoutClient = new RpcSupervisorClient({
394
+ socket: createConnection(attachTimeoutPath),
395
+ state: { scopeId: "b".repeat(64), token: "token" },
396
+ attachTimeoutMs: 30,
397
+ });
398
+ await assert.rejects(attachTimeoutClient.attach(), (error) => error?.code === "RPC_SUPERVISOR_ATTACH_TIMEOUT");
399
+ attachTimeoutClient.close();
400
+ await delay(20);
401
+ await closeServer(attachTimeoutServer);
402
+ console.log("rpc-supervisor-host.test.mjs passed");
403
+ } finally {
404
+ replayClient?.close();
405
+ replacement?.close();
406
+ client?.close();
407
+ await rm(work, { recursive: true, force: true });
408
+ }
@@ -0,0 +1,93 @@
1
+ import assert from "node:assert/strict";
2
+ import {
3
+ PI_RPC_JSONL_LINE_MAX_BYTES,
4
+ RPC_SUPERVISOR_CHILD_ARG_LIMIT,
5
+ RPC_SUPERVISOR_MAX_FRAME_BYTES,
6
+ RPC_SUPERVISOR_PROTOCOL,
7
+ RpcSupervisorProtocolError,
8
+ constantTimeTokenEqual,
9
+ encodeFrame,
10
+ frameReader,
11
+ protocolCompatible,
12
+ protocolCurrent,
13
+ sanitizeSupervisorData,
14
+ validateClientFrame,
15
+ } from "../lib/rpc-supervisor-protocol.mjs";
16
+
17
+ const attach = validateClientFrame({
18
+ type: "attach", version: RPC_SUPERVISOR_PROTOCOL, scopeId: "a".repeat(64), token: "private-token", controllerId: "controller-1",
19
+ });
20
+ assert.equal(attach.token, "private-token", "attach validation must retain the private token for authentication");
21
+ assert.equal(constantTimeTokenEqual("same", "same"), true);
22
+ assert.equal(constantTimeTokenEqual("same", "different"), false);
23
+ assert.equal(protocolCompatible({ major: RPC_SUPERVISOR_PROTOCOL.major, minor: 0 }), true, "older minor versions remain attach-compatible for actionable recovery");
24
+ assert.equal(protocolCurrent({ major: RPC_SUPERVISOR_PROTOCOL.major, minor: 0 }), false, "older detached supervisors must be detectable after a server-only restart");
25
+ assert.equal(protocolCurrent(RPC_SUPERVISOR_PROTOCOL), true);
26
+
27
+ const resumedChildArgs = Array.from({ length: 257 }, (_, index) => index % 2 === 0 ? "--extension" : `/tmp/resource-${index}`);
28
+ const resumedChild = validateClientFrame({
29
+ type: "create",
30
+ requestId: "create-resumed-tab",
31
+ tabId: "resumed-tab",
32
+ metadata: {},
33
+ child: { command: "pi", args: resumedChildArgs, cwd: "/tmp" },
34
+ });
35
+ assert.equal(resumedChild.child.args.length, 257, "resource-heavy resumed tabs must fit the supervisor launch contract");
36
+ assert.throws(
37
+ () => validateClientFrame({
38
+ type: "create",
39
+ requestId: "create-too-many-args",
40
+ tabId: "oversized-tab",
41
+ metadata: {},
42
+ child: { command: "pi", args: Array.from({ length: RPC_SUPERVISOR_CHILD_ARG_LIMIT + 1 }, () => "x"), cwd: "/tmp" },
43
+ }),
44
+ /at most 1024 entries/,
45
+ );
46
+
47
+ const rawPiCommand = {
48
+ type: "prompt",
49
+ message: "x".repeat(64 * 1024 + 1),
50
+ apiToken: "must-round-trip-over-local-pi-transport",
51
+ tokens: { input: 123, output: 456 },
52
+ entries: Array.from({ length: 257 }, (_, index) => ({ index, token: `token-${index}` })),
53
+ };
54
+ const command = validateClientFrame({ type: "command", requestId: "request-1", tabId: "tab-1", command: rawPiCommand, timeoutMs: 500 });
55
+ assert.strictEqual(command.command, rawPiCommand, "live command validation must retain the original Pi RPC object");
56
+ assert.equal(command.command.apiToken, "must-round-trip-over-local-pi-transport");
57
+ assert.equal(command.command.message.length, 64 * 1024 + 1);
58
+ assert.equal(command.command.entries.length, 257);
59
+ assert.deepEqual(command.command.tokens, { input: 123, output: 456 });
60
+ const write = validateClientFrame({ type: "write", requestId: "write-1", tabId: "tab-1", command: { type: "extension_ui_response", id: "ui-1", tokens: { keep: true } } });
61
+ assert.equal(write.command.tokens.keep, true, "raw write validation must not strip token-named data");
62
+ assert.throws(
63
+ () => validateClientFrame({ type: "write", requestId: "write-timeout", tabId: "tab-1", command: { type: "extension_ui_response" }, timeoutMs: 1 }),
64
+ RpcSupervisorProtocolError,
65
+ "fire-and-forget writes must not accept response timeouts",
66
+ );
67
+ assert.throws(
68
+ () => validateClientFrame({ type: "command", requestId: "oversized-pi-line", tabId: "tab-1", command: { type: "prompt", message: "x".repeat(PI_RPC_JSONL_LINE_MAX_BYTES) } }),
69
+ RpcSupervisorProtocolError,
70
+ "a Pi command at the bounded JSONL limit plus its envelope must be rejected rather than truncated",
71
+ );
72
+ for (const timeoutMs of [7_200_000, 86_400_000]) {
73
+ const accepted = validateClientFrame({ type: "command", requestId: `timeout-${timeoutMs}`, tabId: "tab-1", command: { type: "prompt", message: "bounded" }, timeoutMs });
74
+ assert.equal(accepted.timeoutMs, timeoutMs, `${timeoutMs}ms command timeout should be accepted`);
75
+ }
76
+ assert.throws(
77
+ () => validateClientFrame({ type: "command", requestId: "timeout-too-large", tabId: "tab-1", command: { type: "prompt", message: "unbounded" }, timeoutMs: 86_400_001 }),
78
+ RpcSupervisorProtocolError,
79
+ "command timeouts above 24 hours must be rejected",
80
+ );
81
+ assert.deepEqual(sanitizeSupervisorData({ password: "no", nested: { Authorization: "no", safe: true } }), { nested: { safe: true } });
82
+ assert.throws(() => validateClientFrame({ type: "command", requestId: "x", tabId: "t", command: { type: "prompt" }, unexpected: true }), RpcSupervisorProtocolError);
83
+ assert.throws(() => validateClientFrame({ type: "create", requestId: "x", tabId: "t", metadata: {}, child: { command: "pi", args: [], cwd: "/tmp", env: {} } }), RpcSupervisorProtocolError);
84
+ assert.throws(() => encodeFrame({ value: "x".repeat(RPC_SUPERVISOR_MAX_FRAME_BYTES) }), RpcSupervisorProtocolError);
85
+
86
+ const frames = [];
87
+ const errors = [];
88
+ const consume = frameReader((frame) => frames.push(frame), (error) => errors.push(error));
89
+ consume('{"type":"event"}\n{"type":"result"');
90
+ consume(',"requestId":"r"}\n');
91
+ assert.deepEqual(frames, [{ type: "event" }, { type: "result", requestId: "r" }]);
92
+ assert.equal(errors.length, 0);
93
+ console.log("rpc-supervisor-protocol.test.mjs passed");
@@ -0,0 +1,62 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import {
6
+ acquireStartupLock,
7
+ appendSupervisorJournal,
8
+ readSupervisorState,
9
+ removeSupervisorState,
10
+ supervisorPaths,
11
+ writeSupervisorState,
12
+ } from "../lib/rpc-supervisor-state.mjs";
13
+
14
+ const root = await mkdtemp(path.join(tmpdir(), "pi-webui-rpc-supervisor-state-"));
15
+ try {
16
+ const paths = await supervisorPaths({ agentDir: path.join(root, "agent"), port: 41234 });
17
+ assert.match(paths.scopeId, /^[a-f0-9]{64}$/);
18
+ if (process.platform === "win32") assert.match(paths.socketPath, /^\\\\\.\\pipe\\/);
19
+ else assert.match(paths.socketPath, /\.sock$/);
20
+
21
+ await writeSupervisorState(paths, {
22
+ token: "private-token",
23
+ instanceId: "instance-1",
24
+ pid: process.pid,
25
+ tabs: [{ id: "tab-1", metadata: { title: "safe", apiToken: "must-not-persist" } }],
26
+ });
27
+ const state = await readSupervisorState(paths);
28
+ assert.equal(state.token, "private-token");
29
+ assert.equal(state.tabs[0].metadata.apiToken, undefined);
30
+ const stateText = await readFile(paths.stateFile, "utf8");
31
+ assert.doesNotMatch(stateText, /must-not-persist/);
32
+
33
+ await appendSupervisorJournal(paths, { metadata: { title: "safe", authorization: "must-not-persist" } });
34
+ const journal = await readFile(paths.journalFile, "utf8");
35
+ assert.doesNotMatch(journal, /must-not-persist/);
36
+
37
+ const release = await acquireStartupLock(paths);
38
+ assert.equal(typeof release, "function");
39
+ assert.equal(await acquireStartupLock(paths), null, "exclusive startup lock must prevent duplicate launchers");
40
+ await release();
41
+ const secondRelease = await acquireStartupLock(paths);
42
+ assert.equal(typeof secondRelease, "function");
43
+ await secondRelease();
44
+
45
+ await writeSupervisorState(paths, {
46
+ token: "replacement-token",
47
+ instanceId: "instance-2",
48
+ pid: process.pid,
49
+ tabs: [],
50
+ });
51
+ assert.equal(
52
+ await removeSupervisorState(paths, { removeSocket: true, instanceId: "instance-1" }),
53
+ false,
54
+ "an old supervisor must not remove a replacement incarnation's runtime files",
55
+ );
56
+ assert.equal((await readSupervisorState(paths)).instanceId, "instance-2");
57
+ assert.equal(await removeSupervisorState(paths, { instanceId: "instance-2" }), true);
58
+ assert.equal(await readSupervisorState(paths), null);
59
+ console.log("rpc-supervisor-state.test.mjs passed");
60
+ } finally {
61
+ await rm(root, { recursive: true, force: true });
62
+ }
package/tests/run-all.mjs CHANGED
@@ -8,7 +8,10 @@ const files = (await readdir(testsDir)).filter((name) => name.endsWith(".test.mj
8
8
 
9
9
  const failures = [];
10
10
  for (const file of files) {
11
- const result = spawnSync(process.execPath, [join(testsDir, file)], { stdio: "inherit" });
11
+ const result = spawnSync(process.execPath, [join(testsDir, file)], {
12
+ stdio: "inherit",
13
+ env: { ...process.env, PI_WEBUI_RPC_SUPERVISOR: "0" },
14
+ });
12
15
  if (result.status !== 0) failures.push(`${file} (exit ${result.status ?? "signal"})`);
13
16
  }
14
17
 
@@ -109,6 +109,21 @@ assert.doesNotMatch(
109
109
  assert.match(syncLiveTodoProgressWidgetFromText, /scheduleLiveWidgetRender\s*\(/, "fixed theory #0: live todo-progress widget rendering should remain scheduler-based");
110
110
  assert.match(scheduleLiveWidgetRender, /requestAnimationFrame\s*\(/, "fixed theory #0: live widget rebuilds should remain coalesced to animation frames");
111
111
  assert.match(scheduleLiveWidgetRender, /liveWidgetRenderFrame !== null/, "fixed theory #0: repeated tokens in one frame should not queue duplicate widget rebuilds");
112
+ assert.match(
113
+ stripTodoProgressLines,
114
+ /isOptionalFeatureDetected\("todoProgressWidget"\)/,
115
+ "todo-progress transport lines should remain hidden when only the optional widget renderer is disabled",
116
+ );
117
+ assert.doesNotMatch(
118
+ stripTodoProgressLines,
119
+ /isOptionalFeatureEnabled\("todoProgressWidget"\)/,
120
+ "todo-progress output filtering must not depend on the widget renderer toggle",
121
+ );
122
+ assert.match(
123
+ liveTodoProgressWidgetLinesFromText,
124
+ /isOptionalFeatureEnabled\("todoProgressWidget"\)/,
125
+ "disabling todo-progress should still suppress the optional widget renderer itself",
126
+ );
112
127
 
113
128
  futureInvariant("theory #1: message_update streaming hot path must not call immediate scroll/layout work", () => {
114
129
  assert.doesNotMatch(handleMessageUpdate, /scrollChatToBottom\s*\(/, "handleMessageUpdate should schedule/coalesce follow-scroll instead of calling scrollChatToBottom() directly");
@@ -163,7 +178,7 @@ futureInvariant("theory #6: output-seen tab refresh should remain out of the mes
163
178
  futureInvariant("theory #6: event-end output-seen refresh should not synchronously rebuild all tabs", () => {
164
179
  assert.doesNotMatch(markTabOutputSeen, /renderTabs\(\)/, "output-seen serial changes should schedule/coalesce tab chrome updates");
165
180
  });
166
- assert.match(findCaseBody(handleEvent, "agent_end"), /markTabOutputSeen\(\)/, "theory #6: output-seen marking should still happen when a run ends");
181
+ assert.match(findCaseBody(handleEvent, "agent_settled"), /markTabOutputSeen\(\)/, "theory #6: output-seen marking should happen only when a logical run settles");
167
182
  assert.match(findCaseBody(handleEvent, "compaction_end"), /markTabOutputSeen\(\)/, "theory #6: output-seen marking should still happen when compaction ends");
168
183
 
169
184
  futureInvariant("theory #7: skill tracking must not inspect every message_update event", () => {
@@ -177,7 +192,8 @@ assert.match(trackAutoRetryStateFromEvent, /event\.type === "auto_retry_start"/,
177
192
  // Theory #8 is a correctness guard: the current design still uses a steer prompt,
178
193
  // but it must never run while the agent is active.
179
194
  assert.match(requestGitFooterWebuiPayload, /currentState\?\.isStreaming \|\| currentState\?\.isCompacting/, "theory #8: git-footer steer refresh must remain guarded during active streaming/compaction");
180
- assert.match(findCaseBody(handleEvent, "agent_end"), /currentState\) currentState = \{ \.\.\.currentState, isStreaming: false \};[\s\S]*?requestGitFooterWebuiPayload\(tabContext, \{ force: true \}\)/, "theory #8: forced git-footer refresh should only happen after agent_end clears streaming state");
195
+ assert.match(findCaseBody(handleEvent, "agent_settled"), /currentState\) currentState = \{ \.\.\.currentState, isStreaming: false \};[\s\S]*?requestGitFooterWebuiPayload\(tabContext, \{ force: true \}\)/, "theory #8: forced git-footer refresh should only happen after agent settlement clears streaming state");
196
+ assert.doesNotMatch(findCaseBody(handleEvent, "agent_end"), /isStreaming: false|requestGitFooterWebuiPayload/, "theory #8: low-level agent_end must not expose an idle window before retry or continuation");
181
197
 
182
198
  if (futureFailures.length) {
183
199
  assert.fail(`streaming/UI coupling invariants still failing (${futureFailures.length}):\n\n${futureFailures.map((failure, index) => `${index + 1}. ${failure}`).join("\n\n")}`);