@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,69 @@
|
|
|
1
|
+
const WORKFLOW_STATUS_TOOL_NAME = "workflow_status";
|
|
2
|
+
|
|
3
|
+
export function isCompletedWorkflowStatusExecution(message) {
|
|
4
|
+
if (message?.role !== "toolExecution") return false;
|
|
5
|
+
const name = String(message.toolName || message.name || "");
|
|
6
|
+
return name === WORKFLOW_STATUS_TOOL_NAME && !message.live && !message.isPartial && message.result !== undefined && message.result !== null;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function workflowStatusStackKey(items) {
|
|
10
|
+
const first = items[0] || {};
|
|
11
|
+
const toolCallId = String(first.message?.toolCallId ?? "").trim();
|
|
12
|
+
const id = toolCallId || (first.messageIndex !== undefined ? `m:${first.messageIndex}` : first.order !== undefined ? `o:${first.order}` : "first");
|
|
13
|
+
return `workflow-status-stack:${id}`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function groupConsecutiveWorkflowStatusItems(items) {
|
|
17
|
+
const grouped = [];
|
|
18
|
+
let pending = [];
|
|
19
|
+
|
|
20
|
+
const flush = () => {
|
|
21
|
+
if (pending.length === 1) {
|
|
22
|
+
grouped.push(pending[0]);
|
|
23
|
+
} else if (pending.length > 1) {
|
|
24
|
+
const first = pending[0];
|
|
25
|
+
const latest = pending.at(-1);
|
|
26
|
+
const updates = pending.map((item) => item.message);
|
|
27
|
+
grouped.push({
|
|
28
|
+
...first,
|
|
29
|
+
message: {
|
|
30
|
+
role: "workflowStatusStack",
|
|
31
|
+
title: `workflow_status · ${updates.length} updates`,
|
|
32
|
+
timestamp: latest.message?.timestamp || first.message?.timestamp,
|
|
33
|
+
content: latest.message?.result?.content,
|
|
34
|
+
workflowStatusUpdates: updates,
|
|
35
|
+
isError: updates.some((update) => update?.isError || update?.result?.isError),
|
|
36
|
+
},
|
|
37
|
+
transcriptKey: workflowStatusStackKey(pending),
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
pending = [];
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
for (const item of items || []) {
|
|
44
|
+
if (isCompletedWorkflowStatusExecution(item?.message)) pending.push(item);
|
|
45
|
+
else {
|
|
46
|
+
flush();
|
|
47
|
+
grouped.push(item);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
flush();
|
|
51
|
+
return grouped;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function workflowStatusSnapshot(text) {
|
|
55
|
+
const fields = {};
|
|
56
|
+
const lines = String(text || "").split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
|
57
|
+
for (const line of lines) {
|
|
58
|
+
const match = /^(Workflow|Run|Status|Tasks):\s*(.+)$/i.exec(line);
|
|
59
|
+
if (match) fields[match[1].toLowerCase()] = match[2].trim();
|
|
60
|
+
}
|
|
61
|
+
const fallback = lines[0] || "No workflow status details were returned.";
|
|
62
|
+
return {
|
|
63
|
+
workflow: fields.workflow || "",
|
|
64
|
+
run: fields.run || "",
|
|
65
|
+
status: fields.status || "",
|
|
66
|
+
tasks: fields.tasks || "",
|
|
67
|
+
fallback: fallback.length > 180 ? `${fallback.slice(0, 179)}…` : fallback,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
@@ -6,6 +6,8 @@ import path from "node:path";
|
|
|
6
6
|
import { setTimeout as delay } from "node:timers/promises";
|
|
7
7
|
import { dirname, join } from "node:path";
|
|
8
8
|
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { connectRpcSupervisor } from "../lib/rpc-supervisor-client.mjs";
|
|
10
|
+
import { readSupervisorState, supervisorPaths } from "../lib/rpc-supervisor-state.mjs";
|
|
9
11
|
|
|
10
12
|
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
11
13
|
const serverScript = join(root, "bin", "pi-webui.mjs");
|
|
@@ -53,6 +55,8 @@ function killFixtureProcess(pid) {
|
|
|
53
55
|
}
|
|
54
56
|
|
|
55
57
|
const cwd = await mkdtemp(path.join(tmpdir(), "pi-webui-app-runner-tree-"));
|
|
58
|
+
const agentDir = path.join(cwd, "agent");
|
|
59
|
+
const supervisorStatePaths = await supervisorPaths({ agentDir, port });
|
|
56
60
|
const settingsFile = path.join(cwd, "webui-settings.json");
|
|
57
61
|
await chmod(fakePi, 0o755);
|
|
58
62
|
await writeFile(path.join(cwd, "tree-child.mjs"), "setInterval(() => {}, 1000);\n");
|
|
@@ -72,27 +76,37 @@ const server = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "1
|
|
|
72
76
|
stdio: ["ignore", "pipe", "pipe"],
|
|
73
77
|
env: {
|
|
74
78
|
...process.env,
|
|
79
|
+
PI_CODING_AGENT_DIR: agentDir,
|
|
75
80
|
PI_WEBUI_SETTINGS_FILE: settingsFile,
|
|
76
81
|
PI_WEBUI_APP_RUNNER_PTY: "off",
|
|
77
82
|
},
|
|
78
83
|
windowsHide: true,
|
|
79
84
|
});
|
|
80
85
|
let serverOutput = "";
|
|
86
|
+
let piPid = 0;
|
|
87
|
+
let supervisorPid = 0;
|
|
81
88
|
let runnerPid = 0;
|
|
82
89
|
let treeChildPid = 0;
|
|
83
90
|
server.stdout.on("data", (chunk) => { serverOutput += String(chunk); });
|
|
84
91
|
server.stderr.on("data", (chunk) => { serverOutput += String(chunk); });
|
|
85
92
|
|
|
86
93
|
try {
|
|
87
|
-
await waitFor("server health", async () => {
|
|
94
|
+
const health = await waitFor("server health", async () => {
|
|
88
95
|
if (server.exitCode !== null) return false;
|
|
89
96
|
try {
|
|
90
|
-
const
|
|
91
|
-
return
|
|
97
|
+
const response = await request("/api/health", { timeoutMs: 1_000 });
|
|
98
|
+
return response.status === 200 && response.body?.ok === true ? response : false;
|
|
92
99
|
} catch {
|
|
93
100
|
return false;
|
|
94
101
|
}
|
|
95
102
|
}, { attempts: 100, intervalMs: 120 });
|
|
103
|
+
piPid = Number(health.body?.piPid) || 0;
|
|
104
|
+
assert.ok(piPid > 0, `startup fake Pi PID should be available, output:\n${serverOutput}`);
|
|
105
|
+
if (health.body?.rpcSupervisor?.enabled === true) {
|
|
106
|
+
const state = await waitFor("isolated supervisor state", () => readSupervisorState(supervisorStatePaths));
|
|
107
|
+
supervisorPid = Number(state.pid) || 0;
|
|
108
|
+
assert.ok(supervisorPid > 0, "isolated supervisor state should identify its process");
|
|
109
|
+
}
|
|
96
110
|
|
|
97
111
|
const tabsResponse = await request("/api/tabs");
|
|
98
112
|
const tabId = tabsResponse.body?.data?.tabs?.[0]?.id || tabsResponse.body?.tabs?.[0]?.id;
|
|
@@ -149,6 +163,11 @@ try {
|
|
|
149
163
|
await request("/api/shutdown", { method: "POST" }).catch(() => undefined);
|
|
150
164
|
for (let attempt = 0; attempt < 50 && server.exitCode === null; attempt += 1) await delay(100);
|
|
151
165
|
assert.notEqual(server.exitCode, null, "server should exit after /api/shutdown");
|
|
166
|
+
await waitFor("fake Pi teardown", () => !isProcessRunning(piPid));
|
|
167
|
+
if (supervisorPid > 0) await waitFor("supervisor teardown", () => !isProcessRunning(supervisorPid));
|
|
168
|
+
await waitFor("isolated supervisor state cleanup", async () => (await readSupervisorState(supervisorStatePaths)) === null);
|
|
169
|
+
assert.equal(isProcessRunning(piPid), false, "server teardown must not leave its fake Pi running");
|
|
170
|
+
assert.equal(isProcessRunning(supervisorPid), false, "server teardown must not leave its supervisor running");
|
|
152
171
|
console.log("app-runner-process-tree-harness.test.mjs passed");
|
|
153
172
|
} finally {
|
|
154
173
|
if (server.exitCode === null) {
|
|
@@ -156,7 +175,22 @@ try {
|
|
|
156
175
|
for (let attempt = 0; attempt < 20 && server.exitCode === null; attempt += 1) await delay(100);
|
|
157
176
|
if (server.exitCode === null) server.kill("SIGKILL");
|
|
158
177
|
}
|
|
178
|
+
const remainingSupervisor = await readSupervisorState(supervisorStatePaths).catch(() => null);
|
|
179
|
+
if (remainingSupervisor) {
|
|
180
|
+
const cleanupClient = await connectRpcSupervisor({
|
|
181
|
+
agentDir,
|
|
182
|
+
port,
|
|
183
|
+
controllerId: "app-runner-process-tree-cleanup",
|
|
184
|
+
connectTimeoutMs: 1_000,
|
|
185
|
+
}).catch(() => null);
|
|
186
|
+
if (cleanupClient) {
|
|
187
|
+
try { await cleanupClient.shutdown(); } catch {}
|
|
188
|
+
cleanupClient.close();
|
|
189
|
+
}
|
|
190
|
+
}
|
|
159
191
|
killFixtureProcess(runnerPid);
|
|
160
192
|
killFixtureProcess(treeChildPid);
|
|
193
|
+
killFixtureProcess(piPid);
|
|
194
|
+
killFixtureProcess(supervisorPid);
|
|
161
195
|
await rm(cwd, { recursive: true, force: true });
|
|
162
196
|
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import vm from "node:vm";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
|
|
7
|
+
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
8
|
+
const [html, app, serviceWorker] = await Promise.all([
|
|
9
|
+
readFile(join(root, "public", "index.html"), "utf8"),
|
|
10
|
+
readFile(join(root, "public", "app.js"), "utf8"),
|
|
11
|
+
readFile(join(root, "public", "service-worker.js"), "utf8"),
|
|
12
|
+
]);
|
|
13
|
+
|
|
14
|
+
const loaderMatch = html.match(/<script id="webuiBootLoader"[^>]*>([\s\S]*?)<\/script>/);
|
|
15
|
+
assert.ok(loaderMatch, "index.html should contain the inline WebUI boot loader");
|
|
16
|
+
const loaderSource = loaderMatch[1];
|
|
17
|
+
|
|
18
|
+
class FakeElement {
|
|
19
|
+
constructor(values = {}) {
|
|
20
|
+
Object.assign(this, values);
|
|
21
|
+
this.listeners = new Map();
|
|
22
|
+
this.hidden ??= true;
|
|
23
|
+
this.value ??= "";
|
|
24
|
+
this.textContent ??= "";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
addEventListener(name, listener) {
|
|
28
|
+
this.listeners.set(name, listener);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
focus() {}
|
|
32
|
+
select() { this.selected = true; }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
class FakeResponse {
|
|
36
|
+
constructor(url, status, { type = "text/plain", text = "", json = null } = {}) {
|
|
37
|
+
this.url = url;
|
|
38
|
+
this.status = status;
|
|
39
|
+
this.ok = status >= 200 && status < 300;
|
|
40
|
+
this._text = text;
|
|
41
|
+
this._json = json;
|
|
42
|
+
this.headers = { get: (name) => name.toLowerCase() === "content-type" ? type : null };
|
|
43
|
+
this.body = { cancel: async () => {} };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
clone() { return new FakeResponse(this.url, this.status, { type: this.headers.get("content-type"), text: this._text, json: this._json }); }
|
|
47
|
+
async text() { return this._text; }
|
|
48
|
+
async json() { return this._json; }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function makeEnvironment({ importApp, stylesheetLoaded = true, stylesheetStatus = 200, workflowModuleStatus = 404 } = {}) {
|
|
52
|
+
const elements = {
|
|
53
|
+
panel: new FakeElement({ hidden: true }),
|
|
54
|
+
reason: new FakeElement(),
|
|
55
|
+
report: new FakeElement({ value: "Collecting diagnostics…" }),
|
|
56
|
+
copy: new FakeElement(),
|
|
57
|
+
reload: new FakeElement(),
|
|
58
|
+
copyStatus: new FakeElement(),
|
|
59
|
+
};
|
|
60
|
+
const styleLink = new FakeElement({ href: "http://127.0.0.1:31415/styles.css?v=84", sheet: stylesheetLoaded ? {} : null });
|
|
61
|
+
const listeners = new Map();
|
|
62
|
+
const timers = new Map();
|
|
63
|
+
let timerId = 0;
|
|
64
|
+
let copied = "";
|
|
65
|
+
let reloaded = false;
|
|
66
|
+
|
|
67
|
+
const location = {
|
|
68
|
+
href: "http://127.0.0.1:31415/?pin=SUPERSECRET#private",
|
|
69
|
+
origin: "http://127.0.0.1:31415",
|
|
70
|
+
reload() { reloaded = true; },
|
|
71
|
+
};
|
|
72
|
+
const window = {
|
|
73
|
+
location,
|
|
74
|
+
__PI_WEBUI_BOOT_IMPORT__: importApp,
|
|
75
|
+
addEventListener(name, listener) { listeners.set(name, listener); },
|
|
76
|
+
removeEventListener(name) { listeners.delete(name); },
|
|
77
|
+
};
|
|
78
|
+
const document = {
|
|
79
|
+
currentScript: new FakeElement({ dataset: { appSrc: "/app.js?v=91" } }),
|
|
80
|
+
readyState: "complete",
|
|
81
|
+
querySelector(selector) {
|
|
82
|
+
return {
|
|
83
|
+
"#webuiBootFailurePanel": elements.panel,
|
|
84
|
+
"#webuiBootFailureReason": elements.reason,
|
|
85
|
+
"#webuiBootFailureReport": elements.report,
|
|
86
|
+
"#copyWebuiBootFailureReportButton": elements.copy,
|
|
87
|
+
"#reloadWebuiAfterBootFailureButton": elements.reload,
|
|
88
|
+
"#webuiBootFailureCopyStatus": elements.copyStatus,
|
|
89
|
+
'link[rel="stylesheet"]': styleLink,
|
|
90
|
+
}[selector] || null;
|
|
91
|
+
},
|
|
92
|
+
execCommand() { return true; },
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
async function fetch(input) {
|
|
96
|
+
const url = String(input);
|
|
97
|
+
if (url.includes("/api/health")) return new FakeResponse(url, 200, { type: "application/json", json: { ok: true, webuiVersion: "0.7.6", remoteAuthPin: "1234" } });
|
|
98
|
+
if (url.includes("/app.js")) return new FakeResponse(url, 200, { type: "text/javascript", text: 'import "./workflow-status-stack.mjs";\nimport "./fast-output-live.mjs";' });
|
|
99
|
+
if (url.includes("workflow-status-stack.mjs")) return new FakeResponse(url, workflowModuleStatus, { type: workflowModuleStatus === 200 ? "text/javascript" : "application/json" });
|
|
100
|
+
if (url.includes("fast-output-live.mjs")) return new FakeResponse(url, 200, { type: "text/javascript" });
|
|
101
|
+
if (url.includes("styles.css")) return new FakeResponse(url, stylesheetStatus, { type: "text/css" });
|
|
102
|
+
return new FakeResponse(url, 404);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const context = {
|
|
106
|
+
window,
|
|
107
|
+
document,
|
|
108
|
+
navigator: {
|
|
109
|
+
userAgent: "Boot diagnostics test browser",
|
|
110
|
+
clipboard: { async writeText(value) { copied = value; } },
|
|
111
|
+
},
|
|
112
|
+
fetch,
|
|
113
|
+
URL,
|
|
114
|
+
Error,
|
|
115
|
+
Date,
|
|
116
|
+
Promise,
|
|
117
|
+
console,
|
|
118
|
+
setTimeout(callback) { const id = ++timerId; timers.set(id, callback); return id; },
|
|
119
|
+
clearTimeout(id) { timers.delete(id); },
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
return {
|
|
123
|
+
context,
|
|
124
|
+
elements,
|
|
125
|
+
listeners,
|
|
126
|
+
timers,
|
|
127
|
+
copied: () => copied,
|
|
128
|
+
reloaded: () => reloaded,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function settleAsyncWork() {
|
|
133
|
+
for (let index = 0; index < 8; index += 1) await new Promise((resolve) => setImmediate(resolve));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const missingModule = makeEnvironment({
|
|
137
|
+
importApp: async () => { throw new Error("Failed to fetch dynamically imported module: http://127.0.0.1:31415/workflow-status-stack.mjs?pin=SUPERSECRET"); },
|
|
138
|
+
});
|
|
139
|
+
vm.runInNewContext(loaderSource, missingModule.context, { filename: "webui-boot-loader.js" });
|
|
140
|
+
await settleAsyncWork();
|
|
141
|
+
assert.equal(missingModule.elements.panel.hidden, false, "a rejected app import should expose the boot-failure panel");
|
|
142
|
+
assert.match(missingModule.elements.report.value, /Pi Web UI startup failure/);
|
|
143
|
+
assert.match(missingModule.elements.report.value, /Diagnosis[\s\S]*Summary: Missing startup module: \/workflow-status-stack\.mjs \(HTTP 404\)\./, "the diagnosis should name the actual missing transitive import before the full checks list");
|
|
144
|
+
assert.match(missingModule.elements.report.value, /Likely cause: The backend is healthy, but the running server's static asset allowlist is out of sync with app\.js\./);
|
|
145
|
+
assert.match(missingModule.elements.report.value, /Browser note: a transitive import failure may be reported as app\.js/);
|
|
146
|
+
assert.match(missingModule.elements.report.value, /Failing checks[\s\S]*HTTP 404 application\/json/, "the report should isolate failing probes");
|
|
147
|
+
assert.match(missingModule.elements.report.value, /Recheck the failing asset: curl -i http:\/\/127\.0\.0\.1:31415\/workflow-status-stack\.mjs/);
|
|
148
|
+
assert.match(missingModule.elements.report.value, /backend health: HTTP 200 application\/json \(ok=true, webuiVersion=0\.7\.6\)/);
|
|
149
|
+
assert.equal(missingModule.elements.reason.textContent, "Missing startup module: /workflow-status-stack.mjs (HTTP 404).", "the visible summary should expose the diagnosed file without requiring report inspection");
|
|
150
|
+
assert.match(missingModule.elements.report.value, /\/webui-status detailed/);
|
|
151
|
+
assert.doesNotMatch(missingModule.elements.report.value, /SUPERSECRET|remoteAuthPin|1234/, "diagnostics must omit URL secrets and unselected health fields");
|
|
152
|
+
await missingModule.elements.copy.listeners.get("click")();
|
|
153
|
+
assert.equal(missingModule.copied(), missingModule.elements.report.value, "Copy troubleshooting report should copy the complete generated report");
|
|
154
|
+
assert.equal(missingModule.elements.copyStatus.textContent, "Troubleshooting report copied.");
|
|
155
|
+
missingModule.elements.reload.listeners.get("click")();
|
|
156
|
+
assert.equal(missingModule.reloaded(), true, "Reload page should remain available without app.js");
|
|
157
|
+
|
|
158
|
+
const successfulBoot = makeEnvironment({ importApp: async () => ({}) });
|
|
159
|
+
vm.runInNewContext(loaderSource, successfulBoot.context, { filename: "webui-boot-loader.js" });
|
|
160
|
+
await settleAsyncWork();
|
|
161
|
+
assert.equal(successfulBoot.elements.panel.hidden, true, "a successful app import should keep the failure panel hidden");
|
|
162
|
+
assert.equal(successfulBoot.timers.size, 0, "successful startup should cancel the watchdog");
|
|
163
|
+
assert.equal(successfulBoot.listeners.has("error"), false, "successful startup should remove temporary global error capture");
|
|
164
|
+
|
|
165
|
+
const stylesheetFailure = makeEnvironment({ importApp: async () => ({}), stylesheetLoaded: false, stylesheetStatus: 404, workflowModuleStatus: 200 });
|
|
166
|
+
vm.runInNewContext(loaderSource, stylesheetFailure.context, { filename: "webui-boot-loader.js" });
|
|
167
|
+
await settleAsyncWork();
|
|
168
|
+
assert.equal(stylesheetFailure.elements.panel.hidden, false, "a missing critical stylesheet should expose the boot-failure panel");
|
|
169
|
+
assert.match(stylesheetFailure.elements.report.value, /Critical stylesheet returned HTTP 404/);
|
|
170
|
+
|
|
171
|
+
const startupModuleNames = [...new Set([...app.matchAll(/(?:\bfrom\s+|\bimport\s*(?:\(\s*)?)["']\.\/([^"'?]+)(?:\?[^"']*)?["']/g)].map((match) => match[1]))];
|
|
172
|
+
assert.ok(startupModuleNames.length >= 1, "the startup-module invariant should discover app.js imports");
|
|
173
|
+
for (const moduleName of startupModuleNames) {
|
|
174
|
+
assert.ok(serviceWorker.includes(`"/${moduleName}"`), `the PWA app shell should include every app.js startup module: ${moduleName}`);
|
|
175
|
+
}
|
|
176
|
+
assert.match(serviceWorker, /pi-webui-pwa-v\d+/, "the app-shell cache should retain a versioned identity");
|
|
177
|
+
assert.ok(html.indexOf('id="webuiBootLoader"') < html.indexOf("/app.js?v=91"), "the inline loader should own app module startup");
|
|
178
|
+
assert.doesNotMatch(html, /<script type="module" src="\/app\.js/, "the app module should not bypass the guarded loader");
|
|
179
|
+
|
|
180
|
+
console.log("boot-failure-diagnostics.test.mjs passed");
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
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 { connectRpcSupervisor } from "../lib/rpc-supervisor-client.mjs";
|
|
9
|
+
import { readSupervisorState, supervisorPaths } from "../lib/rpc-supervisor-state.mjs";
|
|
10
|
+
|
|
11
|
+
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
12
|
+
const serverScript = path.join(root, "bin", "pi-webui.mjs");
|
|
13
|
+
const fakePi = path.join(root, "tests", "fixtures", "fake-pi.mjs");
|
|
14
|
+
const port = 39000 + Math.floor(Math.random() * 15000);
|
|
15
|
+
const streamPrompt = "fixture continuity delayed stream";
|
|
16
|
+
|
|
17
|
+
async function request(pathname, { method = "GET", body, timeoutMs = 3_000 } = {}) {
|
|
18
|
+
const response = await fetch(`http://127.0.0.1:${port}${pathname}`, {
|
|
19
|
+
method,
|
|
20
|
+
headers: body === undefined ? undefined : { "content-type": "application/json" },
|
|
21
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
22
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
23
|
+
});
|
|
24
|
+
let payload;
|
|
25
|
+
try { payload = await response.json(); } catch { payload = undefined; }
|
|
26
|
+
return { status: response.status, body: payload };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function waitFor(label, predicate, { timeoutMs = 12_000, intervalMs = 80 } = {}) {
|
|
30
|
+
const deadline = Date.now() + timeoutMs;
|
|
31
|
+
let lastError;
|
|
32
|
+
while (Date.now() < deadline) {
|
|
33
|
+
try {
|
|
34
|
+
const value = await predicate();
|
|
35
|
+
if (value) return value;
|
|
36
|
+
} catch (error) {
|
|
37
|
+
lastError = error;
|
|
38
|
+
}
|
|
39
|
+
await delay(intervalMs);
|
|
40
|
+
}
|
|
41
|
+
throw new Error(`${label} did not happen in time${lastError ? `: ${lastError.message}` : ""}`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function initialSseEvents(tabId, expectedCount = 3) {
|
|
45
|
+
const controller = new AbortController();
|
|
46
|
+
const timeout = setTimeout(() => controller.abort(new Error("timed out reading continuity SSE state")), 5_000);
|
|
47
|
+
try {
|
|
48
|
+
const response = await fetch(`http://127.0.0.1:${port}/api/events?tab=${encodeURIComponent(tabId)}`, { signal: controller.signal });
|
|
49
|
+
assert.equal(response.status, 200, "replacement server SSE endpoint must open");
|
|
50
|
+
const reader = response.body.getReader();
|
|
51
|
+
const decoder = new TextDecoder();
|
|
52
|
+
const events = [];
|
|
53
|
+
let buffer = "";
|
|
54
|
+
while (events.length < expectedCount) {
|
|
55
|
+
const { done, value } = await reader.read();
|
|
56
|
+
if (done) break;
|
|
57
|
+
buffer += decoder.decode(value, { stream: true });
|
|
58
|
+
let boundary;
|
|
59
|
+
while ((boundary = buffer.indexOf("\n\n")) >= 0) {
|
|
60
|
+
const block = buffer.slice(0, boundary);
|
|
61
|
+
buffer = buffer.slice(boundary + 2);
|
|
62
|
+
const data = block.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).join("\n");
|
|
63
|
+
if (data) events.push(JSON.parse(data));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return events;
|
|
67
|
+
} finally {
|
|
68
|
+
clearTimeout(timeout);
|
|
69
|
+
controller.abort();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function pidIsAlive(pid) {
|
|
74
|
+
if (!Number.isInteger(pid) || pid < 1) return false;
|
|
75
|
+
try {
|
|
76
|
+
process.kill(pid, 0);
|
|
77
|
+
return true;
|
|
78
|
+
} catch (error) {
|
|
79
|
+
return error?.code === "EPERM";
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function spawnServer({ cwd, env, output }) {
|
|
84
|
+
const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
|
|
85
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
86
|
+
env,
|
|
87
|
+
});
|
|
88
|
+
child.stdout.on("data", (chunk) => output.push(String(chunk)));
|
|
89
|
+
child.stderr.on("data", (chunk) => output.push(String(chunk)));
|
|
90
|
+
return child;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function health() {
|
|
94
|
+
const response = await request("/api/health", { timeoutMs: 1_000 });
|
|
95
|
+
if (response.status !== 200 || response.body?.ok !== true) return null;
|
|
96
|
+
return response.body;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function tabs() {
|
|
100
|
+
const response = await request("/api/tabs");
|
|
101
|
+
assert.equal(response.status, 200, "tabs endpoint should be available");
|
|
102
|
+
return response.body?.data?.tabs || [];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function readLog(logFile) {
|
|
106
|
+
const text = await readFile(logFile, "utf8").catch(() => "");
|
|
107
|
+
return text.split("\n").filter(Boolean).map((line) => JSON.parse(line));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const work = await mkdtemp(path.join(tmpdir(), "pi-webui-continuity-harness-"));
|
|
111
|
+
const agentDir = path.join(work, "agent");
|
|
112
|
+
const cwd = path.join(work, "cwd");
|
|
113
|
+
const settingsFile = path.join(work, "settings.json");
|
|
114
|
+
const sessionFile = path.join(work, "fixture-session.jsonl");
|
|
115
|
+
const logFile = path.join(work, "fake-pi.jsonl");
|
|
116
|
+
const output = [];
|
|
117
|
+
const environment = {
|
|
118
|
+
...process.env,
|
|
119
|
+
PI_CODING_AGENT_DIR: agentDir,
|
|
120
|
+
PI_WEBUI_SETTINGS_FILE: settingsFile,
|
|
121
|
+
PI_WEBUI_RPC_SUPERVISOR: "1",
|
|
122
|
+
FAKE_PI_CONTINUITY_MODE: "1",
|
|
123
|
+
FAKE_PI_CONTINUITY_SESSION_FILE: sessionFile,
|
|
124
|
+
FAKE_PI_LOG_FILE: logFile,
|
|
125
|
+
};
|
|
126
|
+
const paths = await supervisorPaths({ agentDir, port });
|
|
127
|
+
let initialServer;
|
|
128
|
+
let manualServer;
|
|
129
|
+
let observedPiPid;
|
|
130
|
+
let observedTabId;
|
|
131
|
+
|
|
132
|
+
try {
|
|
133
|
+
await writeFile(settingsFile, "{}\n");
|
|
134
|
+
await mkdir(cwd, { recursive: true });
|
|
135
|
+
initialServer = spawnServer({ cwd, env: environment, output });
|
|
136
|
+
|
|
137
|
+
const initialHealth = await waitFor("initial supervised server health", health);
|
|
138
|
+
assert.equal(initialHealth.rpcSupervisor?.enabled, true, "harness must opt into the supervisor");
|
|
139
|
+
assert.equal(initialHealth.rpcSupervisor?.attached, true, "server must attach to the supervisor");
|
|
140
|
+
const initialWebuiPid = initialHealth.webuiPid;
|
|
141
|
+
const initialTabs = await tabs();
|
|
142
|
+
assert.equal(initialTabs.length, 1, "isolated server startup should create one tab");
|
|
143
|
+
const initialTab = initialTabs[0];
|
|
144
|
+
observedTabId = initialTab.id;
|
|
145
|
+
observedPiPid = initialTab.pid;
|
|
146
|
+
assert.ok(Number.isInteger(observedPiPid) && observedPiPid > 0, "initial tab must expose its fake Pi PID");
|
|
147
|
+
assert.equal(initialTab.cwd, cwd, "tab metadata must retain the isolated cwd");
|
|
148
|
+
assert.equal(initialTab.sessionFile, sessionFile, "fixture session metadata must be captured before restart");
|
|
149
|
+
|
|
150
|
+
const controlledPrompt = await request("/api/prompt", { method: "POST", body: { tab: observedTabId, message: streamPrompt } });
|
|
151
|
+
assert.equal(controlledPrompt.status, 200, "controlled-restart prompt must be accepted once");
|
|
152
|
+
const preRestartTab = (await tabs())[0];
|
|
153
|
+
const restart = await request("/api/restart", { method: "POST" });
|
|
154
|
+
assert.equal(restart.status, 200, "controlled restart must be accepted");
|
|
155
|
+
assert.equal(restart.body?.webuiPid, initialWebuiPid, "restart response must identify the retiring HTTP server");
|
|
156
|
+
|
|
157
|
+
const restartedHealth = await waitFor("controlled-restart replacement health", async () => {
|
|
158
|
+
const value = await health();
|
|
159
|
+
return value && value.webuiPid !== initialWebuiPid ? value : null;
|
|
160
|
+
}, { timeoutMs: 15_000 });
|
|
161
|
+
const controlledTabs = await tabs();
|
|
162
|
+
assert.equal(controlledTabs.length, 1, "controlled restart must hydrate instead of spawning duplicate tabs");
|
|
163
|
+
assert.deepEqual(
|
|
164
|
+
controlledTabs.map((tab) => ({ id: tab.id, pid: tab.pid, cwd: tab.cwd, sessionFile: tab.sessionFile, title: tab.title, index: tab.index })),
|
|
165
|
+
[{ id: preRestartTab.id, pid: observedPiPid, cwd, sessionFile, title: preRestartTab.title, index: preRestartTab.index }],
|
|
166
|
+
"controlled restart must retain the same managed tab metadata and Pi PID",
|
|
167
|
+
);
|
|
168
|
+
assert.equal(restartedHealth.piPid, observedPiPid, "controlled restart must retain the active Pi process");
|
|
169
|
+
await waitFor("controlled stream completion", async () => {
|
|
170
|
+
const state = await request(`/api/state?tab=${encodeURIComponent(observedTabId)}`);
|
|
171
|
+
return state.body?.data?.isStreaming === false;
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
const abruptPrompt = await request("/api/prompt", { method: "POST", body: { tab: observedTabId, message: streamPrompt } });
|
|
175
|
+
assert.equal(abruptPrompt.status, 200, "abrupt-loss prompt must be accepted once");
|
|
176
|
+
const abruptWebuiPid = restartedHealth.webuiPid;
|
|
177
|
+
process.kill(abruptWebuiPid, "SIGKILL");
|
|
178
|
+
await waitFor("abrupt HTTP server exit", () => !pidIsAlive(abruptWebuiPid));
|
|
179
|
+
await delay(1_500);
|
|
180
|
+
|
|
181
|
+
const state = await readSupervisorState(paths);
|
|
182
|
+
assert.ok(state, "supervisor state must remain available after HTTP SIGKILL");
|
|
183
|
+
|
|
184
|
+
manualServer = spawnServer({ cwd, env: environment, output });
|
|
185
|
+
const manualHealth = await waitFor("manual same-port replacement health", health, { timeoutMs: 15_000 });
|
|
186
|
+
assert.notEqual(manualHealth.webuiPid, abruptWebuiPid, "manual relaunch must use a new HTTP server process");
|
|
187
|
+
assert.equal(manualHealth.piPid, observedPiPid, "manual same-port relaunch must attach to the original Pi process");
|
|
188
|
+
const manualTabs = await tabs();
|
|
189
|
+
assert.equal(manualTabs.length, 1, "manual relaunch must not duplicate the supervised tab");
|
|
190
|
+
assert.deepEqual(
|
|
191
|
+
manualTabs.map((tab) => ({ id: tab.id, pid: tab.pid, cwd: tab.cwd, sessionFile: tab.sessionFile, title: tab.title, index: tab.index })),
|
|
192
|
+
[{ id: preRestartTab.id, pid: observedPiPid, cwd, sessionFile, title: preRestartTab.title, index: preRestartTab.index }],
|
|
193
|
+
"manual relaunch must retain tab ID, PID, and persisted metadata",
|
|
194
|
+
);
|
|
195
|
+
|
|
196
|
+
const reconnectEvents = await initialSseEvents(observedTabId);
|
|
197
|
+
const connectedEvent = reconnectEvents.find((event) => event.type === "webui_connected");
|
|
198
|
+
const replayGapEvent = reconnectEvents.find((event) => event.type === "webui_supervisor_replay_gap");
|
|
199
|
+
assert.equal(connectedEvent?.supervisorReplayGap, true, "actual replacement server must report a truthful cursor-less replay gap");
|
|
200
|
+
assert.equal(Object.hasOwn(connectedEvent || {}, "supervisorGap"), false, "replacement server must use the browser's canonical replay-gap field");
|
|
201
|
+
assert.equal(replayGapEvent?.supervisorReplayGap, true, "replacement SSE must explicitly warn that authoritative replay recovery ran");
|
|
202
|
+
|
|
203
|
+
const recoveredState = await request(`/api/state?tab=${encodeURIComponent(observedTabId)}`);
|
|
204
|
+
assert.equal(recoveredState.status, 200, "replacement server must query authoritative Pi state");
|
|
205
|
+
assert.equal(recoveredState.body?.data?.isStreaming, false, "replacement server must observe the completed downtime turn");
|
|
206
|
+
const recoveredMessages = await request(`/api/messages?tab=${encodeURIComponent(observedTabId)}`);
|
|
207
|
+
assert.equal(recoveredMessages.status, 200, "replacement server must expose the authoritative transcript");
|
|
208
|
+
const recoveredTranscript = recoveredMessages.body?.data?.messages || [];
|
|
209
|
+
assert.equal(recoveredTranscript.filter((message) => message?.role === "user" && message.content === streamPrompt).length, 2, "both accepted continuity prompts must appear once in the transcript");
|
|
210
|
+
assert.equal(recoveredTranscript.filter((message) => message?.role === "assistant" && message.content?.[0]?.text === "continuity stream complete").length, 2, "the completed controlled and downtime outputs must each appear once authoritatively");
|
|
211
|
+
const replacementStatus = await request("/api/webui-status?detailed=true&events=200");
|
|
212
|
+
const replayedEventTypes = (replacementStatus.body?.data?.events || []).map((event) => event.type);
|
|
213
|
+
const lastAgentStart = replayedEventTypes.lastIndexOf("agent_start");
|
|
214
|
+
const followingAgentEnd = replayedEventTypes.indexOf("agent_end", lastAgentStart);
|
|
215
|
+
assert.deepEqual(replayedEventTypes.slice(lastAgentStart, followingAgentEnd + 1), ["agent_start", "message_start", "message_update", "message_end", "agent_end"], "replacement server must apply the ordered downtime event stream before authoritative refresh events");
|
|
216
|
+
|
|
217
|
+
const commandEntries = (await readLog(logFile)).filter((entry) => entry.direction === "command" && entry.message === streamPrompt);
|
|
218
|
+
assert.equal(commandEntries.length, 2, "each accepted continuity prompt must reach fake Pi exactly once despite server loss");
|
|
219
|
+
assert.equal(new Set(commandEntries.map((entry) => entry.type)).size, 1, "continuity prompt command records must remain identifiable");
|
|
220
|
+
assert.equal(commandEntries[0].type, "prompt");
|
|
221
|
+
|
|
222
|
+
const stopped = await request("/api/shutdown", { method: "POST" });
|
|
223
|
+
assert.equal(stopped.status, 200, "explicit shutdown must be accepted");
|
|
224
|
+
await waitFor("explicit HTTP shutdown", () => !pidIsAlive(manualHealth.webuiPid));
|
|
225
|
+
await waitFor("explicit Pi cleanup", () => !pidIsAlive(observedPiPid), { timeoutMs: 8_000 });
|
|
226
|
+
await waitFor("supervisor state cleanup", async () => {
|
|
227
|
+
const remainingState = await readSupervisorState(paths);
|
|
228
|
+
if (!remainingState) return true;
|
|
229
|
+
if (!pidIsAlive(remainingState.pid)) throw new Error(`dead supervisor ${remainingState.pid} left stale state`);
|
|
230
|
+
return false;
|
|
231
|
+
}, { timeoutMs: 12_000 });
|
|
232
|
+
const exitEntries = (await readLog(logFile)).filter((entry) => entry.direction === "exit" && entry.pid === observedPiPid);
|
|
233
|
+
assert.ok(exitEntries.some((entry) => entry.signal === "SIGTERM"), "explicit shutdown must produce the fake-Pi termination marker");
|
|
234
|
+
console.log(`durable-rpc-supervisor-harness.test.mjs passed (Pi PID ${observedPiPid}; tab ${observedTabId})`);
|
|
235
|
+
} finally {
|
|
236
|
+
const liveServer = manualServer?.exitCode === null ? manualServer : initialServer?.exitCode === null ? initialServer : null;
|
|
237
|
+
if (liveServer) {
|
|
238
|
+
try { await request("/api/shutdown", { method: "POST", timeoutMs: 1_000 }); } catch {
|
|
239
|
+
try { liveServer.kill("SIGKILL"); } catch {}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const remaining = await readSupervisorState(paths).catch(() => null);
|
|
243
|
+
if (remaining) {
|
|
244
|
+
const cleanupClient = await connectRpcSupervisor({ agentDir, port, controllerId: "durable-harness-cleanup", connectTimeoutMs: 1_000 }).catch(() => null);
|
|
245
|
+
if (cleanupClient) {
|
|
246
|
+
try { await cleanupClient.shutdown(); } catch {}
|
|
247
|
+
cleanupClient.close();
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
await delay(150);
|
|
251
|
+
await rm(work, { recursive: true, force: true });
|
|
252
|
+
}
|
|
@@ -149,10 +149,10 @@ assert.match(app, /fastOutputModeSelect\?\.addEventListener\("change", \(\) => \
|
|
|
149
149
|
assert.match(app, /refreshSidebarOutputMode\(\)\.catch[\s\S]*?initializeTabs\(\)/, "sidebar output mode should initialize with the WebUI");
|
|
150
150
|
|
|
151
151
|
assert.match(helper, /FAST_OUTPUT_FLUSH_INTERVAL_MS = 100/, "the live scheduler should retain the exact 100 ms sustained-output bound");
|
|
152
|
-
assert.match(worker, /pi-webui-pwa-
|
|
152
|
+
assert.match(worker, /pi-webui-pwa-v\d+[\s\S]*?"\/fast-output-live\.mjs"/, "PWA cache identity and app shell should include the compact helper");
|
|
153
153
|
assert.match(html, /<label for="fastOutputModeSelect">Fast mode \(Experimental\)<\/label>/, "the sidebar should mark fast mode as experimental");
|
|
154
154
|
assert.match(html, /Markdown final output; live thinking expanded; stored thinking grouped and collapsed/, "the sidebar should distinguish live and stored thinking defaults");
|
|
155
|
-
assert.match(html,
|
|
155
|
+
assert.match(html, /id="webuiBootLoader"[^>]*data-app-src="\/app\.js\?v=91"/, "the guarded PWA entry point should cache-bust browser wiring");
|
|
156
156
|
assert.match(JSON.parse(packageRaw).scripts.check, /node --check public\/fast-output-live\.mjs/, "package checks should parse the compact helper");
|
|
157
157
|
|
|
158
158
|
const events = createFastModeOutputEvents();
|
|
File without changes
|