@firstpick/pi-package-webui 0.10.6 → 0.10.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DEVELOPMENT.md +95 -15
- package/README.md +1 -1
- package/TECHNICAL.md +6 -4
- package/bin/pi-webui-launcher.mjs +6 -3
- package/bin/pi-webui-native-update-guardian.mjs +37 -0
- package/bin/pi-webui-native-update-runner.mjs +148 -0
- package/bin/pi-webui-rpc-supervisor.mjs +85 -10
- package/bin/pi-webui-update-context.mjs +83 -0
- package/bin/pi-webui.mjs +537 -339
- package/lib/component-update-state.mjs +4 -4
- package/lib/rpc-supervisor-client.mjs +4 -0
- package/lib/rpc-supervisor-protocol.mjs +17 -4
- package/lib/update/coordination.mjs +207 -0
- package/lib/update/discovery.mjs +58 -0
- package/lib/update/migration.mjs +115 -0
- package/lib/update/native-jobs.mjs +215 -0
- package/lib/update/native-targets.mjs +81 -0
- package/lib/update/path-pi.mjs +76 -0
- package/lib/update/supervisor.mjs +50 -29
- package/lib/update/verification.mjs +18 -0
- package/lib/update-commands.mjs +17 -27
- package/package.json +3 -3
- package/public/app.js +170 -201
- package/public/index.html +5 -3
- package/public/styles.css +29 -1
- package/tests/browser/control-deck-component-updates.spec.mjs +90 -141
- package/tests/browser/update-reconnect.spec.mjs +37 -1
- package/tests/component-update-api-static.test.mjs +13 -11
- package/tests/control-deck-component-updates-static.test.mjs +25 -25
- package/tests/cwd-footer-reliability-static.test.mjs +4 -1
- package/tests/http-endpoints-harness.test.mjs +32 -9
- package/tests/mobile-static.test.mjs +9 -6
- package/tests/native-update-discovery.test.mjs +69 -0
- package/tests/native-update-lifecycle.test.mjs +90 -0
- package/tests/native-update-shell-survival.test.mjs +68 -0
- package/tests/native-update-verification.test.mjs +17 -0
- package/tests/rpc-supervisor-host.test.mjs +63 -1
- package/tests/rpc-supervisor-protocol.test.mjs +8 -0
- package/tests/run-all.mjs +6 -2
- package/tests/update-api-harness.test.mjs +57 -50
- package/tests/update-commands.test.mjs +29 -15
- package/tests/update-executor-process-tree-harness.test.mjs +84 -1
- package/tests/update-journal-harness.test.mjs +9 -1
- package/tests/update-lock-multiprocess-harness.test.mjs +60 -1
- package/tests/update-owners.test.mjs +32 -0
- package/tests/update-plan.test.mjs +110 -0
- package/tests/update-resolver.test.mjs +36 -0
- package/tests/update-supervisor-harness.test.mjs +74 -1
- package/tests/update-tab-restore-harness.test.mjs +9 -2
- package/bin/pi-webui-update-supervisor.mjs +0 -86
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { discoverNativeJobs, nativeJobBlocksUpdates, publicNativeJob } from "../lib/update/discovery.mjs";
|
|
7
|
+
import { persistSharedJob, sharedUpdateRoot } from "../lib/update/coordination.mjs";
|
|
8
|
+
|
|
9
|
+
const root = await mkdtemp(path.join(tmpdir(), "pi-webui-discovery-"));
|
|
10
|
+
const scope = { agentDir: path.join(root, "agent"), ownerPackageRoot: path.join(root, "package"), ownerBootIdentity: "boot-test" };
|
|
11
|
+
const record = (requested, phase, day, context = {}) => {
|
|
12
|
+
const transactionId = randomUUID();
|
|
13
|
+
return { transactionId, phase, lock: { token: "never-public" },
|
|
14
|
+
plan: { schemaVersion: 2, transactionId, requested, createdAt: `2026-09-${day}T00:00:00.000Z`,
|
|
15
|
+
context: { ...scope, ...context } }, outcome: phase,
|
|
16
|
+
verifiedTargets: [{ id: requested, status: phase === "success" ? "healthy" : "unverified" }] };
|
|
17
|
+
};
|
|
18
|
+
try {
|
|
19
|
+
const previousMode = process.env.NODE_ENV;
|
|
20
|
+
const previousHome = process.env.PI_WEBUI_UPDATE_TEST_HOME;
|
|
21
|
+
try {
|
|
22
|
+
process.env.NODE_ENV = "test";
|
|
23
|
+
process.env.PI_WEBUI_UPDATE_TEST_HOME = path.join(root, "outer-suite");
|
|
24
|
+
const explicitHome = path.join(root, "explicit-fixture");
|
|
25
|
+
const expectedRoot = path.join(explicitHome, process.platform === "win32" ? "AppData/Local/PiWebUI/updates" : ".local/state/pi-webui-updates");
|
|
26
|
+
assert.equal(await sharedUpdateRoot({ home: explicitHome }), expectedRoot,
|
|
27
|
+
"an outer suite's default must not put parent and fixture child in different fence domains");
|
|
28
|
+
} finally {
|
|
29
|
+
if (previousMode === undefined) delete process.env.NODE_ENV; else process.env.NODE_ENV = previousMode;
|
|
30
|
+
if (previousHome === undefined) delete process.env.PI_WEBUI_UPDATE_TEST_HOME; else process.env.PI_WEBUI_UPDATE_TEST_HOME = previousHome;
|
|
31
|
+
}
|
|
32
|
+
assert.deepEqual(await discoverNativeJobs(root, scope), { pi: null, webui: null });
|
|
33
|
+
const completed = record("pi", "success", "20");
|
|
34
|
+
const partial = record("webui", "partial", "21");
|
|
35
|
+
const planned = record("pi", "planned", "23");
|
|
36
|
+
const unrelated = record("webui", "unknown", "23", { agentDir: path.join(root, "another-agent") });
|
|
37
|
+
for (const job of [completed, partial, planned, unrelated]) await persistSharedJob(root, job);
|
|
38
|
+
let found = await discoverNativeJobs(root, scope);
|
|
39
|
+
assert.equal(found.pi.transactionId, completed.transactionId, "unconfirmed previews must not hide a completed job");
|
|
40
|
+
assert.equal(found.webui.transactionId, partial.transactionId, "another agent directory must not contaminate discovery");
|
|
41
|
+
assert.equal(found.webui.phase, "partial", "partial outcomes survive a new browser with no saved job ID");
|
|
42
|
+
assert.equal(JSON.stringify(found).includes("never-public"), false, "fence authorization must never reach HTTP responses");
|
|
43
|
+
assert.equal(nativeJobBlocksUpdates(found.pi), false);
|
|
44
|
+
const interrupted = record("pi", "unknown", "19");
|
|
45
|
+
await persistSharedJob(root, interrupted);
|
|
46
|
+
found = await discoverNativeJobs(root, scope);
|
|
47
|
+
assert.equal(found.pi.transactionId, interrupted.transactionId, "an older unresolved job takes priority over newer terminal results");
|
|
48
|
+
assert.equal(nativeJobBlocksUpdates(found.pi), true);
|
|
49
|
+
for (let index = 0; index < 1025; index++) await persistSharedJob(root, record("pi", "planned", "23"));
|
|
50
|
+
found = await discoverNativeJobs(root, scope);
|
|
51
|
+
assert.equal(found.pi.transactionId, interrupted.transactionId, "canceled previews do not exhaust launched-history discovery");
|
|
52
|
+
const lostOwner = record("webui", "command-complete", "22", { ownerBootIdentity: "old-boot" });
|
|
53
|
+
await persistSharedJob(root, lostOwner);
|
|
54
|
+
found = await discoverNativeJobs(root, scope);
|
|
55
|
+
assert.equal(found.webui.phase, "unknown", "discovery must not authorize another server to restart an old owner's job");
|
|
56
|
+
assert.match(found.webui.error, /original update owner/);
|
|
57
|
+
assert.equal(publicNativeJob({ ...partial, jobDir: "private-capsule", launcherPid: 1 }).jobDir, undefined);
|
|
58
|
+
await assert.rejects(discoverNativeJobs(root, { ...scope, maxRecords: 1 }), /discovery limit/);
|
|
59
|
+
const malformed = path.join(root, "jobs", `${randomUUID()}.json`);
|
|
60
|
+
await writeFile(malformed, "{malformed");
|
|
61
|
+
await assert.rejects(discoverNativeJobs(root, scope), SyntaxError, "unreadable history must fail closed");
|
|
62
|
+
await rm(malformed);
|
|
63
|
+
const directoryRecord = path.join(root, "jobs", `${randomUUID()}.json`);
|
|
64
|
+
await mkdir(directoryRecord);
|
|
65
|
+
await assert.rejects(discoverNativeJobs(root, scope), /linked or exceeds/, "unexpected filesystem types must not be followed");
|
|
66
|
+
} finally {
|
|
67
|
+
await rm(root, { recursive: true, force: true });
|
|
68
|
+
}
|
|
69
|
+
console.log("native-update-discovery.test.mjs passed");
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { createServer } from "node:net";
|
|
4
|
+
import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
9
|
+
|
|
10
|
+
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
11
|
+
const temp = await mkdtemp(path.join(tmpdir(), "pi-webui-native-lifecycle-"));
|
|
12
|
+
const prefix = path.join(temp, "prefix");
|
|
13
|
+
const windows = process.platform === "win32";
|
|
14
|
+
const bin = windows ? prefix : path.join(prefix, "bin");
|
|
15
|
+
const piRoot = path.join(prefix, ...(windows ? [] : ["lib"]), "node_modules", "@earendil-works", "pi-coding-agent");
|
|
16
|
+
const npmRoot = path.join(temp, "npm");
|
|
17
|
+
const cli = path.join(piRoot, "dist", "cli.js");
|
|
18
|
+
const manifest = path.join(piRoot, "package.json");
|
|
19
|
+
const port = await new Promise((resolve) => {
|
|
20
|
+
const server = createServer();
|
|
21
|
+
server.listen(0, "127.0.0.1", () => {
|
|
22
|
+
const chosen = server.address().port;
|
|
23
|
+
server.close(() => resolve(chosen));
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
let child;
|
|
27
|
+
let cleanupSafe = false;
|
|
28
|
+
let output = "";
|
|
29
|
+
const base = `http://127.0.0.1:${port}`;
|
|
30
|
+
const api = (route, body) => fetch(`${base}${route}`, body === undefined ? {} : {
|
|
31
|
+
method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
|
|
32
|
+
});
|
|
33
|
+
try {
|
|
34
|
+
await mkdir(path.join(piRoot, "dist"), { recursive: true });
|
|
35
|
+
await mkdir(bin, { recursive: true });
|
|
36
|
+
await mkdir(path.join(npmRoot, "bin"), { recursive: true });
|
|
37
|
+
await writeFile(manifest, JSON.stringify({ name: "@earendil-works/pi-coding-agent", version: "0.87.1", bin: { pi: "dist/cli.js" } }));
|
|
38
|
+
const fakePi = path.join(packageRoot, "tests", "fixtures", "fake-pi.mjs");
|
|
39
|
+
await writeFile(cli, `import { readFileSync, writeFileSync } from 'node:fs';\nconst manifest = ${JSON.stringify(manifest)};\nconst current = JSON.parse(readFileSync(manifest, 'utf8'));\nif (process.argv.includes('--version')) { console.log(current.version); process.exit(0); }\nif (process.argv.includes('update')) { current.version = '0.87.2'; writeFileSync(manifest, JSON.stringify(current)); process.exit(0); }\nawait import(${JSON.stringify(pathToFileURL(fakePi).href)});\n`);
|
|
40
|
+
if (windows) {
|
|
41
|
+
await writeFile(path.join(bin, "pi.cmd"), `@echo off\r\nnode "%dp0%\\node_modules\\@earendil-works\\pi-coding-agent\\dist\\cli.js" %*\r\n`);
|
|
42
|
+
} else await symlink(cli, path.join(bin, "pi"));
|
|
43
|
+
await writeFile(path.join(npmRoot, "package.json"), JSON.stringify({ name: "npm", bin: { npm: "bin/npm-cli.js" } }));
|
|
44
|
+
await writeFile(path.join(npmRoot, "bin", "npm-cli.js"), `const prefix = ${JSON.stringify(prefix)};\nconst args = process.argv.slice(2).join(' ');\nif (args === 'root -g') console.log(${JSON.stringify(path.join(prefix, ...(windows ? [] : ["lib"]), "node_modules"))});\nelse if (args === 'prefix -g') console.log(prefix);\nelse if (args === 'config get userconfig') console.log(${JSON.stringify(path.join(temp, "user.npmrc"))});\nelse if (args === 'config get globalconfig') console.log(${JSON.stringify(path.join(temp, "global.npmrc"))});\nelse process.exitCode = 2;\n`);
|
|
45
|
+
child = spawn(process.execPath, [path.join(packageRoot, "bin", "pi-webui.mjs"), "--cwd", temp,
|
|
46
|
+
"--host", "127.0.0.1", "--port", String(port), "--pi", cli], {
|
|
47
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
48
|
+
env: { ...process.env, PATH: `${bin}${path.delimiter}${process.env.PATH || ""}`,
|
|
49
|
+
PI_CODING_AGENT_DIR: path.join(temp, "agent"), PI_WEBUI_NPM_BIN: path.join(npmRoot, "bin", "npm-cli.js"),
|
|
50
|
+
PI_WEBUI_UPDATE_TEST_HOME: temp, NODE_ENV: "test", PI_OFFLINE: "1" },
|
|
51
|
+
});
|
|
52
|
+
child.stdout.on("data", (chunk) => { output += chunk; });
|
|
53
|
+
child.stderr.on("data", (chunk) => { output += chunk; });
|
|
54
|
+
for (let i = 0; i < 150; i++) {
|
|
55
|
+
if (child.exitCode !== null) throw new Error(`Fixture server exited: ${output}`);
|
|
56
|
+
try { if ((await api("/api/health")).ok) break; } catch {}
|
|
57
|
+
await delay(100);
|
|
58
|
+
}
|
|
59
|
+
const planned = await api("/api/update/plan", { targets: ["pi"] });
|
|
60
|
+
const planResult = await planned.json();
|
|
61
|
+
assert.equal(planned.status, 201, JSON.stringify(planResult) + output);
|
|
62
|
+
const plan = planResult.data.plan;
|
|
63
|
+
assert.deepEqual(plan.targets.map(({ id }) => id), ["pi"]);
|
|
64
|
+
const applied = await api("/api/update/apply", { transactionId: plan.transactionId, planDigest: plan.digest });
|
|
65
|
+
assert.equal(applied.status, 202, JSON.stringify(await applied.json()) + output);
|
|
66
|
+
let result;
|
|
67
|
+
for (let i = 0; i < 180; i++) {
|
|
68
|
+
result = (await (await api(`/api/update/transactions/${plan.transactionId}`)).json()).data;
|
|
69
|
+
if (["success", "partial", "failed", "unknown"].includes(result.phase)) break;
|
|
70
|
+
await delay(200);
|
|
71
|
+
}
|
|
72
|
+
assert.equal(result.phase, "success", JSON.stringify(result) + output);
|
|
73
|
+
assert.equal(result.receipts[0].status, "changed");
|
|
74
|
+
assert.equal(result.verifiedTargets[0].status, "healthy");
|
|
75
|
+
assert.equal(JSON.parse(await readFile(manifest, "utf8")).version, "0.87.2");
|
|
76
|
+
const state = await api("/api/state");
|
|
77
|
+
assert.equal(state.status, 200, output);
|
|
78
|
+
cleanupSafe = true;
|
|
79
|
+
} finally {
|
|
80
|
+
if (child && child.exitCode === null) {
|
|
81
|
+
try { await api("/api/shutdown", {}); } catch { child.kill("SIGTERM"); }
|
|
82
|
+
await Promise.race([new Promise((resolve) => child.once("exit", resolve)), delay(6_000)]);
|
|
83
|
+
if (child.exitCode === null) child.kill();
|
|
84
|
+
}
|
|
85
|
+
if (cleanupSafe) {
|
|
86
|
+
// Windows may still be closing the detached supervisor's directory handle.
|
|
87
|
+
await rm(temp, { recursive: true, force: true, maxRetries: 30, retryDelay: 150 });
|
|
88
|
+
} else console.error(`Retained failed native lifecycle fixture for inspection: ${temp}`);
|
|
89
|
+
}
|
|
90
|
+
console.log("native-update-lifecycle.test.mjs passed");
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
4
|
+
import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { readUpdateContext } from "../bin/pi-webui-update-context.mjs";
|
|
10
|
+
import { acquireEffectLocks, effectLockForRoot, releaseEffectLocks } from "../lib/update/coordination.mjs";
|
|
11
|
+
|
|
12
|
+
const source = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
13
|
+
const root = await mkdtemp(path.join(tmpdir(), "pi-native-shell-survival-"));
|
|
14
|
+
const transactionId = randomUUID();
|
|
15
|
+
const job = path.join(root, "jobs", transactionId);
|
|
16
|
+
const install = path.join(root, "fake-install");
|
|
17
|
+
const manifest = path.join(install, "package.json");
|
|
18
|
+
const driver = path.join(root, "fake-cli.mjs");
|
|
19
|
+
const sha = (data) => createHash("sha256").update(data).digest("hex");
|
|
20
|
+
let safeCleanup = false;
|
|
21
|
+
let lock;
|
|
22
|
+
try {
|
|
23
|
+
await mkdir(job, { recursive: true });
|
|
24
|
+
await mkdir(install);
|
|
25
|
+
await writeFile(manifest, JSON.stringify({ name: "fixture-package", version: "1.0.0" }));
|
|
26
|
+
await writeFile(driver, `import { readFile, writeFile } from 'node:fs/promises';\nimport { setTimeout as delay } from 'node:timers/promises';\nawait delay(900);\nconst file = ${JSON.stringify(manifest)};\nconst data = JSON.parse(await readFile(file, 'utf8'));\ndata.version = '1.1.0';\nawait writeFile(file, JSON.stringify(data));\n`);
|
|
27
|
+
await copyFile(path.join(source, "bin", "pi-webui-native-update-runner.mjs"), path.join(job, "runner.mjs"));
|
|
28
|
+
await copyFile(path.join(source, "bin", "pi-webui-update-context.mjs"), path.join(job, "pi-webui-update-context.mjs"));
|
|
29
|
+
await copyFile(path.join(source, "bin", "pi-webui-native-update-guardian.mjs"), path.join(job, "guardian.mjs"));
|
|
30
|
+
const env = { ...process.env, PI_CODING_AGENT_DIR: root };
|
|
31
|
+
const bindings = await readUpdateContext({ env });
|
|
32
|
+
await writeFile(path.join(job, "intent.json"), JSON.stringify({ transactionId, cwd: root,
|
|
33
|
+
...bindings, nodeDigest: sha(await readFile(process.execPath)), targets: [{ id: "pi", packageName: "fixture-package",
|
|
34
|
+
beforeVersion: "1.0.0", manifestPath: manifest, driver, driverDigest: sha(await readFile(driver)),
|
|
35
|
+
command: { command: process.execPath, args: [driver, "update"] } }] }));
|
|
36
|
+
lock = await acquireEffectLocks(root, [install], transactionId);
|
|
37
|
+
const windows = process.platform === "win32";
|
|
38
|
+
const shell = windows ? path.join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe") : "/bin/bash";
|
|
39
|
+
const args = windows ? [path.join(job, "guardian.mjs")]
|
|
40
|
+
: ["--noprofile", "--norc", "-c", 'exec "$PI_WEBUI_UPDATE_NODE" "$PI_WEBUI_UPDATE_RUNNER" "$PI_WEBUI_UPDATE_JOB"'];
|
|
41
|
+
const executable = windows ? process.execPath : shell;
|
|
42
|
+
const initiator = spawn(process.execPath, ["-e", `const { spawn } = require('node:child_process');\nconst child = spawn(${JSON.stringify(executable)}, ${JSON.stringify(args)}, { cwd: ${JSON.stringify(root)}, env: process.env, detached: true, windowsHide: true, stdio: 'ignore' });\nchild.once('spawn', () => { child.unref(); process.exit(88); });\nchild.once('error', () => process.exit(89));`], {
|
|
43
|
+
cwd: root, env: { ...env, PI_WEBUI_UPDATE_NODE: process.execPath,
|
|
44
|
+
PI_WEBUI_UPDATE_RUNNER: path.join(job, "runner.mjs"), PI_WEBUI_UPDATE_JOB: job,
|
|
45
|
+
PI_WEBUI_UPDATE_SHELL: shell, PI_WEBUI_UPDATE_CWD: root,
|
|
46
|
+
PI_WEBUI_UPDATE_PATHEXT: env.PATHEXT || env.PathExt || "" }, stdio: "ignore",
|
|
47
|
+
});
|
|
48
|
+
const exit = await Promise.race([new Promise((resolve) => initiator.once("exit", resolve)), delay(8_000, "timeout")]);
|
|
49
|
+
assert.equal(exit, 88, "the initiating server exits abruptly after its background shell starts");
|
|
50
|
+
assert.ok(await effectLockForRoot(root, install), "the effect fence remains after owner exit");
|
|
51
|
+
let complete;
|
|
52
|
+
for (let attempt = 0; attempt < 80; attempt++) {
|
|
53
|
+
try { complete = JSON.parse(await readFile(path.join(job, "complete.json"), "utf8")); break; }
|
|
54
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
55
|
+
await delay(100);
|
|
56
|
+
}
|
|
57
|
+
assert.equal(complete?.transactionId, transactionId, "runner continues independently and durably completes");
|
|
58
|
+
const receipt = JSON.parse(await readFile(path.join(job, "0.receipt.json"), "utf8"));
|
|
59
|
+
assert.equal(receipt.status, "changed", JSON.stringify(receipt));
|
|
60
|
+
assert.equal(JSON.parse(await readFile(manifest, "utf8")).version, "1.1.0");
|
|
61
|
+
assert.ok(await effectLockForRoot(root, install), "completion alone does not silently discard exclusion");
|
|
62
|
+
await releaseEffectLocks(lock, { completionVerified: true });
|
|
63
|
+
safeCleanup = true;
|
|
64
|
+
} finally {
|
|
65
|
+
if (safeCleanup) await rm(root, { recursive: true, force: true, maxRetries: 30, retryDelay: 150 });
|
|
66
|
+
else console.error(`Retained interrupted shell-survival fixture: ${root}`);
|
|
67
|
+
}
|
|
68
|
+
console.log("native-update-shell-survival.test.mjs passed");
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { assertRestoredPiState, nativeUpdateOutcome } from "../lib/update/verification.mjs";
|
|
4
|
+
|
|
5
|
+
for (const [statuses, expected] of [
|
|
6
|
+
[["healthy"], "success"], [["healthy", "unchanged"], "success"],
|
|
7
|
+
[["unchanged", "unchanged"], "unchanged"], [["failed"], "failed"],
|
|
8
|
+
[["healthy", "failed"], "partial"], [["healthy", "unverified"], "partial"],
|
|
9
|
+
]) {
|
|
10
|
+
assert.equal(nativeUpdateOutcome(statuses.map((status) => ({ status }))), expected);
|
|
11
|
+
}
|
|
12
|
+
const sessionFile = path.resolve("fixture", "session.jsonl");
|
|
13
|
+
assert.doesNotThrow(() => assertRestoredPiState({ success: true, data: { sessionFile } }, sessionFile));
|
|
14
|
+
assert.throws(() => assertRestoredPiState({ success: true, data: { sessionFile: "wrong-session.jsonl" } }, sessionFile), /expected session/);
|
|
15
|
+
assert.throws(() => assertRestoredPiState({ success: true, data: { rpcRunning: false, sessionFile } }, sessionFile), /healthy RPC/);
|
|
16
|
+
assert.throws(() => assertRestoredPiState({ success: false, error: "spawned but failed" }, sessionFile), /healthy RPC/);
|
|
17
|
+
console.log("native-update-verification.test.mjs passed");
|
|
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
|
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
3
|
import { createConnection, createServer } from "node:net";
|
|
4
4
|
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { acquireEffectLocks, persistSharedJob, releaseEffectLocks, sharedUpdateRoot } from "../lib/update/coordination.mjs";
|
|
5
6
|
import { tmpdir } from "node:os";
|
|
6
7
|
import path from "node:path";
|
|
7
8
|
import { fileURLToPath } from "node:url";
|
|
@@ -26,6 +27,8 @@ import {
|
|
|
26
27
|
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
27
28
|
const fakePi = path.join(root, "tests", "fixtures", "fake-pi.mjs");
|
|
28
29
|
const work = await mkdtemp(path.join(tmpdir(), "pi-webui-rpc-supervisor-host-"));
|
|
30
|
+
const effectRoot = path.join(work, "effect");
|
|
31
|
+
await mkdir(effectRoot);
|
|
29
32
|
const agentDir = path.join(work, "agent");
|
|
30
33
|
const port = 35000 + Math.floor(Math.random() * 15000);
|
|
31
34
|
const logFile = path.join(work, "commands.jsonl");
|
|
@@ -129,6 +132,9 @@ try {
|
|
|
129
132
|
...process.env,
|
|
130
133
|
FAKE_PI_LOG_FILE: logFile,
|
|
131
134
|
RAW_PI_LOG: rawLogFile,
|
|
135
|
+
NODE_ENV: "test",
|
|
136
|
+
PI_WEBUI_UPDATE_TEST_HOME: work,
|
|
137
|
+
PI_WEBUI_UPDATE_EFFECT_ROOTS: JSON.stringify([effectRoot]),
|
|
132
138
|
PI_WEBUI_RECOVERY_URL: `http://127.0.0.1:${port}/api/recovery/plan`,
|
|
133
139
|
PI_WEBUI_RECOVERY_TOKEN: "server-ephemeral-recovery-token",
|
|
134
140
|
},
|
|
@@ -301,6 +307,47 @@ try {
|
|
|
301
307
|
assert.equal(state.tabs.length, 2);
|
|
302
308
|
assert.equal(state.tabs.find((tab) => tab.id === "tab-1").metadata.apiToken, undefined, "private metadata fields must not reach the state snapshot");
|
|
303
309
|
|
|
310
|
+
await client.command("tab-1", { type: "get_state" }, { requestId: "update-idle-state" });
|
|
311
|
+
const updateRoot = await sharedUpdateRoot({ home: work });
|
|
312
|
+
const updateLock = await acquireEffectLocks(updateRoot, [effectRoot], "verified-job");
|
|
313
|
+
const originalChild = { command: process.execPath, args: [fakePi], cwd: work };
|
|
314
|
+
const updatedMetadata = { title: "One", index: 0, cwd: work, sessionFile: path.join(work, "one.jsonl") };
|
|
315
|
+
const restart = { transactionId: "verified-job", lockToken: updateLock.token, effectRoot, nonce: "once-only" };
|
|
316
|
+
await assert.rejects(client.command("tab-1", { type: "prompt", message: "must not race" }), /fenced/i);
|
|
317
|
+
await assert.rejects(client.replaceTabUnderUpdate({ tabId: "tab-1", metadata: updatedMetadata, child: originalChild, restart }), /durable healthy/i);
|
|
318
|
+
const updateJobDir = path.join(updateRoot, "jobs", restart.transactionId);
|
|
319
|
+
await mkdir(path.join(updateJobDir, "restarts"), { recursive: true });
|
|
320
|
+
await writeFile(path.join(updateJobDir, "complete.json"), JSON.stringify({ transactionId: restart.transactionId, receipts: [{ id: "pi", status: "changed" }] }));
|
|
321
|
+
await persistSharedJob(updateRoot, { transactionId: restart.transactionId, phase: "restart-authorized", lock: updateLock,
|
|
322
|
+
jobDir: updateJobDir, verifiedTargets: [{ id: "pi", effectRoot, status: "healthy" }] });
|
|
323
|
+
const requestDigest = createHash("sha256").update(JSON.stringify({ tabId: "tab-1", metadata: updatedMetadata, child: originalChild })).digest("hex");
|
|
324
|
+
await writeFile(path.join(updateJobDir, "restarts", `${restart.nonce}.json`), JSON.stringify({ tabId: "tab-1", transactionId: restart.transactionId,
|
|
325
|
+
lockToken: updateLock.token, effectRoot, requestDigest }));
|
|
326
|
+
const restarted = await client.replaceTabUnderUpdate({ tabId: "tab-1", metadata: updatedMetadata, child: originalChild, restart }, { requestId: "one-restart" });
|
|
327
|
+
const deduped = await client.replaceTabUnderUpdate({ tabId: "tab-1", metadata: updatedMetadata, child: originalChild, restart }, { requestId: "one-restart" });
|
|
328
|
+
assert.equal(deduped.pid, restarted.pid, "deduplicated transport request must not launch another child");
|
|
329
|
+
await assert.rejects(client.replaceTabUnderUpdate({ tabId: "tab-1", metadata: updatedMetadata, child: originalChild, restart }, { requestId: "replayed-restart" }), /ENOENT|already used/i);
|
|
330
|
+
await writeFile(path.join(updateJobDir, "restarts", "wrong-tab.json"), JSON.stringify({ tabId: "raw-tab", transactionId: restart.transactionId,
|
|
331
|
+
lockToken: updateLock.token, effectRoot, requestDigest }));
|
|
332
|
+
await assert.rejects(client.replaceTabUnderUpdate({ tabId: "tab-1", metadata: updatedMetadata, child: originalChild, restart: { ...restart, nonce: "wrong-tab" } }), /authorization/i);
|
|
333
|
+
await releaseEffectLocks(updateLock, { completionVerified: true });
|
|
334
|
+
const dependencyLock = await acquireEffectLocks(updateRoot, [effectRoot], "webui-dependency-job");
|
|
335
|
+
const dependencyJobDir = path.join(updateRoot, "jobs", dependencyLock.transactionId);
|
|
336
|
+
await mkdir(path.join(dependencyJobDir, "restarts"), { recursive: true });
|
|
337
|
+
await writeFile(path.join(dependencyJobDir, "complete.json"), JSON.stringify({ transactionId: dependencyLock.transactionId,
|
|
338
|
+
receipts: [{ id: "webui:npm-global", status: "unchanged" }] }));
|
|
339
|
+
await persistSharedJob(updateRoot, { transactionId: dependencyLock.transactionId, phase: "restart-authorized", lock: dependencyLock,
|
|
340
|
+
jobDir: dependencyJobDir, verifiedTargets: [{ id: "webui:npm-global", effectRoot, status: "healthy", piChanged: true }] });
|
|
341
|
+
const dependencyRestart = { transactionId: dependencyLock.transactionId, lockToken: dependencyLock.token,
|
|
342
|
+
effectRoot, nonce: "webui-dependency-pi-reload" };
|
|
343
|
+
await writeFile(path.join(dependencyJobDir, "restarts", `${dependencyRestart.nonce}.json`), JSON.stringify({ tabId: "tab-1",
|
|
344
|
+
transactionId: dependencyRestart.transactionId, lockToken: dependencyRestart.lockToken, effectRoot,
|
|
345
|
+
requestDigest: createHash("sha256").update(JSON.stringify({ tabId: "tab-1", metadata: updatedMetadata, child: originalChild })).digest("hex") }));
|
|
346
|
+
const dependencyReload = await client.replaceTabUnderUpdate({ tabId: "tab-1", metadata: updatedMetadata, child: originalChild,
|
|
347
|
+
restart: dependencyRestart });
|
|
348
|
+
assert.notEqual(dependencyReload.pid, restarted.pid, "verified bundled Pi dependency changes must reload owned tabs despite unchanged WebUI version");
|
|
349
|
+
await releaseEffectLocks(dependencyLock, { completionVerified: true });
|
|
350
|
+
|
|
304
351
|
const failedReplacementCwd = path.join(work, "failed-replacement-cwd");
|
|
305
352
|
await mkdir(failedReplacementCwd);
|
|
306
353
|
await assert.rejects(
|
|
@@ -426,9 +473,24 @@ try {
|
|
|
426
473
|
await delay(20);
|
|
427
474
|
await closeServer(attachTimeoutServer);
|
|
428
475
|
console.log("rpc-supervisor-host.test.mjs passed");
|
|
476
|
+
} catch (error) {
|
|
477
|
+
console.error("RPC supervisor fixture failed before shutdown:", error);
|
|
478
|
+
throw error;
|
|
429
479
|
} finally {
|
|
480
|
+
// A failed assertion must not strand the detached fixture owner and mask the
|
|
481
|
+
// original failure with Windows EBUSY during temporary-directory removal.
|
|
482
|
+
for (const owner of [replayClient, replacement, client]) {
|
|
483
|
+
if (!owner?.isConnected()) continue;
|
|
484
|
+
try { await owner.shutdown(); break; } catch { /* Another controller may own this fixture. */ }
|
|
485
|
+
}
|
|
430
486
|
replayClient?.close();
|
|
431
487
|
replacement?.close();
|
|
432
488
|
client?.close();
|
|
433
|
-
|
|
489
|
+
for (let attempt = 0; attempt < 25; attempt++) {
|
|
490
|
+
try { await rm(work, { recursive: true, force: true }); break; }
|
|
491
|
+
catch (error) {
|
|
492
|
+
if (error.code !== "EBUSY" || attempt === 24) throw error;
|
|
493
|
+
await delay(200);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
434
496
|
}
|
|
@@ -86,6 +86,14 @@ assert.throws(
|
|
|
86
86
|
assert.deepEqual(sanitizeSupervisorData({ password: "no", nested: { Authorization: "no", safe: true } }), { nested: { safe: true } });
|
|
87
87
|
assert.throws(() => validateClientFrame({ type: "command", requestId: "x", tabId: "t", command: { type: "prompt" }, unexpected: true }), RpcSupervisorProtocolError);
|
|
88
88
|
assert.throws(() => validateClientFrame({ type: "create", requestId: "x", tabId: "t", metadata: {}, child: { command: "pi", args: [], cwd: "/tmp", env: {} } }), RpcSupervisorProtocolError);
|
|
89
|
+
const updateRestart = { transactionId: "job-1", lockToken: "fence-1", effectRoot: "/global", nonce: "once-1" };
|
|
90
|
+
const restartFrame = validateClientFrame({ type: "replace_update", requestId: "restart-request", tabId: "tab-1",
|
|
91
|
+
metadata: { title: "Restored" }, child: { command: "pi", args: [], cwd: "/tmp" }, restart: updateRestart });
|
|
92
|
+
assert.deepEqual(restartFrame.restart, updateRestart);
|
|
93
|
+
assert.throws(() => validateClientFrame({ type: "replace_update", requestId: "r", tabId: "t", metadata: {},
|
|
94
|
+
child: { command: "pi", args: [], cwd: "/tmp" }, restart: { ...updateRestart, bypass: true } }), /unsupported field/);
|
|
95
|
+
assert.throws(() => validateClientFrame({ type: "replace", requestId: "r", tabId: "t", metadata: {},
|
|
96
|
+
child: { command: "pi", args: [], cwd: "/tmp" }, restart: updateRestart }), /only valid/);
|
|
89
97
|
assert.throws(() => encodeFrame({ value: "x".repeat(RPC_SUPERVISOR_MAX_FRAME_BYTES) }), RpcSupervisorProtocolError);
|
|
90
98
|
|
|
91
99
|
const frames = [];
|
package/tests/run-all.mjs
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
|
-
import { readdir } from "node:fs/promises";
|
|
2
|
+
import { mkdtemp, readdir } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
3
4
|
import { dirname, join } from "node:path";
|
|
4
5
|
import { fileURLToPath } from "node:url";
|
|
5
6
|
|
|
6
7
|
const testsDir = dirname(fileURLToPath(import.meta.url));
|
|
7
8
|
const files = (await readdir(testsDir)).filter((name) => name.endsWith(".test.mjs")).sort();
|
|
9
|
+
// Every test child (and any WebUI it launches) inherits a disposable update
|
|
10
|
+
// coordination domain. Retain ambiguous detached-job artifacts after a failure.
|
|
11
|
+
const coordinationHome = await mkdtemp(join(tmpdir(), "pi-webui-test-coordination-"));
|
|
8
12
|
|
|
9
13
|
const failures = [];
|
|
10
14
|
for (const file of files) {
|
|
11
15
|
const result = spawnSync(process.execPath, [join(testsDir, file)], {
|
|
12
16
|
stdio: "inherit",
|
|
13
|
-
env: { ...process.env, PI_WEBUI_RPC_SUPERVISOR: "0" },
|
|
17
|
+
env: { ...process.env, NODE_ENV: "test", PI_WEBUI_UPDATE_TEST_HOME: coordinationHome, PI_WEBUI_RPC_SUPERVISOR: "0" },
|
|
14
18
|
});
|
|
15
19
|
if (result.status !== 0) failures.push(`${file} (exit ${result.status ?? "signal"})`);
|
|
16
20
|
}
|
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
3
4
|
import { createServer as createHttpServer } from "node:http";
|
|
4
5
|
import { createServer as createNetServer } from "node:net";
|
|
5
|
-
import { mkdtemp, readFile,
|
|
6
|
+
import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises";
|
|
7
|
+
import { persistSharedJob } from "../lib/update/coordination.mjs";
|
|
6
8
|
import { tmpdir } from "node:os";
|
|
7
9
|
import path from "node:path";
|
|
8
10
|
import { setTimeout as delay } from "node:timers/promises";
|
|
9
11
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
10
12
|
import { validateUpdateApplyRequest, validateUpdatePlanRequest } from "../lib/component-update-state.mjs";
|
|
11
|
-
import { exactNpmInstallArgs, exactPackageSpec, updatePlanConfirmationText } from "../lib/update-commands.mjs";
|
|
12
|
-
import { createUpdateJournal } from "../lib/update/journal.mjs";
|
|
13
|
-
import { createUpdatePlan } from "../lib/update/plan.mjs";
|
|
14
13
|
|
|
15
|
-
assert.deepEqual(validateUpdatePlanRequest({ targets: ["pi"
|
|
16
|
-
|
|
14
|
+
assert.deepEqual(validateUpdatePlanRequest({ targets: ["pi"] }), { ok: true, targets: ["pi"] });
|
|
15
|
+
assert.deepEqual(validateUpdatePlanRequest({ targets: ["webui"] }), { ok: true, targets: ["webui"] });
|
|
16
|
+
for (const invalid of [{}, { targets: [] }, { targets: ["all"] }, { targets: ["pi", "pi"] }, { targets: ["pi", "webui"] }, { targets: ["pi"], registry: "https://evil.test" }]) {
|
|
17
17
|
assert.equal(validateUpdatePlanRequest(invalid).ok, false);
|
|
18
18
|
}
|
|
19
19
|
const digest = "a".repeat(64);
|
|
@@ -21,20 +21,13 @@ assert.deepEqual(validateUpdateApplyRequest({ transactionId: "tx-1", planDigest:
|
|
|
21
21
|
for (const invalid of [{ transactionId: "tx-1" }, { transactionId: "../x", planDigest: digest }, { transactionId: "tx", planDigest: digest, command: "npm" }]) {
|
|
22
22
|
assert.equal(validateUpdateApplyRequest(invalid).ok, false);
|
|
23
23
|
}
|
|
24
|
-
assert.equal(exactPackageSpec("@firstpick/pi-package-webui", "1.2.3"), "@firstpick/pi-package-webui@1.2.3");
|
|
25
|
-
assert.throws(() => exactPackageSpec("pkg", "latest"), /exact version/);
|
|
26
|
-
const installArgs = exactNpmInstallArgs({ installRoot: "/private/runtime", packageName: "pkg", version: "1.2.3", registry: "https://registry.example.test" });
|
|
27
|
-
assert.deepEqual(installArgs.slice(-3), ["--registry", "https://registry.example.test/", "pkg@1.2.3"]);
|
|
28
|
-
assert.doesNotMatch(installArgs.join(" "), /--all|--extensions|@latest/);
|
|
29
|
-
assert.match(updatePlanConfirmationText({ transactionId: "tx", digest, targets: [{ id: "webui", currentVersion: "1.0.0", targetVersion: "1.1.0" }], refusals: [] }), new RegExp(digest));
|
|
30
24
|
|
|
31
25
|
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
32
26
|
const server = await readFile(path.join(root, "bin", "pi-webui.mjs"), "utf8");
|
|
33
|
-
assert.match(server, /\/api\/update\/plan[\s\S]*validateUpdatePlanRequest[\s\S]*
|
|
34
|
-
assert.match(server, /\/api\/update\/apply[\s\S]*validateUpdateApplyRequest[\s\S]*
|
|
27
|
+
assert.match(server, /\/api\/update\/plan[\s\S]*validateUpdatePlanRequest[\s\S]*createNativeServerPlan/);
|
|
28
|
+
assert.match(server, /\/api\/update\/apply[\s\S]*validateUpdateApplyRequest[\s\S]*applyNativeServerPlan/);
|
|
35
29
|
assert.match(server, /Legacy update mutation is disabled/);
|
|
36
|
-
assert.match(server, /
|
|
37
|
-
assert.match(server, /acquireInstallLock\(agentDir\)[\s\S]*assertPlanIdentity/);
|
|
30
|
+
assert.match(server, /validateNativePlan\(job\.plan, digest\)/);
|
|
38
31
|
assert.match(server, /bootIdentity/);
|
|
39
32
|
assert.doesNotMatch(server, /function resolveUpdateTasks|function projectPackageRootUpdateTasks|function npmGlobalPackageRootUpdateTask|function bunGlobalPackageRootUpdateTask/);
|
|
40
33
|
|
|
@@ -53,7 +46,8 @@ const registry = createHttpServer((req, res) => {
|
|
|
53
46
|
});
|
|
54
47
|
await new Promise((resolve) => registry.listen(registryPort, "127.0.0.1", resolve));
|
|
55
48
|
const temp = await mkdtemp(path.join(tmpdir(), "pi-webui-update-api-"));
|
|
56
|
-
const
|
|
49
|
+
const piFixture = await mkdtemp(path.join(tmpdir(), "pi-webui-update-api-pi-"));
|
|
50
|
+
const fakePi = path.join(piFixture, "fake-pi-with-version.mjs");
|
|
57
51
|
await writeFile(fakePi, `if (process.argv.includes("--version")) { console.log("0.84.0"); process.exit(0); } await import(${JSON.stringify(pathToFileURL(path.join(root, "tests", "fixtures", "fake-pi.mjs")).href)});\n`, "utf8");
|
|
58
52
|
const child = spawn(process.execPath, [path.join(root, "bin", "pi-webui.mjs"), "--cwd", temp, "--host", "127.0.0.1", "--port", String(webuiPort), "--pi", fakePi], {
|
|
59
53
|
stdio: ["ignore", "pipe", "pipe"],
|
|
@@ -64,6 +58,9 @@ const child = spawn(process.execPath, [path.join(root, "bin", "pi-webui.mjs"), "
|
|
|
64
58
|
PI_WEBUI_SETTINGS_FILE: path.join(temp, "settings.json"),
|
|
65
59
|
PI_WEBUI_PI_LATEST_VERSION_URL: `http://127.0.0.1:${registryPort}/pi-latest`,
|
|
66
60
|
PI_WEBUI_NPM_REGISTRY_URL: `http://127.0.0.1:${registryPort}`,
|
|
61
|
+
PI_WEBUI_NPM_BIN: path.join(temp, "missing-npm"),
|
|
62
|
+
NODE_ENV: "test",
|
|
63
|
+
PI_WEBUI_UPDATE_TEST_HOME: temp,
|
|
67
64
|
},
|
|
68
65
|
});
|
|
69
66
|
let output = "";
|
|
@@ -79,47 +76,57 @@ try {
|
|
|
79
76
|
await delay(100);
|
|
80
77
|
}
|
|
81
78
|
assert.ok(health?.bootIdentity, output);
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
assert.equal(planResponse.status, 201, JSON.stringify(planPayload));
|
|
85
|
-
const plan = planPayload.data.plan;
|
|
86
|
-
assert.equal(plan.targets.length, 1, "the exact explicit Pi executable should own its delegated update while source WebUI remains refused");
|
|
87
|
-
assert.equal(plan.targets[0].id, "pi");
|
|
88
|
-
assert.equal(plan.targets[0].strategy, "delegate-exact-pi");
|
|
89
|
-
assert.deepEqual(plan.targets[0].command.args.slice(-2), ["update", "--self"]);
|
|
90
|
-
assert.doesNotMatch(plan.targets[0].command.args.join(" "), /@latest/);
|
|
91
|
-
assert.deepEqual(plan.refusals.map((item) => item.id), ["webui"]);
|
|
92
|
-
|
|
93
|
-
const updatesDir = path.join(temp, "agent", "webui", "updates");
|
|
94
|
-
const journalsBeforeRefusal = await readdir(updatesDir);
|
|
95
|
-
const sourcePlanResponse = await fetch(`http://127.0.0.1:${webuiPort}/api/update/plan`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ targets: ["webui"] }) });
|
|
96
|
-
const sourcePlanPayload = await sourcePlanResponse.json();
|
|
97
|
-
assert.equal(sourcePlanResponse.status, 409, JSON.stringify(sourcePlanPayload));
|
|
98
|
-
assert.match(sourcePlanPayload.error || "", /no accepted targets/i, "a refused-only plan must fail before confirmation or persistence");
|
|
99
|
-
assert.deepEqual(await readdir(updatesDir), journalsBeforeRefusal, "a refused-only plan must not create an update journal");
|
|
100
|
-
|
|
101
|
-
const legacyRefusedPlan = await createUpdatePlan({
|
|
102
|
-
transactionId: "legacy-refused-only",
|
|
103
|
-
createdAt: "2026-08-14T00:00:00.000Z",
|
|
104
|
-
registry: `http://127.0.0.1:${registryPort}`,
|
|
105
|
-
identities: [],
|
|
106
|
-
candidates: [{ id: "pi", packageName: "@earendil-works/pi-coding-agent", owner: { manager: "unknown" } }],
|
|
107
|
-
resolveExactTarget: () => assert.fail("refused targets must not resolve"),
|
|
79
|
+
const request = (targets) => fetch(`http://127.0.0.1:${webuiPort}/api/update/plan`, {
|
|
80
|
+
method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ targets }),
|
|
108
81
|
});
|
|
109
|
-
await
|
|
110
|
-
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
assert.
|
|
82
|
+
const combined = await request(["pi", "webui"]);
|
|
83
|
+
assert.equal(combined.status, 400, "combined actions must be rejected without shell execution");
|
|
84
|
+
const piPlan = await request(["pi"]);
|
|
85
|
+
const piData = await piPlan.json();
|
|
86
|
+
assert.equal(piPlan.status, 409, JSON.stringify(piData));
|
|
87
|
+
assert.match(piData.error || "", /PATH Pi|npm-global|manual/i, "explicit fake Pi is not the verified PATH Pi");
|
|
88
|
+
const webuiPlan = await request(["webui"]);
|
|
89
|
+
const webuiData = await webuiPlan.json();
|
|
90
|
+
assert.equal(webuiPlan.status, 409, JSON.stringify(webuiData));
|
|
91
|
+
assert.match(webuiData.error || "", /manual|unproven|missing/i);
|
|
114
92
|
|
|
115
|
-
const
|
|
116
|
-
assert.equal(
|
|
93
|
+
const refusedApply = await fetch(`http://127.0.0.1:${webuiPort}/api/update/apply`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ transactionId: "legacy-refused-only", planDigest: digest }) });
|
|
94
|
+
assert.equal(refusedApply.status, 404, "legacy per-agent journals must never authorize a native update");
|
|
95
|
+
const missingReceipt = await fetch(`http://127.0.0.1:${webuiPort}/api/update/transactions/legacy-refused-only`);
|
|
96
|
+
assert.equal(missingReceipt.status, 404);
|
|
97
|
+
const rollback = await fetch(`http://127.0.0.1:${webuiPort}/api/update/rollback`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
|
|
98
|
+
assert.equal(rollback.status, 410);
|
|
117
99
|
const legacy = await fetch(`http://127.0.0.1:${webuiPort}/api/update`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
|
|
118
100
|
assert.equal(legacy.status, 410);
|
|
101
|
+
|
|
102
|
+
const getStatus = async () => (await (await fetch(`http://127.0.0.1:${webuiPort}/api/update-status`)).json()).data;
|
|
103
|
+
assert.deepEqual((await getStatus()).nativeJobs, { pi: null, webui: null });
|
|
104
|
+
const stateRoot = path.join(temp, process.platform === "win32" ? "AppData/Local/PiWebUI/updates" : ".local/state/pi-webui-updates");
|
|
105
|
+
const transactionId = randomUUID();
|
|
106
|
+
const jobDir = path.join(stateRoot, "jobs", transactionId);
|
|
107
|
+
await mkdir(jobDir, { recursive: true });
|
|
108
|
+
const receipt = { transactionId, id: "webui:npm-global", status: "failed", exitCode: 1, stderr: "fixture failure" };
|
|
109
|
+
await writeFile(path.join(jobDir, "0.receipt.json"), JSON.stringify(receipt));
|
|
110
|
+
await writeFile(path.join(jobDir, "complete.json"), JSON.stringify({ transactionId, receipts: [{ id: receipt.id, status: receipt.status }] }));
|
|
111
|
+
await persistSharedJob(stateRoot, { transactionId, jobDir, phase: "partial", outcome: "partial", lock: { token: "fixture-private-lock-token" },
|
|
112
|
+
plan: { schemaVersion: 2, transactionId, requested: "webui", createdAt: new Date().toISOString(), targets: [{ id: receipt.id }],
|
|
113
|
+
context: { agentDir: await realpath(path.join(temp, "agent")), ownerPackageRoot: await realpath(root), ownerBootIdentity: health.bootIdentity } } });
|
|
114
|
+
const discovered = await getStatus();
|
|
115
|
+
assert.equal(discovered.nativeJobs.webui.transactionId, transactionId, "a new browser can discover the durable job without local storage");
|
|
116
|
+
assert.equal(discovered.nativeJobs.webui.phase, "partial");
|
|
117
|
+
assert.equal(discovered.nativeJobs.webui.receipts[0].stderr, "fixture failure");
|
|
118
|
+
assert.equal(JSON.stringify(discovered).includes("fixture-private-lock-token"), false);
|
|
119
|
+
assert.equal((await getStatus()).nativeJobs.webui.transactionId, transactionId, "reconnection retains the same partial result");
|
|
120
|
+
await writeFile(path.join(stateRoot, "jobs", `${randomUUID()}.json`), "invalid private record");
|
|
121
|
+
const unverified = await getStatus();
|
|
122
|
+
assert.ok(unverified.nativeJobDiscoveryError);
|
|
123
|
+
assert.equal(unverified.canRunUpdate, false, "discovery failure cannot authorize another update");
|
|
124
|
+
assert.equal(unverified.nativeJobDiscoveryError.includes("invalid private record"), false, "corrupt record contents must not leak in the error");
|
|
119
125
|
} finally {
|
|
120
126
|
child.kill("SIGTERM");
|
|
121
127
|
if (child.exitCode === null) await new Promise((resolve) => child.once("exit", resolve));
|
|
122
128
|
await new Promise((resolve) => registry.close(resolve));
|
|
123
129
|
await rm(temp, { recursive: true, force: true });
|
|
130
|
+
await rm(piFixture, { recursive: true, force: true });
|
|
124
131
|
}
|
|
125
132
|
console.log("update API harness passed");
|
|
@@ -1,18 +1,32 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
|
-
import {
|
|
2
|
+
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { readUpdateContext } from "../bin/pi-webui-update-context.mjs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { nativeUpdateConfirmationText } from "../lib/update-commands.mjs";
|
|
8
|
+
import { createNativeUpdatePlan } from "../lib/update/native-jobs.mjs";
|
|
3
9
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
assert.match(
|
|
17
|
-
assert.match(
|
|
10
|
+
const root = await mkdtemp(path.join(tmpdir(), "pi-webui-update-confirm-"));
|
|
11
|
+
try {
|
|
12
|
+
const driver = path.join(root, "fake-pi.js");
|
|
13
|
+
await writeFile(driver, "// fixture only\n");
|
|
14
|
+
const digest = createHash("sha256").update(await readFile(process.execPath)).digest("hex");
|
|
15
|
+
const context = await readUpdateContext({ env: process.env });
|
|
16
|
+
const plan = await createNativeUpdatePlan({ requested: "pi", context: { cwd: root, agentDir: root, npmPrefix: root,
|
|
17
|
+
shell: process.execPath, shellDigest: digest, nodeDigest: digest,
|
|
18
|
+
settingsPath: path.join(root, "settings.json"), npmConfigFiles: [], ...context },
|
|
19
|
+
targets: [{ eligible: true, id: "pi", effectRoot: root, installed: { root, version: "0.87.1" }, driver,
|
|
20
|
+
command: { command: process.execPath, args: [driver, "update"] } }], refusals: ["Other installations are unproven."], });
|
|
21
|
+
const text = nativeUpdateConfirmationText(plan);
|
|
22
|
+
assert.match(text, /Working directory:/);
|
|
23
|
+
assert.match(text, /Pi agent directory:/);
|
|
24
|
+
assert.match(text, /npm prefix:/);
|
|
25
|
+
assert.match(text, /lifecycle scripts/i);
|
|
26
|
+
assert.match(text, /Other installations are unproven/);
|
|
27
|
+
assert.match(text, /"update"/);
|
|
28
|
+
assert.match(text, new RegExp(plan.digest));
|
|
29
|
+
assert.doesNotMatch(text, /--ignore-scripts|--all|--extensions/);
|
|
30
|
+
assert.throws(() => nativeUpdateConfirmationText({ ...plan, digest: "0".repeat(64) }), /invalid/);
|
|
31
|
+
} finally { await rm(root, { recursive: true, force: true }); }
|
|
18
32
|
console.log("update command planning tests passed");
|