@firstpick/pi-package-webui 0.7.6 → 0.7.7
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.
- package/README.md +37 -4
- package/bin/pi-webui-rpc-supervisor.mjs +518 -0
- package/bin/pi-webui.mjs +1003 -82
- package/lib/WEBUI_TUI_NATIVE_PARITY.json +13 -0
- package/lib/rpc-supervisor-client.mjs +301 -0
- package/lib/rpc-supervisor-protocol.mjs +236 -0
- package/lib/rpc-supervisor-state.mjs +165 -0
- package/lib/trust-boundaries.mjs +1 -0
- package/package.json +2 -2
- package/public/app.js +1237 -82
- package/public/index.html +334 -25
- package/public/service-worker.js +6 -1
- package/public/styles.css +366 -52
- package/public/subagent-gate-visibility.mjs +36 -0
- package/public/workflow-status-stack.mjs +69 -0
- package/tests/app-runner-process-tree-harness.test.mjs +37 -3
- package/tests/boot-failure-diagnostics.test.mjs +180 -0
- package/tests/durable-rpc-supervisor-harness.test.mjs +252 -0
- package/tests/fast-mode-client-static.test.mjs +2 -2
- package/tests/fixtures/compacting-pi.mjs +0 -0
- package/tests/fixtures/fake-pi.mjs +81 -2
- package/tests/git-panel-file-preview-static.test.mjs +221 -0
- package/tests/http-endpoints-harness.test.mjs +458 -33
- package/tests/mobile-static.test.mjs +74 -12
- package/tests/native-parity-harness.test.mjs +2 -1
- package/tests/native-parity.test.mjs +11 -0
- package/tests/numpad-decimal-input-static.test.mjs +128 -0
- package/tests/prompt-routing-input-clear-static.test.mjs +34 -0
- package/tests/prompt-routing-tab-status.test.mjs +103 -0
- package/tests/rpc-supervisor-host.test.mjs +275 -0
- package/tests/rpc-supervisor-protocol.test.mjs +67 -0
- package/tests/rpc-supervisor-state.test.mjs +62 -0
- package/tests/run-all.mjs +4 -1
- package/tests/streaming-ui-coupling.test.mjs +15 -0
- package/tests/subagent-gate-visibility.test.mjs +66 -0
- package/tests/subagent-launch-slots-static.test.mjs +1 -1
- package/tests/subagents-helper.test.mjs +136 -0
- package/tests/workflow-status-stack.test.mjs +87 -0
- package/webui-rpc-helper.mjs +160 -2
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { createConnection, createServer } from "node:net";
|
|
3
|
+
import { 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_EVENT_RING_MAX_BYTES,
|
|
10
|
+
RPC_SUPERVISOR_REQUEST_DEDUPE_LIMIT,
|
|
11
|
+
} from "../lib/rpc-supervisor-protocol.mjs";
|
|
12
|
+
import {
|
|
13
|
+
RpcSupervisorClient,
|
|
14
|
+
discoverStartAttachRpcSupervisor,
|
|
15
|
+
} from "../lib/rpc-supervisor-client.mjs";
|
|
16
|
+
import {
|
|
17
|
+
readSupervisorState,
|
|
18
|
+
removeSupervisorState,
|
|
19
|
+
supervisorPaths,
|
|
20
|
+
writeSupervisorState,
|
|
21
|
+
} from "../lib/rpc-supervisor-state.mjs";
|
|
22
|
+
|
|
23
|
+
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
24
|
+
const fakePi = path.join(root, "tests", "fixtures", "fake-pi.mjs");
|
|
25
|
+
const work = await mkdtemp(path.join(tmpdir(), "pi-webui-rpc-supervisor-host-"));
|
|
26
|
+
const agentDir = path.join(work, "agent");
|
|
27
|
+
const port = 35000 + Math.floor(Math.random() * 15000);
|
|
28
|
+
const logFile = path.join(work, "commands.jsonl");
|
|
29
|
+
const rawLogFile = path.join(work, "raw-pi.jsonl");
|
|
30
|
+
const rawPiScript = String.raw`
|
|
31
|
+
const { appendFileSync } = require("node:fs");
|
|
32
|
+
const { createInterface } = require("node:readline");
|
|
33
|
+
const log = process.env.RAW_PI_LOG;
|
|
34
|
+
const send = (value) => process.stdout.write(JSON.stringify(value) + "\n");
|
|
35
|
+
createInterface({ input: process.stdin }).on("line", (line) => {
|
|
36
|
+
const command = JSON.parse(line);
|
|
37
|
+
appendFileSync(log, line + "\n");
|
|
38
|
+
if (command.type === "hold") {
|
|
39
|
+
setTimeout(() => process.exit(0), 2500).unref();
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (command.type === "extension_ui_response") return;
|
|
43
|
+
if (command.type === "flood") {
|
|
44
|
+
send({ type: "response", id: command.id, data: { accepted: true } });
|
|
45
|
+
for (let index = 0; index < 80; index += 1) send({ type: "large_event", index, tokens: { keep: index }, body: "r".repeat(72 * 1024) });
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (command.type === "emit_one") {
|
|
49
|
+
send({ type: "response", id: command.id, data: { accepted: true } });
|
|
50
|
+
send({ type: "other_tab_live_event", tokens: { keep: true } });
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
send({ type: "response", id: command.id, data: command });
|
|
54
|
+
});
|
|
55
|
+
`;
|
|
56
|
+
|
|
57
|
+
async function listen(server, socketPath) {
|
|
58
|
+
const connections = new Set();
|
|
59
|
+
server.__testConnections = connections;
|
|
60
|
+
server.on("connection", (socket) => {
|
|
61
|
+
connections.add(socket);
|
|
62
|
+
socket.on("close", () => connections.delete(socket));
|
|
63
|
+
});
|
|
64
|
+
await new Promise((resolve, reject) => {
|
|
65
|
+
server.once("error", reject);
|
|
66
|
+
server.listen(socketPath, () => {
|
|
67
|
+
server.off("error", reject);
|
|
68
|
+
resolve();
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function closeServer(server) {
|
|
74
|
+
for (const socket of server.__testConnections || []) socket.destroy();
|
|
75
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function rawLines() {
|
|
79
|
+
const text = await readFile(rawLogFile, "utf8").catch(() => "");
|
|
80
|
+
return text.split("\n").filter(Boolean).map((line) => JSON.parse(line));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function waitFor(label, predicate, timeoutMs = 5_000) {
|
|
84
|
+
const deadline = Date.now() + timeoutMs;
|
|
85
|
+
while (Date.now() < deadline) {
|
|
86
|
+
const value = await predicate();
|
|
87
|
+
if (value) return value;
|
|
88
|
+
await delay(20);
|
|
89
|
+
}
|
|
90
|
+
throw new Error(`${label} did not happen within ${timeoutMs}ms`);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
let client;
|
|
94
|
+
let replacement;
|
|
95
|
+
let replayClient;
|
|
96
|
+
try {
|
|
97
|
+
client = await discoverStartAttachRpcSupervisor({
|
|
98
|
+
agentDir,
|
|
99
|
+
port,
|
|
100
|
+
environment: { ...process.env, FAKE_PI_LOG_FILE: logFile, RAW_PI_LOG: rawLogFile },
|
|
101
|
+
startupTimeoutMs: 10_000,
|
|
102
|
+
});
|
|
103
|
+
const created = await client.createTab({
|
|
104
|
+
tabId: "tab-1",
|
|
105
|
+
metadata: { title: "One", index: 0, cwd: work, sessionFile: path.join(work, "one.jsonl"), apiToken: "never-persist" },
|
|
106
|
+
child: { command: process.execPath, args: [fakePi], cwd: work },
|
|
107
|
+
});
|
|
108
|
+
assert.equal(created.id, "tab-1");
|
|
109
|
+
assert.ok(created.pid > 0);
|
|
110
|
+
await client.createTab({
|
|
111
|
+
tabId: "raw-tab",
|
|
112
|
+
metadata: { title: "Raw", index: 1, cwd: work, sessionFile: path.join(work, "raw.jsonl") },
|
|
113
|
+
child: { command: process.execPath, args: ["-e", rawPiScript], cwd: work },
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
const response = await Promise.all([
|
|
117
|
+
client.command("tab-1", { type: "prompt", message: "dedupe me" }, { requestId: "prompt-once" }),
|
|
118
|
+
client.command("tab-1", { type: "prompt", message: "dedupe me" }, { requestId: "prompt-once" }),
|
|
119
|
+
]);
|
|
120
|
+
assert.equal(response[0].data.output, "fake prompt accepted");
|
|
121
|
+
assert.deepEqual(response[0], response[1]);
|
|
122
|
+
await delay(60);
|
|
123
|
+
const logged = (await readFile(logFile, "utf8")).split("\n").filter(Boolean).map(JSON.parse);
|
|
124
|
+
assert.equal(logged.filter((entry) => entry.direction === "command" && entry.message === "dedupe me").length, 1, "duplicate request IDs must not write to Pi twice");
|
|
125
|
+
|
|
126
|
+
const rawCommand = {
|
|
127
|
+
type: "raw_round_trip",
|
|
128
|
+
message: "x".repeat(64 * 1024 + 1),
|
|
129
|
+
tokens: { input: 123, output: 456 },
|
|
130
|
+
entries: Array.from({ length: 257 }, (_, index) => ({ index, token: `token-${index}` })),
|
|
131
|
+
};
|
|
132
|
+
const rawResponse = await client.command("raw-tab", rawCommand, { requestId: "raw-round-trip" });
|
|
133
|
+
assert.equal(rawResponse.data.message.length, rawCommand.message.length, "live Pi responses must preserve long strings");
|
|
134
|
+
assert.equal(rawResponse.data.entries.length, 257, "live Pi responses must preserve arrays beyond metadata limits");
|
|
135
|
+
assert.deepEqual(rawResponse.data.tokens, rawCommand.tokens, "live Pi responses must preserve token-named fields");
|
|
136
|
+
|
|
137
|
+
const rawWrite = { type: "extension_ui_response", id: "ui-no-response", tokens: { private: "keep" }, entries: Array.from({ length: 257 }, (_, index) => index) };
|
|
138
|
+
await Promise.race([
|
|
139
|
+
client.write("raw-tab", rawWrite, { requestId: "raw-write-once" }),
|
|
140
|
+
delay(1_000).then(() => { throw new Error("raw write waited for a Pi response"); }),
|
|
141
|
+
]);
|
|
142
|
+
const written = await waitFor("raw write log", async () => (await rawLines()).find((line) => line.type === "extension_ui_response"));
|
|
143
|
+
assert.deepEqual(written, rawWrite, "fire-and-forget writes must reach Pi unchanged and without an injected request ID");
|
|
144
|
+
|
|
145
|
+
const deliveredStartupEvents = [];
|
|
146
|
+
const unsubscribe = client.onEvent((event) => deliveredStartupEvents.push(event));
|
|
147
|
+
await client.command("raw-tab", { type: "emit_one" }, { requestId: "startup-buffer-event" });
|
|
148
|
+
await delay(50);
|
|
149
|
+
assert.equal(deliveredStartupEvents.length, 0, "events arriving during startup must wait for explicit hydration drain");
|
|
150
|
+
const drainedStartupEvents = client.drainStartupEvents();
|
|
151
|
+
assert.ok(drainedStartupEvents.some((event) => event.payload?.type === "other_tab_live_event"), "startup drain must retain other-tab live events");
|
|
152
|
+
assert.deepEqual(deliveredStartupEvents.map((event) => event.seq), drainedStartupEvents.map((event) => event.seq), "startup drain must deliver buffered events in order");
|
|
153
|
+
unsubscribe();
|
|
154
|
+
|
|
155
|
+
const paths = await supervisorPaths({ agentDir, port });
|
|
156
|
+
const state = await readSupervisorState(paths);
|
|
157
|
+
assert.equal(state.tabs.length, 2);
|
|
158
|
+
assert.equal(state.tabs.find((tab) => tab.id === "tab-1").metadata.apiToken, undefined, "private metadata fields must not reach the state snapshot");
|
|
159
|
+
|
|
160
|
+
replacement = await discoverStartAttachRpcSupervisor({ agentDir, port, controllerId: "replacement-controller", startupTimeoutMs: 5_000 });
|
|
161
|
+
await assert.rejects(client.command("tab-1", { type: "get_state" }), /fenced|closed|not attached/i, "newer attachment must fence prior controller writes");
|
|
162
|
+
assert.equal(replacement.snapshot.tabs.find((tab) => tab.id === "tab-1").id, "tab-1");
|
|
163
|
+
assert.equal(replacement.snapshot.gap, true, "a cursor-less attach with managed history must truthfully report a gap");
|
|
164
|
+
assert.ok(replacement.snapshot.replay.length > 0, "a cursor-less attach must replay retained history");
|
|
165
|
+
|
|
166
|
+
await replacement.command("raw-tab", { type: "flood" }, { requestId: "flood-replay-ring" });
|
|
167
|
+
await delay(500);
|
|
168
|
+
replayClient = await discoverStartAttachRpcSupervisor({
|
|
169
|
+
agentDir,
|
|
170
|
+
port,
|
|
171
|
+
controllerId: "replay-controller",
|
|
172
|
+
cursor: { epoch: state.epoch, seq: "0" },
|
|
173
|
+
startupTimeoutMs: 5_000,
|
|
174
|
+
});
|
|
175
|
+
assert.equal(replayClient.snapshot.gap, true, "evicted byte-bounded replay history must report a gap");
|
|
176
|
+
assert.ok(replayClient.snapshot.replay.length > 0, "byte-bounded replay must still attach with a retained suffix");
|
|
177
|
+
const replayBytes = Buffer.byteLength(JSON.stringify(replayClient.snapshot.replay));
|
|
178
|
+
assert.ok(replayBytes <= RPC_SUPERVISOR_EVENT_RING_MAX_BYTES + 1024, "replay payload must remain well below the transport frame limit");
|
|
179
|
+
const replaySequences = replayClient.snapshot.replay.map((event) => BigInt(event.seq));
|
|
180
|
+
assert.deepEqual(replaySequences, [...replaySequences].sort((left, right) => left < right ? -1 : left > right ? 1 : 0), "replay events must be sequence ordered");
|
|
181
|
+
|
|
182
|
+
const pending = Array.from({ length: RPC_SUPERVISOR_REQUEST_DEDUPE_LIMIT }, (_, index) => (
|
|
183
|
+
replayClient.command("raw-tab", { type: "hold" }, { requestId: `hold-${index}`, timeoutMs: 86_400_000 }).catch(() => {})
|
|
184
|
+
));
|
|
185
|
+
await Promise.race([
|
|
186
|
+
assert.rejects(
|
|
187
|
+
replayClient.command("raw-tab", { type: "hold" }, { requestId: "hold-over-capacity", timeoutMs: 86_400_000 }),
|
|
188
|
+
(error) => error?.code === "RPC_SUPERVISOR_DEDUPE_CAPACITY",
|
|
189
|
+
"unresolved dedupe entries must never be evicted to admit new work",
|
|
190
|
+
),
|
|
191
|
+
delay(5_000).then(() => { throw new Error("dedupe capacity response timed out"); }),
|
|
192
|
+
]);
|
|
193
|
+
await Promise.all(pending);
|
|
194
|
+
await replayClient.closeTab("raw-tab");
|
|
195
|
+
|
|
196
|
+
await replayClient.closeTab("tab-1");
|
|
197
|
+
await replayClient.shutdown();
|
|
198
|
+
await delay(200);
|
|
199
|
+
assert.equal(await readSupervisorState(paths), null, "a matching supervisor shutdown must remove private state");
|
|
200
|
+
|
|
201
|
+
// A host that loses its state race must leave the new incarnation untouched.
|
|
202
|
+
const safeAgentDir = path.join(work, "instance-safe-agent");
|
|
203
|
+
const safePort = port + 1;
|
|
204
|
+
const safePaths = await supervisorPaths({ agentDir: safeAgentDir, port: safePort });
|
|
205
|
+
const safeClient = await discoverStartAttachRpcSupervisor({ agentDir: safeAgentDir, port: safePort, startupTimeoutMs: 10_000 });
|
|
206
|
+
await writeSupervisorState(safePaths, { token: "replacement-token", instanceId: "replacement-instance", pid: process.pid, tabs: [] });
|
|
207
|
+
await safeClient.shutdown();
|
|
208
|
+
await delay(150);
|
|
209
|
+
assert.equal((await readSupervisorState(safePaths)).instanceId, "replacement-instance", "old supervisor shutdown must not remove newer state");
|
|
210
|
+
safeClient.close();
|
|
211
|
+
await removeSupervisorState(safePaths, { removeSocket: true, instanceId: "replacement-instance" });
|
|
212
|
+
|
|
213
|
+
// A stale socket path cannot authorize replacement while the recorded PID is alive.
|
|
214
|
+
const liveAgentDir = path.join(work, "live-state-agent");
|
|
215
|
+
const livePort = port + 2;
|
|
216
|
+
const livePaths = await supervisorPaths({ agentDir: liveAgentDir, port: livePort });
|
|
217
|
+
await writeSupervisorState(livePaths, { token: "live-token", instanceId: "live-instance", pid: process.pid, tabs: [] });
|
|
218
|
+
await assert.rejects(
|
|
219
|
+
discoverStartAttachRpcSupervisor({ agentDir: liveAgentDir, port: livePort, startupTimeoutMs: 300 }),
|
|
220
|
+
(error) => error?.code === "RPC_SUPERVISOR_LIVE_STATE",
|
|
221
|
+
"startup must refuse a live recorded supervisor instead of replacing it after a connection failure",
|
|
222
|
+
);
|
|
223
|
+
assert.equal((await readSupervisorState(livePaths)).instanceId, "live-instance");
|
|
224
|
+
await removeSupervisorState(livePaths, { removeSocket: true, instanceId: "live-instance" });
|
|
225
|
+
|
|
226
|
+
// A live state plus a reset pipe is ambiguous and must fail closed rather
|
|
227
|
+
// than launching a duplicate detached owner.
|
|
228
|
+
const resetAgentDir = path.join(work, "reset-state-agent");
|
|
229
|
+
const resetPort = port + 3;
|
|
230
|
+
const resetPaths = await supervisorPaths({ agentDir: resetAgentDir, port: resetPort });
|
|
231
|
+
await writeSupervisorState(resetPaths, { token: "reset-token", instanceId: "reset-instance", pid: process.pid, tabs: [] });
|
|
232
|
+
const resetServer = createServer((socket) => socket.destroy());
|
|
233
|
+
await listen(resetServer, resetPaths.socketPath);
|
|
234
|
+
await assert.rejects(
|
|
235
|
+
discoverStartAttachRpcSupervisor({ agentDir: resetAgentDir, port: resetPort, startupTimeoutMs: 300 }),
|
|
236
|
+
/closed|reset|pipe/i,
|
|
237
|
+
"a transient reset must not trigger stale-state replacement",
|
|
238
|
+
);
|
|
239
|
+
assert.equal((await readSupervisorState(resetPaths)).instanceId, "reset-instance");
|
|
240
|
+
await closeServer(resetServer);
|
|
241
|
+
await removeSupervisorState(resetPaths, { removeSocket: true, instanceId: "reset-instance" });
|
|
242
|
+
|
|
243
|
+
// Untagged pre-attach errors and silent peers must fail a client deterministically.
|
|
244
|
+
const attachErrorPath = path.join(work, "attach-error.sock");
|
|
245
|
+
const attachErrorServer = createServer((socket) => socket.once("data", () => socket.write(`${JSON.stringify({ type: "result", ok: false, code: "RPC_SUPERVISOR_AUTH", error: "denied" })}\n`)));
|
|
246
|
+
await listen(attachErrorServer, attachErrorPath);
|
|
247
|
+
const attachErrorClient = new RpcSupervisorClient({
|
|
248
|
+
socket: createConnection(attachErrorPath),
|
|
249
|
+
state: { scopeId: "a".repeat(64), token: "token" },
|
|
250
|
+
attachTimeoutMs: 500,
|
|
251
|
+
});
|
|
252
|
+
await assert.rejects(attachErrorClient.attach(), (error) => error?.code === "RPC_SUPERVISOR_AUTH");
|
|
253
|
+
attachErrorClient.close();
|
|
254
|
+
await delay(20);
|
|
255
|
+
await closeServer(attachErrorServer);
|
|
256
|
+
|
|
257
|
+
const attachTimeoutPath = path.join(work, "attach-timeout.sock");
|
|
258
|
+
const attachTimeoutServer = createServer(() => {});
|
|
259
|
+
await listen(attachTimeoutServer, attachTimeoutPath);
|
|
260
|
+
const attachTimeoutClient = new RpcSupervisorClient({
|
|
261
|
+
socket: createConnection(attachTimeoutPath),
|
|
262
|
+
state: { scopeId: "b".repeat(64), token: "token" },
|
|
263
|
+
attachTimeoutMs: 30,
|
|
264
|
+
});
|
|
265
|
+
await assert.rejects(attachTimeoutClient.attach(), (error) => error?.code === "RPC_SUPERVISOR_ATTACH_TIMEOUT");
|
|
266
|
+
attachTimeoutClient.close();
|
|
267
|
+
await delay(20);
|
|
268
|
+
await closeServer(attachTimeoutServer);
|
|
269
|
+
console.log("rpc-supervisor-host.test.mjs passed");
|
|
270
|
+
} finally {
|
|
271
|
+
replayClient?.close();
|
|
272
|
+
replacement?.close();
|
|
273
|
+
client?.close();
|
|
274
|
+
await rm(work, { recursive: true, force: true });
|
|
275
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import {
|
|
3
|
+
PI_RPC_JSONL_LINE_MAX_BYTES,
|
|
4
|
+
RPC_SUPERVISOR_MAX_FRAME_BYTES,
|
|
5
|
+
RPC_SUPERVISOR_PROTOCOL,
|
|
6
|
+
RpcSupervisorProtocolError,
|
|
7
|
+
constantTimeTokenEqual,
|
|
8
|
+
encodeFrame,
|
|
9
|
+
frameReader,
|
|
10
|
+
sanitizeSupervisorData,
|
|
11
|
+
validateClientFrame,
|
|
12
|
+
} from "../lib/rpc-supervisor-protocol.mjs";
|
|
13
|
+
|
|
14
|
+
const attach = validateClientFrame({
|
|
15
|
+
type: "attach", version: RPC_SUPERVISOR_PROTOCOL, scopeId: "a".repeat(64), token: "private-token", controllerId: "controller-1",
|
|
16
|
+
});
|
|
17
|
+
assert.equal(attach.token, "private-token", "attach validation must retain the private token for authentication");
|
|
18
|
+
assert.equal(constantTimeTokenEqual("same", "same"), true);
|
|
19
|
+
assert.equal(constantTimeTokenEqual("same", "different"), false);
|
|
20
|
+
|
|
21
|
+
const rawPiCommand = {
|
|
22
|
+
type: "prompt",
|
|
23
|
+
message: "x".repeat(64 * 1024 + 1),
|
|
24
|
+
apiToken: "must-round-trip-over-local-pi-transport",
|
|
25
|
+
tokens: { input: 123, output: 456 },
|
|
26
|
+
entries: Array.from({ length: 257 }, (_, index) => ({ index, token: `token-${index}` })),
|
|
27
|
+
};
|
|
28
|
+
const command = validateClientFrame({ type: "command", requestId: "request-1", tabId: "tab-1", command: rawPiCommand, timeoutMs: 500 });
|
|
29
|
+
assert.strictEqual(command.command, rawPiCommand, "live command validation must retain the original Pi RPC object");
|
|
30
|
+
assert.equal(command.command.apiToken, "must-round-trip-over-local-pi-transport");
|
|
31
|
+
assert.equal(command.command.message.length, 64 * 1024 + 1);
|
|
32
|
+
assert.equal(command.command.entries.length, 257);
|
|
33
|
+
assert.deepEqual(command.command.tokens, { input: 123, output: 456 });
|
|
34
|
+
const write = validateClientFrame({ type: "write", requestId: "write-1", tabId: "tab-1", command: { type: "extension_ui_response", id: "ui-1", tokens: { keep: true } } });
|
|
35
|
+
assert.equal(write.command.tokens.keep, true, "raw write validation must not strip token-named data");
|
|
36
|
+
assert.throws(
|
|
37
|
+
() => validateClientFrame({ type: "write", requestId: "write-timeout", tabId: "tab-1", command: { type: "extension_ui_response" }, timeoutMs: 1 }),
|
|
38
|
+
RpcSupervisorProtocolError,
|
|
39
|
+
"fire-and-forget writes must not accept response timeouts",
|
|
40
|
+
);
|
|
41
|
+
assert.throws(
|
|
42
|
+
() => validateClientFrame({ type: "command", requestId: "oversized-pi-line", tabId: "tab-1", command: { type: "prompt", message: "x".repeat(PI_RPC_JSONL_LINE_MAX_BYTES) } }),
|
|
43
|
+
RpcSupervisorProtocolError,
|
|
44
|
+
"a Pi command at the bounded JSONL limit plus its envelope must be rejected rather than truncated",
|
|
45
|
+
);
|
|
46
|
+
for (const timeoutMs of [7_200_000, 86_400_000]) {
|
|
47
|
+
const accepted = validateClientFrame({ type: "command", requestId: `timeout-${timeoutMs}`, tabId: "tab-1", command: { type: "prompt", message: "bounded" }, timeoutMs });
|
|
48
|
+
assert.equal(accepted.timeoutMs, timeoutMs, `${timeoutMs}ms command timeout should be accepted`);
|
|
49
|
+
}
|
|
50
|
+
assert.throws(
|
|
51
|
+
() => validateClientFrame({ type: "command", requestId: "timeout-too-large", tabId: "tab-1", command: { type: "prompt", message: "unbounded" }, timeoutMs: 86_400_001 }),
|
|
52
|
+
RpcSupervisorProtocolError,
|
|
53
|
+
"command timeouts above 24 hours must be rejected",
|
|
54
|
+
);
|
|
55
|
+
assert.deepEqual(sanitizeSupervisorData({ password: "no", nested: { Authorization: "no", safe: true } }), { nested: { safe: true } });
|
|
56
|
+
assert.throws(() => validateClientFrame({ type: "command", requestId: "x", tabId: "t", command: { type: "prompt" }, unexpected: true }), RpcSupervisorProtocolError);
|
|
57
|
+
assert.throws(() => validateClientFrame({ type: "create", requestId: "x", tabId: "t", metadata: {}, child: { command: "pi", args: [], cwd: "/tmp", env: {} } }), RpcSupervisorProtocolError);
|
|
58
|
+
assert.throws(() => encodeFrame({ value: "x".repeat(RPC_SUPERVISOR_MAX_FRAME_BYTES) }), RpcSupervisorProtocolError);
|
|
59
|
+
|
|
60
|
+
const frames = [];
|
|
61
|
+
const errors = [];
|
|
62
|
+
const consume = frameReader((frame) => frames.push(frame), (error) => errors.push(error));
|
|
63
|
+
consume('{"type":"event"}\n{"type":"result"');
|
|
64
|
+
consume(',"requestId":"r"}\n');
|
|
65
|
+
assert.deepEqual(frames, [{ type: "event" }, { type: "result", requestId: "r" }]);
|
|
66
|
+
assert.equal(errors.length, 0);
|
|
67
|
+
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)], {
|
|
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");
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import {
|
|
6
|
+
SUBAGENT_GATE_RETENTION_MS,
|
|
7
|
+
pruneDismissedSubagentGateKeys,
|
|
8
|
+
subagentGateIsTerminal,
|
|
9
|
+
subagentGateKey,
|
|
10
|
+
visibleSubagentGates,
|
|
11
|
+
} from "../public/subagent-gate-visibility.mjs";
|
|
12
|
+
|
|
13
|
+
const now = 100_000;
|
|
14
|
+
const tab = {
|
|
15
|
+
tabId: "tab-a",
|
|
16
|
+
gates: [
|
|
17
|
+
{ id: "running", status: "running", endedAt: 1 },
|
|
18
|
+
{ id: "fresh", status: "failed", endedAt: now - SUBAGENT_GATE_RETENTION_MS + 1 },
|
|
19
|
+
{ id: "expired", status: "satisfied", endedAt: now - SUBAGENT_GATE_RETENTION_MS },
|
|
20
|
+
{ id: "updated", status: "cancelled", updatedAt: now - 1_000 },
|
|
21
|
+
{ id: "untimed", status: "failed" },
|
|
22
|
+
],
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
assert.equal(SUBAGENT_GATE_RETENTION_MS, 30_000, "terminal retry gates should remain readable for 30 seconds");
|
|
26
|
+
assert.equal(subagentGateKey("tab-a", "gate-a"), "tab-a:gate-a");
|
|
27
|
+
assert.equal(subagentGateKey("", "gate-a"), "");
|
|
28
|
+
assert.equal(subagentGateIsTerminal({ status: "running" }), false);
|
|
29
|
+
assert.equal(subagentGateIsTerminal({ status: "failed" }), true);
|
|
30
|
+
|
|
31
|
+
assert.deepEqual(
|
|
32
|
+
visibleSubagentGates(tab, new Set(), now).map((gate) => gate.id),
|
|
33
|
+
["running", "fresh", "updated", "untimed"],
|
|
34
|
+
"running gates should remain visible while terminal gates should expire after the retention window",
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
assert.deepEqual(
|
|
38
|
+
visibleSubagentGates(tab, new Set(["tab-a:fresh"]), now).map((gate) => gate.id),
|
|
39
|
+
["running", "updated", "untimed"],
|
|
40
|
+
"manual dismissal should hide a terminal gate immediately",
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
const dismissed = new Set(["tab-a:fresh", "tab-z:gone"]);
|
|
44
|
+
pruneDismissedSubagentGateKeys([tab], dismissed);
|
|
45
|
+
assert.deepEqual([...dismissed], ["tab-a:fresh"], "dismissal state should be pruned after its gate leaves the server snapshot");
|
|
46
|
+
|
|
47
|
+
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
48
|
+
const [app, css, serviceWorker, server, pkgRaw] = await Promise.all([
|
|
49
|
+
readFile(join(root, "public", "app.js"), "utf8"),
|
|
50
|
+
readFile(join(root, "public", "styles.css"), "utf8"),
|
|
51
|
+
readFile(join(root, "public", "service-worker.js"), "utf8"),
|
|
52
|
+
readFile(join(root, "bin", "pi-webui.mjs"), "utf8"),
|
|
53
|
+
readFile(join(root, "package.json"), "utf8"),
|
|
54
|
+
]);
|
|
55
|
+
const pkg = JSON.parse(pkgRaw);
|
|
56
|
+
|
|
57
|
+
assert.match(app, /from "\.\/subagent-gate-visibility\.mjs"/, "the browser should load the retry-gate visibility policy");
|
|
58
|
+
assert.match(app, /function subagentTabsWithRunningAgents\(\)[\s\S]*latestSubagents\?\.updatedAt[\s\S]*visibleSubagentGates\(tab, dismissedSubagentGateKeys, now\)/, "the side panel should use server time and filter expired or dismissed gates before deriving counts");
|
|
59
|
+
assert.match(app, /function renderSubagentGate\(tab, gate\)[\s\S]*subagentGateIsTerminal\(gate\)[\s\S]*Hide finished retry gate[\s\S]*dismissedSubagentGateKeys\.add\(key\)[\s\S]*renderSubagents\(\)[\s\S]*event\.detail === 0[\s\S]*focusTarget\?\.focus/, "terminal gate cards should expose an accessible hide button and preserve keyboard focus after rerendering");
|
|
60
|
+
assert.match(app, /pruneDismissedSubagentGateKeys\(latestSubagents\?\.tabs, dismissedSubagentGateKeys\)/, "polling should prune stale dismissal keys");
|
|
61
|
+
assert.match(css, /\.subagent-gate-actions[\s\S]*\.subagent-gate-close[\s\S]*min-width:\s*1\.75rem[\s\S]*\.subagent-gate-close:hover,[\s\S]*\.subagent-gate-close:focus-visible/, "the close control should remain compact and keyboard-visible");
|
|
62
|
+
assert.match(serviceWorker, /"\/subagent-gate-visibility\.mjs"/, "the PWA app shell should cache the visibility module");
|
|
63
|
+
assert.match(server, /"subagent-gate-visibility\.mjs"/, "the server static allowlist should serve the visibility module");
|
|
64
|
+
assert.match(pkg.scripts.check, /node --check public\/subagent-gate-visibility\.mjs/, "the package check should syntax-check the visibility module");
|
|
65
|
+
|
|
66
|
+
console.log("subagent gate visibility tests passed");
|
|
@@ -28,7 +28,7 @@ assert.match(css, /\.subagent-launch-slot-controls \{[\s\S]*grid-column: 1 \/ -1
|
|
|
28
28
|
assert.match(css, /\.sr-only \{[\s\S]*clip-path: inset\(50%\)[\s\S]*white-space: nowrap/, "screen-reader announcements should stay visually hidden without leaving the accessibility tree");
|
|
29
29
|
assert.match(css, /\.subagent-launch-slot-remove \{[^}]*color: var\(--ctp-red\)/, "destructive slot removal should have a textual control and warning color");
|
|
30
30
|
assert.match(server, /"subagent-launch-slot-state\.mjs"/, "the pure browser module should be on the static allowlist");
|
|
31
|
-
assert.match(serviceWorker, /pi-webui-pwa-
|
|
31
|
+
assert.match(serviceWorker, /pi-webui-pwa-v\d+[\s\S]*"\/subagent-launch-slot-state\.mjs"/, "the refreshed PWA cache should include the browser module");
|
|
32
32
|
assert.match(pkg, /node --check public\/subagent-launch-slot-state\.mjs/, "package checks should syntax-check the browser state module");
|
|
33
33
|
|
|
34
34
|
console.log("subagent-launch-slots-static.test.mjs passed");
|