@firstpick/pi-package-webui 0.9.1 → 0.9.2
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 +21 -5
- package/bin/pi-webui-launcher.mjs +23 -12
- package/bin/pi-webui.mjs +479 -60
- package/lib/agent-run-adapters.mjs +500 -0
- package/lib/agent-run-protocol.mjs +262 -0
- package/lib/agent-run-registry.mjs +339 -0
- package/lib/git-workflow-preferences.mjs +11 -4
- package/lib/trust-boundaries.mjs +2 -0
- package/lib/ui-layout-settings.mjs +172 -28
- package/lib/update/package-layout.mjs +50 -0
- package/lib/update/plan.mjs +11 -0
- package/package.json +1 -1
- package/public/app.js +1261 -314
- package/public/index.html +113 -68
- package/public/service-worker.js +1 -1
- package/public/styles.css +371 -93
- package/tests/agent-run-adapters.test.mjs +217 -0
- package/tests/agent-run-launcher.test.mjs +41 -0
- package/tests/agent-run-protocol.test.mjs +82 -0
- package/tests/agent-run-registry.test.mjs +102 -0
- package/tests/boot-failure-diagnostics.test.mjs +3 -3
- package/tests/browser/control-deck-side-panels.spec.mjs +354 -0
- package/tests/browser/controls-layout.spec.mjs +122 -0
- package/tests/browser/file-tree-git-ignored.spec.mjs +113 -0
- package/tests/browser/interaction-continuity.spec.mjs +127 -0
- package/tests/browser/mobile-foundation.spec.mjs +26 -0
- package/tests/browser/model-search-focus.spec.mjs +96 -0
- package/tests/browser/optimistic-prompt.spec.mjs +22 -0
- package/tests/browser/persistent-ui-layout.spec.mjs +224 -66
- package/tests/browser/subagent-observability.spec.mjs +87 -0
- package/tests/codex-fast-mode-static.test.mjs +2 -2
- package/tests/component-update-api-static.test.mjs +2 -1
- package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
- package/tests/control-deck-component-updates-static.test.mjs +2 -0
- package/tests/control-deck-side-panels-static.test.mjs +68 -0
- package/tests/controls-layout-static.test.mjs +22 -0
- package/tests/fast-mode-client-static.test.mjs +1 -1
- package/tests/feature-decision-output-popup-static.test.mjs +2 -2
- package/tests/file-tree-git-ignored-static.test.mjs +152 -0
- package/tests/file-tree-search-layout-static.test.mjs +2 -1
- package/tests/fixtures/fake-pi.mjs +43 -7
- package/tests/git-workflow-preferences.test.mjs +55 -6
- package/tests/http-endpoints-harness.test.mjs +173 -14
- package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
- package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
- package/tests/mobile-foundation-static.test.mjs +3 -3
- package/tests/mobile-phone-experience-static.test.mjs +1 -1
- package/tests/mobile-static.test.mjs +13 -3
- package/tests/open-issue-wizard-static.test.mjs +2 -2
- package/tests/persistent-ui-layout-static.test.mjs +13 -13
- package/tests/questionnaire-dialog.test.mjs +3 -3
- package/tests/remote-auth-settings-harness.test.mjs +1 -1
- package/tests/session-sampling-ui-static.test.mjs +3 -3
- package/tests/side-panel-context-menu-static.test.mjs +1 -1
- package/tests/side-panel-resize-static.test.mjs +26 -16
- package/tests/side-panel-section-height-removal-static.test.mjs +4 -4
- package/tests/side-panel-section-reorder-static.test.mjs +16 -70
- package/tests/subagent-gate-visibility.test.mjs +2 -1
- package/tests/subagent-launch-slots.test.mjs +1 -1
- package/tests/subagent-observability-static.test.mjs +32 -0
- package/tests/subagent-reliability-integration.test.mjs +161 -0
- package/tests/subagents-helper.test.mjs +344 -4
- package/tests/terminal-tabs-resize-static.test.mjs +35 -0
- package/tests/theme-customizer-static.test.mjs +1 -1
- package/tests/ui-layout-settings.test.mjs +104 -32
- package/tests/update-api-harness.test.mjs +24 -10
- package/tests/update-package-layout.test.mjs +38 -0
- package/tests/update-plan.test.mjs +11 -1
- package/tests/webui-settings-locking.test.mjs +33 -3
- package/webui-rpc-helper.mjs +417 -28
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { EventEmitter } from "node:events";
|
|
3
|
+
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { PassThrough } from "node:stream";
|
|
7
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
8
|
+
import {
|
|
9
|
+
resolveAttachSession,
|
|
10
|
+
runAgentCli,
|
|
11
|
+
startObservedPiProcess,
|
|
12
|
+
trackPiAgentSession,
|
|
13
|
+
trackPiAgentSessionEventBus,
|
|
14
|
+
} from "../lib/agent-run-adapters.mjs";
|
|
15
|
+
import { AgentRunRegistry } from "../lib/agent-run-registry.mjs";
|
|
16
|
+
|
|
17
|
+
class MemoryRegistry {
|
|
18
|
+
constructor() { this.records = []; this.events = []; this.locators = []; }
|
|
19
|
+
async init() { return this; }
|
|
20
|
+
async writeRecord(producerId, instance, { recordId }) { this.records.push({ producerId, recordId, instance }); return { producerId, recordId, instance }; }
|
|
21
|
+
async appendArtifactEvent(producerId, recordId, event) { this.events.push({ producerId, recordId, event }); return event; }
|
|
22
|
+
async writeSessionLocator(producerId, recordId, sessionFile) { this.locators.push({ producerId, recordId, sessionFile }); }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
let sdkListener;
|
|
26
|
+
const session = {
|
|
27
|
+
sessionId: "sdk-session",
|
|
28
|
+
sessionName: "SDK agent",
|
|
29
|
+
isStreaming: false,
|
|
30
|
+
model: { provider: "anthropic", id: "model" },
|
|
31
|
+
thinkingLevel: "high",
|
|
32
|
+
subscribe(listener) { sdkListener = listener; return () => { sdkListener = undefined; }; },
|
|
33
|
+
};
|
|
34
|
+
const memory = new MemoryRegistry();
|
|
35
|
+
let clock = 1_000;
|
|
36
|
+
const tracked = trackPiAgentSession({ session, registry: memory, producerId: "sdk-test", instanceId: "sdk-instance", runId: "sdk-run", recordId: "sdk-record", now: () => ++clock, heartbeatMs: 60_000 });
|
|
37
|
+
await tracked.ready;
|
|
38
|
+
sdkListener({ type: "agent_start" });
|
|
39
|
+
sdkListener({ type: "tool_execution_start", toolName: "read", args: { secret: "must-not-persist" } });
|
|
40
|
+
sdkListener({ type: "tool_execution_end", toolName: "read", result: { secret: "must-not-persist" }, isError: false });
|
|
41
|
+
sdkListener({ type: "message_end", message: { role: "assistant", content: "private prompt", usage: { input: 3, output: 4 } } });
|
|
42
|
+
sdkListener({ type: "agent_settled" });
|
|
43
|
+
await tracked.flush();
|
|
44
|
+
assert.equal(memory.records.at(-1).instance.status, "done");
|
|
45
|
+
assert.equal(memory.records.at(-1).instance.endedAt, memory.records.at(-1).instance.updatedAt);
|
|
46
|
+
assert.equal(memory.records.some((item) => item.instance.currentTool === "read"), true);
|
|
47
|
+
assert.equal(memory.events.some((item) => item.event.tool === "read"), true);
|
|
48
|
+
assert.equal(memory.events.some((item) => item.event.usage?.input === 3), true);
|
|
49
|
+
assert.doesNotMatch(JSON.stringify({ records: memory.records, events: memory.events }), /must-not-persist|private prompt/, "SDK overview/artifacts must omit args and message text");
|
|
50
|
+
await tracked.dispose();
|
|
51
|
+
assert.equal(sdkListener, undefined, "dispose must unsubscribe without disposing the caller-owned session");
|
|
52
|
+
|
|
53
|
+
{
|
|
54
|
+
let listener;
|
|
55
|
+
let attempts = 0;
|
|
56
|
+
const recoveringRegistry = new MemoryRegistry();
|
|
57
|
+
recoveringRegistry.writeRecord = async (...args) => {
|
|
58
|
+
attempts += 1;
|
|
59
|
+
if (attempts === 1) throw new Error("temporary registry failure");
|
|
60
|
+
return MemoryRegistry.prototype.writeRecord.apply(recoveringRegistry, args);
|
|
61
|
+
};
|
|
62
|
+
const recoveringSession = { ...session, subscribe(value) { listener = value; return () => { listener = undefined; }; } };
|
|
63
|
+
const recovering = trackPiAgentSession({ session: recoveringSession, registry: recoveringRegistry, instanceId: "recovering-sdk", runId: "recovering-run", recordId: "recovering-record", heartbeatMs: 60_000 });
|
|
64
|
+
await recovering.ready;
|
|
65
|
+
assert.match(recovering.observationError, /temporary registry failure/);
|
|
66
|
+
listener({ type: "agent_start" });
|
|
67
|
+
await recovering.flush();
|
|
68
|
+
assert.ok(recoveringRegistry.records.length > 0, "a failed SDK write must not poison later registry writes");
|
|
69
|
+
await recovering.dispose();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
{
|
|
73
|
+
let listener;
|
|
74
|
+
const emitted = [];
|
|
75
|
+
const eventSession = { ...session, subscribe(value) { listener = value; return () => { listener = undefined; }; } };
|
|
76
|
+
const eventTracked = trackPiAgentSessionEventBus({ session: eventSession, producerId: "sdk-event-test", instanceId: "event-sdk", runId: "event-run", heartbeatMs: 60_000, emit: (name, payload) => emitted.push({ name, payload }) });
|
|
77
|
+
listener({ type: "agent_start" });
|
|
78
|
+
listener({ type: "agent_settled" });
|
|
79
|
+
assert.equal(emitted.at(-1).name, "firstpick:webui-agent-runs:v1");
|
|
80
|
+
assert.equal(emitted.at(-1).payload.instances[0].status, "done");
|
|
81
|
+
eventTracked.dispose();
|
|
82
|
+
assert.equal(listener, undefined);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
for (const [stopReason, expectedStatus] of [["aborted", "cancelled"], ["error", "failed"]]) {
|
|
86
|
+
let listener;
|
|
87
|
+
const terminalRegistry = new MemoryRegistry();
|
|
88
|
+
const terminalSession = { ...session, sessionId: `sdk-${stopReason}`, subscribe(value) { listener = value; return () => { listener = undefined; }; } };
|
|
89
|
+
const terminal = trackPiAgentSession({ terminalSession, session: terminalSession, registry: terminalRegistry, producerId: "sdk-test", instanceId: `sdk-${stopReason}`, runId: `run-${stopReason}`, recordId: `record-${stopReason}`, heartbeatMs: 60_000 });
|
|
90
|
+
await terminal.ready;
|
|
91
|
+
listener({ type: "agent_start" });
|
|
92
|
+
listener({ type: "agent_end", messages: [{ role: "assistant", stopReason }], willRetry: false });
|
|
93
|
+
listener({ type: "agent_settled" });
|
|
94
|
+
await terminal.flush();
|
|
95
|
+
assert.equal(terminalRegistry.records.at(-1).instance.status, expectedStatus, `SDK ${stopReason} lifecycle must remain terminal after settlement`);
|
|
96
|
+
await terminal.dispose();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const temp = await mkdtemp(path.join(tmpdir(), "pi-webui-agent-adapters-"));
|
|
100
|
+
try {
|
|
101
|
+
const registry = new AgentRunRegistry({ agentDir: path.join(temp, "agent"), port: 31415, stateHome: path.join(temp, "state"), eventMaxBytes: 4_096 });
|
|
102
|
+
await registry.init();
|
|
103
|
+
const jsonScript = [
|
|
104
|
+
"process.stdout.write(JSON.stringify({type:'agent_start'}) + '\\r\\n');",
|
|
105
|
+
"process.stdout.write(JSON.stringify({type:'tool_execution_start',toolName:'bash',args:{token:'secret'}}) + '\\n');",
|
|
106
|
+
"process.stdout.write(JSON.stringify({type:'message_update',message:{content:'a\\u2028b'}}) + '\\n');",
|
|
107
|
+
"process.stdout.write('{bad}\\n');",
|
|
108
|
+
].join("");
|
|
109
|
+
const jsonRun = startObservedPiProcess({ registry, launcher: "pi-json", producerId: "json", command: process.execPath, argv: ["-e", jsonScript], recordId: "json-record", instanceId: "json-instance", runId: "json-run" });
|
|
110
|
+
assert.equal((await jsonRun.completion).status, "done");
|
|
111
|
+
const jsonArtifact = await registry.readArtifact("json-record");
|
|
112
|
+
assert.ok(jsonArtifact.events.some((event) => event.type === "agent_start"), "CRLF framed event must parse");
|
|
113
|
+
assert.ok(jsonArtifact.events.some((event) => event.type === "tool_execution_start" && event.tool === "bash"));
|
|
114
|
+
assert.ok(jsonArtifact.events.some((event) => event.type === "message_update"), "Unicode line separators inside JSON must not split framing");
|
|
115
|
+
assert.ok(jsonArtifact.events.some((event) => event.type === "invalid_frame" && event.status === "malformed"));
|
|
116
|
+
assert.doesNotMatch(JSON.stringify(jsonArtifact), /secret|a\\u2028b/, "structured captures must omit args and message content");
|
|
117
|
+
|
|
118
|
+
const rpcScript = "process.stdout.write(JSON.stringify({type:'event',event:{type:'tool_execution_start',toolName:'read'}})+'\\n');process.stdout.write(JSON.stringify({type:'response',success:true})+'\\n');";
|
|
119
|
+
const rpcRun = startObservedPiProcess({ registry, launcher: "pi-rpc", producerId: "rpc", command: process.execPath, argv: ["-e", rpcScript], recordId: "rpc-record", instanceId: "rpc-instance", runId: "rpc-run" });
|
|
120
|
+
assert.equal((await rpcRun.completion).status, "done");
|
|
121
|
+
const rpcArtifact = await registry.readArtifact("rpc-record");
|
|
122
|
+
assert.ok(rpcArtifact.events.some((event) => event.type === "tool_execution_start"));
|
|
123
|
+
assert.ok(rpcArtifact.events.some((event) => event.type === "rpc_response" && event.status === "ok"));
|
|
124
|
+
|
|
125
|
+
const printScript = "process.stdout.write('x'.repeat(4000));process.stderr.write('print-error');process.exitCode=7";
|
|
126
|
+
const printRun = startObservedPiProcess({ registry, launcher: "pi-print", producerId: "print", command: process.execPath, argv: ["-e", printScript], outputBytes: 1_024, recordId: "print-record", instanceId: "print-instance", runId: "print-run" });
|
|
127
|
+
const printResult = await printRun.completion;
|
|
128
|
+
assert.equal(printResult.status, "failed");
|
|
129
|
+
assert.equal(printResult.code, 7);
|
|
130
|
+
assert.ok(Buffer.byteLength(printResult.stdout) <= 1_024, "print stdout tail must be bounded");
|
|
131
|
+
assert.match(printResult.stderr, /print-error/);
|
|
132
|
+
assert.equal((await registry.readRecords()).records.find((item) => item.recordId === "print-record").instance.status, "failed");
|
|
133
|
+
|
|
134
|
+
const quietRun = startObservedPiProcess({ registry, launcher: "pi-print", producerId: "quiet", command: process.execPath, argv: ["-e", "setTimeout(() => {}, 1400)"], heartbeatMs: 1_000, recordId: "quiet-record", instanceId: "quiet-instance", runId: "quiet-run" });
|
|
135
|
+
await quietRun.ready;
|
|
136
|
+
await delay(1_100);
|
|
137
|
+
const quietSnapshot = await registry.readRecords({ now: Date.now(), maxRecords: 100 });
|
|
138
|
+
assert.equal(quietSnapshot.records.find((item) => item.recordId === "quiet-record")?.instance.status, "running", "owned quiet subprocess heartbeat must prevent registry aging");
|
|
139
|
+
assert.equal((await quietRun.completion).status, "done");
|
|
140
|
+
|
|
141
|
+
const cancelRun = startObservedPiProcess({ registry, launcher: "pi-print", producerId: "cancel", command: process.execPath, argv: ["-e", "setInterval(() => {}, 1000)"], recordId: "cancel-record", instanceId: "cancel-instance", runId: "cancel-run" });
|
|
142
|
+
await cancelRun.ready;
|
|
143
|
+
assert.equal(cancelRun.cancel(), true, "adapter may cancel the child it spawned");
|
|
144
|
+
assert.equal((await cancelRun.completion).status, "cancelled");
|
|
145
|
+
|
|
146
|
+
let spawnEvidence;
|
|
147
|
+
let forwardedOutput = "";
|
|
148
|
+
let forwardedError = "";
|
|
149
|
+
const fakeChild = new EventEmitter();
|
|
150
|
+
fakeChild.stdout = new PassThrough();
|
|
151
|
+
fakeChild.stderr = new PassThrough();
|
|
152
|
+
fakeChild.pid = 999999;
|
|
153
|
+
fakeChild.exitCode = null;
|
|
154
|
+
fakeChild.signalCode = null;
|
|
155
|
+
fakeChild.kill = () => true;
|
|
156
|
+
const declared = startObservedPiProcess({
|
|
157
|
+
registry: new MemoryRegistry(), launcher: "pi-print", command: "pi", argv: ["-p", "literal ; not shell"],
|
|
158
|
+
recordId: "declared-record", instanceId: "declared-instance", runId: "declared-run",
|
|
159
|
+
stdoutSink: { write(chunk) { forwardedOutput += String(chunk); } }, stderrSink: { write(chunk) { forwardedError += String(chunk); } },
|
|
160
|
+
spawnImpl(command, argv, options) {
|
|
161
|
+
spawnEvidence = { command, argv, options };
|
|
162
|
+
queueMicrotask(() => { fakeChild.stdout.write("visible"); fakeChild.stderr.write("diagnostic"); fakeChild.exitCode = 0; fakeChild.emit("close", 0, null); });
|
|
163
|
+
return fakeChild;
|
|
164
|
+
},
|
|
165
|
+
});
|
|
166
|
+
await declared.completion;
|
|
167
|
+
assert.deepEqual(spawnEvidence.argv, ["-p", "literal ; not shell"]);
|
|
168
|
+
assert.equal(spawnEvidence.options.shell, false, "declared argv must never use a shell");
|
|
169
|
+
assert.equal(forwardedOutput, "visible", "CLI/library callers may tee observed stdout without changing framing");
|
|
170
|
+
assert.equal(forwardedError, "diagnostic", "CLI/library callers may tee observed stderr");
|
|
171
|
+
|
|
172
|
+
const failingChild = new EventEmitter();
|
|
173
|
+
failingChild.stdout = new PassThrough();
|
|
174
|
+
failingChild.stderr = new PassThrough();
|
|
175
|
+
failingChild.pid = 999998;
|
|
176
|
+
failingChild.exitCode = null;
|
|
177
|
+
failingChild.signalCode = null;
|
|
178
|
+
failingChild.kill = () => true;
|
|
179
|
+
const failingRegistry = { writeRecord: async () => { throw new Error("registry unavailable"); }, appendArtifactEvent: async () => { throw new Error("registry unavailable"); } };
|
|
180
|
+
const observationFailure = startObservedPiProcess({
|
|
181
|
+
registry: failingRegistry, launcher: "pi-print", command: "pi", argv: [], recordId: "failure-record", instanceId: "failure-instance", runId: "failure-run",
|
|
182
|
+
spawnImpl() { queueMicrotask(() => { failingChild.exitCode = 0; failingChild.emit("close", 0, null); }); return failingChild; },
|
|
183
|
+
});
|
|
184
|
+
assert.match((await observationFailure.completion).observationError, /registry unavailable/, "registry failures must settle rather than hanging the owned process observer");
|
|
185
|
+
|
|
186
|
+
const sessionsRoot = path.join(temp, "agent", "sessions");
|
|
187
|
+
await mkdir(sessionsRoot, { recursive: true });
|
|
188
|
+
const sessionFile = path.join(sessionsRoot, "attached.jsonl");
|
|
189
|
+
await writeFile(sessionFile, '{"type":"session","id":"attach-id"}\n');
|
|
190
|
+
const FakeSessionManager = {
|
|
191
|
+
async listAll() { return [{ id: "attach-id", path: sessionFile }]; },
|
|
192
|
+
open(file) {
|
|
193
|
+
assert.equal(file, sessionFile);
|
|
194
|
+
return { getSessionId: () => "attach-id", getSessionName: () => "Attached", buildSessionContext: () => ({ model: { provider: "p", modelId: "m" }, thinkingLevel: "medium" }) };
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
assert.equal((await resolveAttachSession({ session: "attach-id", sessionRoots: [sessionsRoot], SessionManagerImpl: FakeSessionManager })).sessionFile, sessionFile);
|
|
198
|
+
await assert.rejects(() => resolveAttachSession({ session: path.join(temp, "outside.jsonl"), sessionRoots: [sessionsRoot], SessionManagerImpl: FakeSessionManager }), /inside a configured Pi session root/);
|
|
199
|
+
|
|
200
|
+
const attachRegistry = new MemoryRegistry();
|
|
201
|
+
let cliOutput = "";
|
|
202
|
+
const exitCode = await runAgentCli(["attach", "--session", "attach-id", "--name", "Mirror", "--port", "4567"], {
|
|
203
|
+
agentDir: path.join(temp, "agent"), registry: attachRegistry, SessionManagerImpl: FakeSessionManager,
|
|
204
|
+
output: { write(value) { cliOutput += value; } }, errorOutput: { write() {} },
|
|
205
|
+
});
|
|
206
|
+
assert.equal(exitCode, 0);
|
|
207
|
+
assert.equal(attachRegistry.records[0].instance.launcher, "interactive");
|
|
208
|
+
assert.equal(attachRegistry.records[0].instance.status, "stale", "attach without a reporter must not claim running");
|
|
209
|
+
assert.equal(attachRegistry.records[0].instance.capabilities.cancel, false, "PID/session evidence must not grant cancellation");
|
|
210
|
+
assert.equal(attachRegistry.locators[0].sessionFile, sessionFile);
|
|
211
|
+
assert.match(cliOutput, /^WebUI registration: port=4567 scope=custom-registry\nattach-id:/, "CLI must print its explicit non-default registration scope");
|
|
212
|
+
|
|
213
|
+
await delay(10);
|
|
214
|
+
console.log("agent-run-adapters.test.mjs passed");
|
|
215
|
+
} finally {
|
|
216
|
+
await rm(temp, { recursive: true, force: true });
|
|
217
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { managedRuntimePaths, writeRuntimePointer } from "../lib/update/supervisor.mjs";
|
|
9
|
+
|
|
10
|
+
const execFileAsync = promisify(execFile);
|
|
11
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
12
|
+
const launcher = path.join(root, "bin", "pi-webui-launcher.mjs");
|
|
13
|
+
const temp = await mkdtemp(path.join(tmpdir(), "pi-webui-agent-launcher-"));
|
|
14
|
+
try {
|
|
15
|
+
const agentHelp = await execFileAsync(process.execPath, [launcher, "agent", "help"], {
|
|
16
|
+
env: { ...process.env, PI_CODING_AGENT_DIR: path.join(temp, "agent-help") },
|
|
17
|
+
});
|
|
18
|
+
assert.match(agentHelp.stdout, /pi-webui agent run/);
|
|
19
|
+
assert.doesNotMatch(agentHelp.stdout, /Pi Web UI:/, "agent routing must not start the HTTP server");
|
|
20
|
+
|
|
21
|
+
const agentDir = path.join(temp, "agent-plain");
|
|
22
|
+
const runtimePaths = managedRuntimePaths(agentDir);
|
|
23
|
+
const runtimeRoot = path.join(runtimePaths.runtimesDir, "test-runtime");
|
|
24
|
+
const serverEntry = path.join(runtimeRoot, "bin", "pi-webui.mjs");
|
|
25
|
+
const evidenceFile = path.join(temp, "plain-args.json");
|
|
26
|
+
await mkdir(path.dirname(serverEntry), { recursive: true });
|
|
27
|
+
await writeFile(serverEntry, [
|
|
28
|
+
"import { writeFileSync } from 'node:fs';",
|
|
29
|
+
`writeFileSync(${JSON.stringify(evidenceFile)}, JSON.stringify(process.argv.slice(2)));`,
|
|
30
|
+
"",
|
|
31
|
+
].join("\n"));
|
|
32
|
+
await writeRuntimePointer(agentDir, "current", { runtimeRoot, serverEntry, version: "test" });
|
|
33
|
+
await execFileAsync(process.execPath, [launcher, "--host", "127.0.0.1", "--port", "39999"], {
|
|
34
|
+
env: { ...process.env, PI_CODING_AGENT_DIR: agentDir },
|
|
35
|
+
});
|
|
36
|
+
assert.deepEqual(JSON.parse(await readFile(evidenceFile, "utf8")), ["--host", "127.0.0.1", "--port", "39999"], "plain pi-webui must still use the update pointer and forward argv unchanged");
|
|
37
|
+
|
|
38
|
+
console.log("agent-run-launcher.test.mjs passed");
|
|
39
|
+
} finally {
|
|
40
|
+
await rm(temp, { recursive: true, force: true });
|
|
41
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import {
|
|
3
|
+
AGENT_RUN_LAUNCHERS,
|
|
4
|
+
AGENT_RUN_OUTPUT_KINDS,
|
|
5
|
+
AGENT_RUN_STATUSES,
|
|
6
|
+
AgentRunIndex,
|
|
7
|
+
mergeAgentInstances,
|
|
8
|
+
normalizeAgentInstance,
|
|
9
|
+
normalizeProviderSnapshot,
|
|
10
|
+
} from "../lib/agent-run-protocol.mjs";
|
|
11
|
+
|
|
12
|
+
const base = (overrides = {}) => ({
|
|
13
|
+
version: 1,
|
|
14
|
+
instanceId: "instance-1",
|
|
15
|
+
runId: "run-1",
|
|
16
|
+
parentInstanceId: null,
|
|
17
|
+
parentSessionId: "parent-1",
|
|
18
|
+
launcher: "sdk",
|
|
19
|
+
provider: "webui-registry",
|
|
20
|
+
origin: "test",
|
|
21
|
+
name: "reviewer",
|
|
22
|
+
status: "running",
|
|
23
|
+
startedAt: 100,
|
|
24
|
+
updatedAt: 110,
|
|
25
|
+
endedAt: null,
|
|
26
|
+
model: "provider/model",
|
|
27
|
+
thinking: "high",
|
|
28
|
+
activityState: "tool",
|
|
29
|
+
currentTool: "read",
|
|
30
|
+
capabilities: { open: true, refresh: true, cancel: false, steer: false },
|
|
31
|
+
outputRef: { kind: "registry-artifact", id: "artifact-1" },
|
|
32
|
+
...overrides,
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
for (const launcher of AGENT_RUN_LAUNCHERS) assert.equal(normalizeAgentInstance(base({ launcher })).launcher, launcher);
|
|
36
|
+
for (const status of AGENT_RUN_STATUSES) {
|
|
37
|
+
const terminal = ["done", "failed", "cancelled"].includes(status);
|
|
38
|
+
assert.equal(normalizeAgentInstance(base({ status, endedAt: terminal ? 120 : null })).status, status);
|
|
39
|
+
}
|
|
40
|
+
for (const kind of AGENT_RUN_OUTPUT_KINDS) {
|
|
41
|
+
const outputRef = kind === "none" ? { kind } : { kind, id: "artifact-1" };
|
|
42
|
+
assert.equal(normalizeAgentInstance(base({ outputRef })).outputRef.kind, kind);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
assert.throws(() => normalizeAgentInstance(base({ version: 2 })), /version/);
|
|
46
|
+
assert.throws(() => normalizeAgentInstance(base({ launcher: "future" })), /unsupported/);
|
|
47
|
+
assert.throws(() => normalizeAgentInstance(base({ status: "unknown" })), /unsupported/);
|
|
48
|
+
assert.throws(() => normalizeAgentInstance(base({ instanceId: "../escape" })), /opaque safe identifier/);
|
|
49
|
+
assert.throws(() => normalizeAgentInstance(base({ provider: "bad/provider" })), /opaque safe identifier/);
|
|
50
|
+
assert.throws(() => normalizeAgentInstance(base({ name: "x".repeat(241) })), /exceeds 240 bytes/);
|
|
51
|
+
assert.throws(() => normalizeAgentInstance(base({ capabilities: { open: "yes" } })), /must be boolean/);
|
|
52
|
+
assert.throws(() => normalizeAgentInstance(base({ outputRef: { kind: "plain-log", id: "../../x" } })), /opaque safe identifier/);
|
|
53
|
+
assert.throws(() => normalizeAgentInstance(base({ status: "done", endedAt: null })), /endedAt is required/);
|
|
54
|
+
assert.throws(() => normalizeProviderSnapshot({ version: 1, producerId: "p", complete: true, instances: [base(), base()] }), /duplicate/);
|
|
55
|
+
|
|
56
|
+
const merged = mergeAgentInstances(
|
|
57
|
+
base({ updatedAt: 110, outputRef: { kind: "plain-log", id: "plain" }, currentTool: "read" }),
|
|
58
|
+
base({ updatedAt: 120, outputRef: { kind: "session-jsonl", id: "session" }, currentTool: "bash" }),
|
|
59
|
+
);
|
|
60
|
+
assert.equal(merged.currentTool, "bash");
|
|
61
|
+
assert.equal(merged.outputRef.kind, "session-jsonl", "stronger output evidence must win");
|
|
62
|
+
|
|
63
|
+
const index = new AgentRunIndex();
|
|
64
|
+
index.upsert(base(), { producerId: "one" });
|
|
65
|
+
index.upsert(base({ updatedAt: 120, currentTool: "bash" }), { producerId: "two" });
|
|
66
|
+
assert.equal(index.size, 1, "exact parent-scoped identity must deduplicate");
|
|
67
|
+
index.upsert(base({ instanceId: "instance-2", runId: "run-2", updatedAt: 121 }), { producerId: "one" });
|
|
68
|
+
assert.equal(index.size, 2, "same name/model/time must not deduplicate distinct IDs");
|
|
69
|
+
|
|
70
|
+
const upgrades = new AgentRunIndex();
|
|
71
|
+
upgrades.upsert(base({ instanceId: "provisional-1" }), { producerId: "p" });
|
|
72
|
+
upgrades.upsert(base({ instanceId: "session-strong", updatedAt: 130 }), { producerId: "p", previousInstanceId: "provisional-1" });
|
|
73
|
+
assert.equal(upgrades.size, 1, "explicit stronger identity must migrate without adding a row");
|
|
74
|
+
assert.equal(upgrades.values()[0].instanceId, "session-strong");
|
|
75
|
+
|
|
76
|
+
const snapshots = new AgentRunIndex();
|
|
77
|
+
snapshots.ingestSnapshot({ version: 1, producerId: "alpha", complete: true, instances: [base()] });
|
|
78
|
+
snapshots.ingestSnapshot({ version: 1, producerId: "beta", complete: true, instances: [base({ instanceId: "beta-1" })] });
|
|
79
|
+
snapshots.ingestSnapshot({ version: 1, producerId: "alpha", complete: true, instances: [] });
|
|
80
|
+
assert.deepEqual(snapshots.values().map((item) => item.instanceId), ["beta-1"], "complete snapshots clear only their producer");
|
|
81
|
+
|
|
82
|
+
console.log("agent-run-protocol.test.mjs passed");
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { lstat, mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import {
|
|
6
|
+
AGENT_RUN_REGISTRY_LIMITS,
|
|
7
|
+
AgentRunRegistry,
|
|
8
|
+
ageAgentRun,
|
|
9
|
+
agentRunRegistryPaths,
|
|
10
|
+
agentRunScopeId,
|
|
11
|
+
} from "../lib/agent-run-registry.mjs";
|
|
12
|
+
|
|
13
|
+
const base = (overrides = {}) => ({
|
|
14
|
+
version: 1, instanceId: "instance-1", runId: "run-1", parentInstanceId: null, parentSessionId: null,
|
|
15
|
+
launcher: "sdk", provider: "webui-registry", origin: "test", name: "agent", status: "running",
|
|
16
|
+
startedAt: 1_000, updatedAt: 2_000, endedAt: null, model: "p/m", thinking: "high", activityState: "thinking",
|
|
17
|
+
capabilities: { open: true, refresh: true, cancel: false, steer: false }, outputRef: { kind: "registry-artifact", id: "record-1" },
|
|
18
|
+
...overrides,
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
assert.match(agentRunScopeId("/tmp/agent", 31415), /^[a-f0-9]{64}$/);
|
|
22
|
+
assert.equal(agentRunScopeId("/tmp/agent", 31415), agentRunScopeId("/tmp/agent", 31415));
|
|
23
|
+
assert.throws(() => agentRunScopeId("/tmp/agent", 0), /between 1 and 65535/);
|
|
24
|
+
assert.equal(ageAgentRun(base(), 31_999, { staleAfterMs: 30_000, lostAfterMs: 120_000 }).status, "running");
|
|
25
|
+
assert.equal(ageAgentRun(base(), 32_000, { staleAfterMs: 30_000, lostAfterMs: 120_000 }).status, "stale");
|
|
26
|
+
assert.equal(ageAgentRun(base(), 122_000, { staleAfterMs: 30_000, lostAfterMs: 120_000 }).status, "lost");
|
|
27
|
+
assert.equal(ageAgentRun(base({ status: "done", endedAt: 2_000 }), 999_999).status, "done", "terminal evidence must win over aging");
|
|
28
|
+
|
|
29
|
+
const temp = await mkdtemp(path.join(tmpdir(), "pi-webui-agent-registry-"));
|
|
30
|
+
try {
|
|
31
|
+
let now = 10_000;
|
|
32
|
+
const registry = new AgentRunRegistry({ agentDir: path.join(temp, "agent"), port: 31415, stateHome: path.join(temp, "state"), now: () => now, eventMaxBytes: 16_384, staleAfterMs: 100, lostAfterMs: 200, finishedRetentionMs: 500 });
|
|
33
|
+
await registry.init();
|
|
34
|
+
if (process.platform !== "win32") {
|
|
35
|
+
assert.equal((await stat(registry.paths.root)).mode & 0o777, 0o700, "registry directories must be owner-private");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
await Promise.all([
|
|
39
|
+
registry.writeRecord("producer-a", base({ startedAt: 9_000, updatedAt: 10_000 }), { recordId: "record-1" }),
|
|
40
|
+
registry.writeRecord("producer-b", base({ instanceId: "instance-2", runId: "run-2", startedAt: 9_000, updatedAt: 10_000, outputRef: { kind: "none" } }), { recordId: "record-2" }),
|
|
41
|
+
]);
|
|
42
|
+
const recordFile = path.join(registry.paths.root, "producer-a", "record-1.json");
|
|
43
|
+
assert.equal(JSON.parse(await readFile(recordFile, "utf8")).instanceId, "instance-1");
|
|
44
|
+
if (process.platform !== "win32") assert.equal((await stat(recordFile)).mode & 0o777, 0o600, "record files must be owner-private");
|
|
45
|
+
assert.equal((await registry.readRecords()).records.length, 2, "separate producer records must coexist atomically");
|
|
46
|
+
|
|
47
|
+
await writeFile(path.join(registry.paths.root, "producer-a", "partial.json"), "{", { mode: 0o600 });
|
|
48
|
+
const withCorruption = await registry.readRecords();
|
|
49
|
+
assert.equal(withCorruption.records.length, 2);
|
|
50
|
+
assert.ok(withCorruption.diagnostics.some((item) => item.code === "invalid-record"), "corrupt records must be isolated");
|
|
51
|
+
|
|
52
|
+
now = 10_150;
|
|
53
|
+
assert.equal((await registry.readRecords()).records.find((item) => item.recordId === "record-1").instance.status, "stale");
|
|
54
|
+
now = 10_250;
|
|
55
|
+
assert.equal((await registry.readRecords()).records.find((item) => item.recordId === "record-1").instance.status, "lost");
|
|
56
|
+
|
|
57
|
+
for (let index = 0; index < 400; index += 1) {
|
|
58
|
+
await registry.appendArtifactEvent("producer-a", "record-1", { type: "output", stream: "stdout", message: `${index}:${"x".repeat(100)}` });
|
|
59
|
+
}
|
|
60
|
+
const artifact = await registry.readArtifact("record-1");
|
|
61
|
+
assert.ok(artifact.bytes <= 16_384, "artifact rotation must enforce the configured byte cap");
|
|
62
|
+
assert.ok(artifact.events.length < 400, "artifact rotation must retain only a bounded tail");
|
|
63
|
+
await registry.appendArtifactEvent("producer-a", "record-1", { type: "output", message: "🙂".repeat(AGENT_RUN_REGISTRY_LIMITS.eventLineBytes) });
|
|
64
|
+
const cappedMessage = (await registry.readArtifact("record-1")).events.at(-1).message;
|
|
65
|
+
assert.ok(Buffer.byteLength(cappedMessage) <= 8_192, "individual UTF-8 event text must be byte-capped before serialization");
|
|
66
|
+
await assert.rejects(() => registry.readArtifact("../record-1"), /opaque safe identifier/);
|
|
67
|
+
|
|
68
|
+
const sessions = path.join(temp, "agent", "sessions");
|
|
69
|
+
await mkdir(sessions, { recursive: true });
|
|
70
|
+
const sessionFile = path.join(sessions, "session.jsonl");
|
|
71
|
+
await writeFile(sessionFile, '{"type":"session","id":"s"}\n');
|
|
72
|
+
await registry.writeRecord("attach", base({ instanceId: "attached", launcher: "interactive", status: "stale", outputRef: { kind: "session-jsonl", id: "attach-1" } }), { recordId: "attach-1" });
|
|
73
|
+
await registry.writeSessionLocator("attach", "attach-1", sessionFile, { allowedRoots: [sessions] });
|
|
74
|
+
assert.equal((await registry.resolveSessionLocator("attach-1", { allowedRoots: [sessions] })).sessionFile, sessionFile);
|
|
75
|
+
await assert.rejects(() => registry.writeSessionLocator("attach", "attach-1", path.join(temp, "outside.jsonl"), { allowedRoots: [sessions] }), /inside a configured Pi session root/);
|
|
76
|
+
|
|
77
|
+
if (process.platform !== "win32") {
|
|
78
|
+
const outside = path.join(temp, "outside.json");
|
|
79
|
+
await writeFile(outside, `${JSON.stringify(base({ outputRef: { kind: "none" } }))}\n`);
|
|
80
|
+
await symlink(outside, path.join(registry.paths.root, "producer-a", "linked.json"));
|
|
81
|
+
const symlinkScan = await registry.readRecords();
|
|
82
|
+
assert.ok(symlinkScan.diagnostics.some((item) => item.code === "unsafe-record"), "record symlinks must be rejected");
|
|
83
|
+
|
|
84
|
+
const symlinkHome = path.join(temp, "symlink-state");
|
|
85
|
+
await symlink(path.join(temp, "state"), symlinkHome);
|
|
86
|
+
const unsafe = new AgentRunRegistry({ agentDir: path.join(temp, "agent"), port: 31416, stateHome: symlinkHome });
|
|
87
|
+
await assert.rejects(() => unsafe.init(), /must not be a symlink/);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
now = 20_000;
|
|
91
|
+
await registry.writeRecord("producer-a", base({ status: "done", updatedAt: 19_000, endedAt: 19_000 }), { recordId: "record-1" });
|
|
92
|
+
assert.equal(await registry.prune({ now, retentionMs: 500 }), 1);
|
|
93
|
+
assert.equal((await registry.readRecords({ now })).records.some((item) => item.recordId === "record-1"), false);
|
|
94
|
+
assert.equal((await registry.readRecords({ now })).records.some((item) => item.recordId === "record-2"), true, "pruning must retain non-terminal records");
|
|
95
|
+
|
|
96
|
+
const expected = agentRunRegistryPaths({ agentDir: path.join(temp, "agent"), port: 31415, stateHome: path.join(temp, "state") });
|
|
97
|
+
assert.equal(registry.paths.root, expected.root);
|
|
98
|
+
assert.equal((await lstat(registry.paths.root)).isSymbolicLink(), false);
|
|
99
|
+
console.log("agent-run-registry.test.mjs passed");
|
|
100
|
+
} finally {
|
|
101
|
+
await rm(temp, { recursive: true, force: true });
|
|
102
|
+
}
|
|
@@ -65,7 +65,7 @@ function makeEnvironment({
|
|
|
65
65
|
reload: new FakeElement(),
|
|
66
66
|
copyStatus: new FakeElement(),
|
|
67
67
|
};
|
|
68
|
-
const styleLink = new FakeElement({ href: "http://127.0.0.1:31415/styles.css?v=
|
|
68
|
+
const styleLink = new FakeElement({ href: "http://127.0.0.1:31415/styles.css?v=115", sheet: stylesheetLoaded ? {} : null });
|
|
69
69
|
const listeners = new Map();
|
|
70
70
|
const timers = new Map();
|
|
71
71
|
let timerId = 0;
|
|
@@ -84,7 +84,7 @@ function makeEnvironment({
|
|
|
84
84
|
removeEventListener(name) { listeners.delete(name); },
|
|
85
85
|
};
|
|
86
86
|
const document = {
|
|
87
|
-
currentScript: new FakeElement({ dataset: { appSrc: "/app.js?v=
|
|
87
|
+
currentScript: new FakeElement({ dataset: { appSrc: "/app.js?v=132" } }),
|
|
88
88
|
readyState: "complete",
|
|
89
89
|
querySelector(selector) {
|
|
90
90
|
return {
|
|
@@ -232,7 +232,7 @@ for (const moduleName of startupModuleNames) {
|
|
|
232
232
|
assert.ok(serviceWorker.includes(`"/${moduleName}"`), `the PWA app shell should include every app.js startup module: ${moduleName}`);
|
|
233
233
|
}
|
|
234
234
|
assert.match(serviceWorker, /pi-webui-pwa-v\d+/, "the app-shell cache should retain a versioned identity");
|
|
235
|
-
assert.ok(html.indexOf('id="webuiBootLoader"') < html.indexOf("/app.js?v=
|
|
235
|
+
assert.ok(html.indexOf('id="webuiBootLoader"') < html.indexOf("/app.js?v=132"), "the inline loader should own app module startup");
|
|
236
236
|
assert.doesNotMatch(html, /<script type="module" src="\/app\.js/, "the app module should not bypass the guarded loader");
|
|
237
237
|
|
|
238
238
|
console.log("boot-failure-diagnostics.test.mjs passed");
|