@firstpick/pi-package-webui 0.10.2 → 0.10.4
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 +28 -0
- package/README.md +10 -0
- package/TECHNICAL.md +14 -0
- package/bin/pi-webui.mjs +236 -20
- package/lib/append-system-selection.mjs +311 -0
- package/lib/git-workflow-preferences.mjs +6 -0
- package/lib/trust-boundaries.mjs +37 -0
- package/package.json +2 -2
- package/public/app.js +215 -30
- package/public/index.html +5 -2
- package/public/service-worker.js +1 -1
- package/public/styles.css +9 -0
- package/tests/append-system-http.test.mjs +622 -0
- package/tests/append-system-selection.test.mjs +259 -0
- package/tests/append-system-selector-static.test.mjs +95 -0
- package/tests/boot-failure-diagnostics.test.mjs +2 -2
- package/tests/browser/stats-overlay.spec.mjs +13 -0
- package/tests/codex-fast-mode-static.test.mjs +2 -2
- package/tests/common-options-submenus-interaction-static.test.mjs +4 -0
- package/tests/common-options-submenus-markup-static.test.mjs +2 -1
- package/tests/composer-action-grid-reorder-static.test.mjs +2 -2
- package/tests/control-visibility-static.test.mjs +2 -2
- package/tests/controls-layout-static.test.mjs +2 -2
- package/tests/events-tree-context-menu-static.test.mjs +2 -2
- package/tests/fast-mode-client-static.test.mjs +1 -1
- package/tests/feature-decision-output-popup-static.test.mjs +1 -1
- package/tests/feature-system-prompt-optional-feature-static.test.mjs +1 -1
- package/tests/file-viewer-image-static.test.mjs +2 -2
- package/tests/fixtures/fake-pi.mjs +9 -1
- package/tests/guided-git-activation-static.test.mjs +2 -2
- package/tests/guided-git-fallback-ui-static.test.mjs +2 -2
- package/tests/intercom-conversation-viewer-static.test.mjs +2 -2
- package/tests/main-output-loading-static.test.mjs +2 -2
- package/tests/middle-button-drag-scroll-static.test.mjs +2 -2
- package/tests/mobile-continuity-tablet-static.test.mjs +2 -2
- package/tests/mobile-foundation-static.test.mjs +2 -2
- package/tests/mobile-phone-experience-static.test.mjs +1 -1
- package/tests/native-parity-harness.test.mjs +7 -0
- package/tests/open-issue-wizard-static.test.mjs +1 -1
- package/tests/optional-feature-prompt-impact-static.test.mjs +2 -2
- package/tests/persistent-ui-layout-static.test.mjs +2 -2
- package/tests/prompt-input-vertical-scroll-static.test.mjs +2 -2
- package/tests/questionnaire-dialog.test.mjs +2 -2
- package/tests/session-sampling-ui-static.test.mjs +2 -2
- package/tests/side-panel-section-height-removal-static.test.mjs +2 -2
- package/tests/stats-dashboard-static.test.mjs +11 -0
- package/tests/subagent-observability-static.test.mjs +2 -2
- package/tests/syntax-highlighting-static.test.mjs +2 -2
- package/tests/terminal-tab-prompt-tooltip-static.test.mjs +147 -0
- package/tests/terminal-tab-workspace-static.test.mjs +1 -1
- package/tests/theme-customizer-static.test.mjs +1 -1
- package/tests/windows-drive-cwd-picker-static.test.mjs +2 -2
|
@@ -0,0 +1,622 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { EventEmitter } from "node:events";
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import { createServer, request as httpRequest } from "node:http";
|
|
5
|
+
import { chmod, mkdir, mkdtemp, readFile, rename, rm, symlink, writeFile } from "node:fs/promises";
|
|
6
|
+
import { networkInterfaces, tmpdir } from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { StringDecoder } from "node:string_decoder";
|
|
9
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
10
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
11
|
+
import vm from "node:vm";
|
|
12
|
+
import { terminateProcessTree } from "../lib/process-tree.mjs";
|
|
13
|
+
import { discoverStartAttachRpcSupervisor } from "../lib/rpc-supervisor-client.mjs";
|
|
14
|
+
import { readSupervisorState, supervisorPaths } from "../lib/rpc-supervisor-state.mjs";
|
|
15
|
+
|
|
16
|
+
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
|
17
|
+
const serverScript = path.join(packageRoot, "bin", "pi-webui.mjs");
|
|
18
|
+
const fakePiFixture = path.join(packageRoot, "tests", "fixtures", "fake-pi.mjs");
|
|
19
|
+
const serverSource = await readFile(serverScript, "utf8");
|
|
20
|
+
|
|
21
|
+
function sourceBetween(startMarker, endMarker) {
|
|
22
|
+
const start = serverSource.indexOf(startMarker);
|
|
23
|
+
const end = serverSource.indexOf(endMarker, start);
|
|
24
|
+
assert.ok(start >= 0 && end > start, `${startMarker} should remain extractable for lifecycle regression coverage`);
|
|
25
|
+
return serverSource.slice(start, end);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function assertDirectProcessLifecycle() {
|
|
29
|
+
const children = [];
|
|
30
|
+
const PiRpcProcess = vm.runInNewContext(`
|
|
31
|
+
${sourceBetween("class PiRpcProcess {", "\n// JSON responses are compact")}
|
|
32
|
+
PiRpcProcess;
|
|
33
|
+
`, {
|
|
34
|
+
Buffer,
|
|
35
|
+
StringDecoder,
|
|
36
|
+
clearTimeout,
|
|
37
|
+
console,
|
|
38
|
+
mirrorPiStderr: () => {},
|
|
39
|
+
PI_RPC_JSONL_LINE_MAX_BYTES: 1024,
|
|
40
|
+
process: { env: {} },
|
|
41
|
+
randomUUID: () => "rpc-id",
|
|
42
|
+
REQUEST_TIMEOUT_MS: 1000,
|
|
43
|
+
sanitizeError: (error) => error?.message || String(error),
|
|
44
|
+
setTimeout,
|
|
45
|
+
spawn: () => children.shift(),
|
|
46
|
+
});
|
|
47
|
+
const fakeChild = (pid) => Object.assign(new EventEmitter(), {
|
|
48
|
+
exitCode: null,
|
|
49
|
+
killed: false,
|
|
50
|
+
pid,
|
|
51
|
+
stderr: new EventEmitter(),
|
|
52
|
+
stdin: new EventEmitter(),
|
|
53
|
+
stdout: new EventEmitter(),
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const successfulChild = fakeChild(4321);
|
|
57
|
+
children.push(successfulChild);
|
|
58
|
+
const successfulRpc = new PiRpcProcess({ command: "pi", args: ["--mode", "rpc"], displayCommand: "pi --mode rpc", cwd: "/workspace" });
|
|
59
|
+
const successfulEvents = [];
|
|
60
|
+
successfulRpc.onEvent((event) => successfulEvents.push(event));
|
|
61
|
+
const successfulStart = successfulRpc.start();
|
|
62
|
+
assert.deepEqual(successfulEvents, [], "a direct process must not publish pi_process_start before the child spawn event");
|
|
63
|
+
successfulChild.emit("spawn");
|
|
64
|
+
await successfulStart;
|
|
65
|
+
assert.deepEqual(successfulEvents.map((event) => event.type), ["pi_process_start"], "a successful direct spawn must publish exactly one start event");
|
|
66
|
+
assert.equal(successfulEvents[0].pid, 4321, "the start event must carry the child pid available at spawn time");
|
|
67
|
+
|
|
68
|
+
const failedChild = fakeChild(undefined);
|
|
69
|
+
children.push(failedChild);
|
|
70
|
+
const failedRpc = new PiRpcProcess({ command: "missing-pi", args: [], displayCommand: "missing-pi", cwd: "/workspace" });
|
|
71
|
+
const failedEvents = [];
|
|
72
|
+
failedRpc.onEvent((event) => failedEvents.push(event));
|
|
73
|
+
const failedStart = failedRpc.start();
|
|
74
|
+
assert.deepEqual(failedEvents, [], "a failed direct launch must not report a synchronous start");
|
|
75
|
+
failedChild.emit("error", new Error("spawn missing-pi ENOENT"));
|
|
76
|
+
await assert.rejects(failedStart, /ENOENT/);
|
|
77
|
+
assert.deepEqual(failedEvents.map((event) => event.type), ["pi_process_error"], "a failed spawn must report an error without any start event");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
await assertDirectProcessLifecycle();
|
|
81
|
+
|
|
82
|
+
const cwdUpdateSource = sourceBetween("async function performTabCwdUpdate(tab, cwd) {", "\nasync function restartTabRpc(");
|
|
83
|
+
const directSpawnSuccess = cwdUpdateSource.indexOf("await rpc.start()");
|
|
84
|
+
for (const publication of ["tab.cwd = nextCwd", "resetTabActivity(tab)", "workspaceFilesLiveWatcher.unsubscribe(tab.id)"]) {
|
|
85
|
+
assert.ok(directSpawnSuccess >= 0 && cwdUpdateSource.indexOf(publication) > directSpawnSuccess, `${publication} must remain delayed until a direct replacement spawn succeeds`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function freePort() {
|
|
89
|
+
const probe = createServer();
|
|
90
|
+
await new Promise((resolve, reject) => {
|
|
91
|
+
probe.once("error", reject);
|
|
92
|
+
probe.listen(0, "127.0.0.1", resolve);
|
|
93
|
+
});
|
|
94
|
+
const selected = probe.address().port;
|
|
95
|
+
await new Promise((resolve, reject) => probe.close((error) => error ? reject(error) : resolve()));
|
|
96
|
+
return selected;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function lanAddress() {
|
|
100
|
+
for (const entries of Object.values(networkInterfaces())) {
|
|
101
|
+
for (const entry of entries || []) {
|
|
102
|
+
if (entry.family === "IPv4" && !entry.internal) return entry.address;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const root = await mkdtemp(path.join(tmpdir(), "pi-webui-append-system-http-"));
|
|
109
|
+
const home = path.join(root, "home");
|
|
110
|
+
const cwd = path.join(root, "project");
|
|
111
|
+
const otherCwd = path.join(root, "other-project");
|
|
112
|
+
const replacementCwd = path.join(root, "replacement-project");
|
|
113
|
+
const failedReplacementCwd = path.join(root, "failed-replacement-project");
|
|
114
|
+
const settingsFile = path.join(root, "settings.json");
|
|
115
|
+
const launchLog = path.join(root, "pi-launches.jsonl");
|
|
116
|
+
const fakePi = path.join(root, process.platform === "win32" ? "fake-pi.mjs" : "fake-pi");
|
|
117
|
+
const port = await freePort();
|
|
118
|
+
const baseUrl = `http://127.0.0.1:${port}`;
|
|
119
|
+
let child;
|
|
120
|
+
let supervisorSeed;
|
|
121
|
+
let output = "";
|
|
122
|
+
|
|
123
|
+
async function request(host, pathname, { method = "GET", body, headers = {}, rawBody } = {}) {
|
|
124
|
+
const requestHeaders = { ...headers };
|
|
125
|
+
if (body !== undefined && !Object.keys(requestHeaders).some((name) => name.toLowerCase() === "content-type")) {
|
|
126
|
+
requestHeaders["content-type"] = "application/json";
|
|
127
|
+
}
|
|
128
|
+
const requestBody = rawBody === undefined ? (body === undefined ? undefined : JSON.stringify(body)) : rawBody;
|
|
129
|
+
if (Object.keys(requestHeaders).some((name) => name.toLowerCase() === "host")) {
|
|
130
|
+
return new Promise((resolve, reject) => {
|
|
131
|
+
const pending = httpRequest({ host, port, path: pathname, method, headers: requestHeaders }, (response) => {
|
|
132
|
+
const chunks = [];
|
|
133
|
+
response.on("data", (chunk) => chunks.push(chunk));
|
|
134
|
+
response.on("end", () => {
|
|
135
|
+
try {
|
|
136
|
+
resolve({ status: response.statusCode, body: JSON.parse(Buffer.concat(chunks).toString("utf8")), headers: new Headers(response.headers) });
|
|
137
|
+
} catch (error) {
|
|
138
|
+
reject(error);
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
pending.setTimeout(8_000, () => pending.destroy(new Error("HTTP request timed out")));
|
|
143
|
+
pending.once("error", reject);
|
|
144
|
+
pending.end(requestBody);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
const response = await fetch(`http://${host}:${port}${pathname}`, {
|
|
148
|
+
method,
|
|
149
|
+
headers: requestHeaders,
|
|
150
|
+
body: requestBody,
|
|
151
|
+
signal: AbortSignal.timeout(8_000),
|
|
152
|
+
});
|
|
153
|
+
return { status: response.status, body: await response.json(), headers: response.headers };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function launches() {
|
|
157
|
+
const text = await readFile(launchLog, "utf8").catch(() => "");
|
|
158
|
+
return text.split(/\r?\n/).filter(Boolean).map((line) => JSON.parse(line));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function withDirectSpawnFailure(run) {
|
|
162
|
+
const unavailableFakePi = `${fakePi}.unavailable`;
|
|
163
|
+
await rename(fakePi, unavailableFakePi);
|
|
164
|
+
try {
|
|
165
|
+
return await run();
|
|
166
|
+
} finally {
|
|
167
|
+
await rename(unavailableFakePi, fakePi);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
try {
|
|
172
|
+
const externalPiRoot = path.join(root, "external-pi-root");
|
|
173
|
+
const externalDirectoryTarget = path.join(root, "external-directory-target");
|
|
174
|
+
const externalFileTarget = path.join(root, "external-file-target", "prompt.txt");
|
|
175
|
+
await Promise.all([
|
|
176
|
+
mkdir(home, { recursive: true }),
|
|
177
|
+
mkdir(path.join(externalPiRoot, "global"), { recursive: true }),
|
|
178
|
+
mkdir(path.join(externalPiRoot, "agent", "minimal"), { recursive: true }),
|
|
179
|
+
mkdir(externalDirectoryTarget, { recursive: true }),
|
|
180
|
+
mkdir(path.dirname(externalFileTarget), { recursive: true }),
|
|
181
|
+
mkdir(path.join(cwd, ".pi"), { recursive: true }),
|
|
182
|
+
mkdir(path.join(cwd, "zz-saved"), { recursive: true }),
|
|
183
|
+
mkdir(path.join(cwd, "linked-file"), { recursive: true }),
|
|
184
|
+
mkdir(otherCwd, { recursive: true }),
|
|
185
|
+
mkdir(replacementCwd, { recursive: true }),
|
|
186
|
+
mkdir(failedReplacementCwd, { recursive: true }),
|
|
187
|
+
]);
|
|
188
|
+
|
|
189
|
+
const unsupportedSymlinkCodes = new Set(["EPERM", "EACCES", "EINVAL", "ENOTSUP"]);
|
|
190
|
+
let rootSymlinkAvailable = true;
|
|
191
|
+
try {
|
|
192
|
+
await symlink(externalPiRoot, path.join(home, ".pi"), process.platform === "win32" ? "junction" : "dir");
|
|
193
|
+
} catch (error) {
|
|
194
|
+
rootSymlinkAvailable = false;
|
|
195
|
+
if (!unsupportedSymlinkCodes.has(error?.code)) throw error;
|
|
196
|
+
await mkdir(path.join(home, ".pi", "global"), { recursive: true });
|
|
197
|
+
await mkdir(path.join(home, ".pi", "agent", "minimal"), { recursive: true });
|
|
198
|
+
}
|
|
199
|
+
const piStorageRoot = rootSymlinkAvailable ? externalPiRoot : path.join(home, ".pi");
|
|
200
|
+
const globalDefaultCandidate = path.join(home, ".pi", "agent", "APPEND_SYSTEM.md");
|
|
201
|
+
const globalCandidate = path.join(home, ".pi", "global", "APPEND_SYSTEM.md");
|
|
202
|
+
const nestedGlobalCandidate = path.join(home, ".pi", "agent", "minimal", "APPEND_SYSTEM.md");
|
|
203
|
+
const projectDefaultCandidate = path.join(cwd, ".pi", "APPEND_SYSTEM.md");
|
|
204
|
+
const projectCandidate = path.join(cwd, "zz-saved", "APPEND_SYSTEM.md");
|
|
205
|
+
const directoryAlias = path.join(cwd, "linked-directory");
|
|
206
|
+
const directoryAliasCandidate = path.join(directoryAlias, "APPEND_SYSTEM.md");
|
|
207
|
+
const fileAliasCandidate = path.join(cwd, "linked-file", "APPEND_SYSTEM.md");
|
|
208
|
+
const outsideCandidate = path.join(root, "outside", "APPEND_SYSTEM.md");
|
|
209
|
+
await mkdir(path.dirname(outsideCandidate), { recursive: true });
|
|
210
|
+
await Promise.all([
|
|
211
|
+
writeFile(path.join(piStorageRoot, "agent", "APPEND_SYSTEM.md"), "Pi global default must not be duplicated\n", "utf8"),
|
|
212
|
+
writeFile(path.join(piStorageRoot, "global", "APPEND_SYSTEM.md"), "global prompt contents must remain private\n", "utf8"),
|
|
213
|
+
writeFile(path.join(piStorageRoot, "agent", "minimal", "APPEND_SYSTEM.md"), "nested global prompt contents must remain private\n", "utf8"),
|
|
214
|
+
writeFile(path.join(externalDirectoryTarget, "APPEND_SYSTEM.md"), "external directory prompt\n", "utf8"),
|
|
215
|
+
writeFile(externalFileTarget, "external file prompt\n", "utf8"),
|
|
216
|
+
writeFile(projectDefaultCandidate, "project-local default must remain selectable\n", "utf8"),
|
|
217
|
+
writeFile(projectCandidate, "project prompt contents must remain private\n", "utf8"),
|
|
218
|
+
writeFile(outsideCandidate, "outside prompt\n", "utf8"),
|
|
219
|
+
...(process.platform === "win32" ? [] : ["\n", "\r", "\t", "\u007f"].map(async (control) => {
|
|
220
|
+
const unsafeCandidate = path.join(cwd, `unsafe${control}`, "APPEND_SYSTEM.md");
|
|
221
|
+
await mkdir(path.dirname(unsafeCandidate), { recursive: true });
|
|
222
|
+
await writeFile(unsafeCandidate, "control-character candidate contents must remain private\n", "utf8");
|
|
223
|
+
})),
|
|
224
|
+
writeFile(settingsFile, `${JSON.stringify({
|
|
225
|
+
version: 8,
|
|
226
|
+
remoteAuthEnabled: false,
|
|
227
|
+
retainedFixture: { value: 7 },
|
|
228
|
+
appendSystemPromptPath: globalDefaultCandidate,
|
|
229
|
+
appendSystemPromptRootPath: path.join(home, ".pi"),
|
|
230
|
+
})}\n`, "utf8"),
|
|
231
|
+
]);
|
|
232
|
+
|
|
233
|
+
let directorySymlinkAvailable = true;
|
|
234
|
+
try {
|
|
235
|
+
await symlink(externalDirectoryTarget, directoryAlias, process.platform === "win32" ? "junction" : "dir");
|
|
236
|
+
} catch (error) {
|
|
237
|
+
directorySymlinkAvailable = false;
|
|
238
|
+
if (!unsupportedSymlinkCodes.has(error?.code)) throw error;
|
|
239
|
+
}
|
|
240
|
+
let fileSymlinkAvailable = true;
|
|
241
|
+
try {
|
|
242
|
+
await symlink(externalFileTarget, fileAliasCandidate, "file");
|
|
243
|
+
} catch (error) {
|
|
244
|
+
fileSymlinkAvailable = false;
|
|
245
|
+
if (!unsupportedSymlinkCodes.has(error?.code)) throw error;
|
|
246
|
+
}
|
|
247
|
+
const selectedCandidate = fileSymlinkAvailable ? fileAliasCandidate : projectCandidate;
|
|
248
|
+
await writeFile(fakePi, `#!/usr/bin/env node\nimport { appendFile } from "node:fs/promises";\nconst args = process.argv.slice(2);\nif (args[0] === "--version") { console.log("0.84.0"); process.exit(0); }\nawait appendFile(process.env.APPEND_SYSTEM_LAUNCH_LOG, JSON.stringify(args) + "\\n", "utf8");\nawait import(${JSON.stringify(pathToFileURL(fakePiFixture).href)});\n`, "utf8");
|
|
249
|
+
await chmod(fakePi, 0o755);
|
|
250
|
+
|
|
251
|
+
child = spawn(process.execPath, [
|
|
252
|
+
serverScript,
|
|
253
|
+
"--cwd", cwd,
|
|
254
|
+
"--host", "0.0.0.0",
|
|
255
|
+
"--port", String(port),
|
|
256
|
+
"--pi", fakePi,
|
|
257
|
+
"--",
|
|
258
|
+
"--append-system-prompt", "explicit-launcher-override",
|
|
259
|
+
], {
|
|
260
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
261
|
+
env: {
|
|
262
|
+
...process.env,
|
|
263
|
+
HOME: home,
|
|
264
|
+
USERPROFILE: home,
|
|
265
|
+
PI_CODING_AGENT_DIR: path.join(home, ".pi", "agent"),
|
|
266
|
+
PI_WEBUI_SETTINGS_FILE: settingsFile,
|
|
267
|
+
PI_WEBUI_RPC_SUPERVISOR: "0",
|
|
268
|
+
APPEND_SYSTEM_LAUNCH_LOG: launchLog,
|
|
269
|
+
},
|
|
270
|
+
});
|
|
271
|
+
child.stdout.on("data", (chunk) => { output += String(chunk); });
|
|
272
|
+
child.stderr.on("data", (chunk) => { output += String(chunk); });
|
|
273
|
+
|
|
274
|
+
let health;
|
|
275
|
+
for (let attempt = 0; attempt < 100; attempt += 1) {
|
|
276
|
+
if (child.exitCode !== null) break;
|
|
277
|
+
try {
|
|
278
|
+
health = await fetch(`${baseUrl}/api/health`, { signal: AbortSignal.timeout(1_000) });
|
|
279
|
+
if (health.status === 200) break;
|
|
280
|
+
} catch {
|
|
281
|
+
}
|
|
282
|
+
await delay(100);
|
|
283
|
+
}
|
|
284
|
+
assert.equal(health?.status, 200, `server should become healthy\n${output}`);
|
|
285
|
+
|
|
286
|
+
const tabsResponse = await request("127.0.0.1", "/api/tabs");
|
|
287
|
+
const initialTab = tabsResponse.body?.data?.tabs?.[0];
|
|
288
|
+
const tabId = initialTab?.id;
|
|
289
|
+
assert.ok(tabId);
|
|
290
|
+
assert.equal(initialTab.prompt, null, "Pi default discovery must expose no tab-local override");
|
|
291
|
+
assert.equal(JSON.stringify(initialTab.prompt).includes("explicit-launcher-override"), false, "arbitrary launcher prompt values must not be inferred into prompt metadata");
|
|
292
|
+
const route = `/api/append-system-files?tab=${encodeURIComponent(tabId)}`;
|
|
293
|
+
const discovered = await request("127.0.0.1", route);
|
|
294
|
+
assert.equal(discovered.status, 200, discovered.body?.error);
|
|
295
|
+
assert.equal(discovered.headers.get("cache-control"), "private, no-store");
|
|
296
|
+
assert.equal(discovered.body?.data?.appendSystemPromptPath, null, "a persisted exact global default must be represented as Pi default discovery");
|
|
297
|
+
assert.deepEqual(discovered.body?.data?.roots?.map(({ label }) => label), ["Pi home", "Current folder"]);
|
|
298
|
+
const expectedCandidates = [globalCandidate, nestedGlobalCandidate, projectDefaultCandidate, projectCandidate];
|
|
299
|
+
if (directorySymlinkAvailable) expectedCandidates.push(directoryAliasCandidate);
|
|
300
|
+
if (fileSymlinkAvailable) expectedCandidates.push(fileAliasCandidate);
|
|
301
|
+
assert.deepEqual(discovered.body?.data?.candidates?.map(({ path: candidatePath }) => candidatePath), expectedCandidates.sort());
|
|
302
|
+
assert.equal(discovered.body?.data?.candidates?.some(({ path: candidatePath }) => /[\u0000-\u001f\u007f]/.test(candidatePath)), false, "control-character candidates must be omitted from API discovery");
|
|
303
|
+
assert.equal(JSON.stringify(discovered.body).includes("control-character candidate contents must remain private"), false, "omitted control-character candidates must not expose contents");
|
|
304
|
+
assert.equal(discovered.body?.data?.candidates?.some(({ path: candidatePath }) => candidatePath === globalDefaultCandidate), false, "the exact global Pi default must not be rendered as a duplicate candidate");
|
|
305
|
+
assert.ok(discovered.body?.data?.candidates?.some(({ path: candidatePath }) => candidatePath === nestedGlobalCandidate), "a nested global alternative must remain visible");
|
|
306
|
+
assert.ok(discovered.body?.data?.candidates?.some(({ path: candidatePath }) => candidatePath === projectDefaultCandidate), "a project-local default must remain visible");
|
|
307
|
+
if (rootSymlinkAvailable) assert.ok(discovered.body?.data?.candidates?.some(({ path: candidatePath }) => candidatePath === nestedGlobalCandidate), "a symlinked ~/.pi root must preserve its visible alias candidate");
|
|
308
|
+
if (directorySymlinkAvailable) assert.ok(discovered.body?.data?.candidates?.some(({ path: candidatePath }) => candidatePath === directoryAliasCandidate), "an external directory link must expose its visible candidate path");
|
|
309
|
+
if (fileSymlinkAvailable) assert.ok(discovered.body?.data?.candidates?.some(({ path: candidatePath }) => candidatePath === fileAliasCandidate), "an exact-name file link to a differently named external file must expose its visible alias");
|
|
310
|
+
assert.equal(JSON.stringify(discovered.body).includes("prompt contents"), false, "HTTP discovery must not expose file contents");
|
|
311
|
+
assert.equal((await request("127.0.0.1", route, { headers: { "sec-fetch-site": "same-origin" } })).status, 200, "same-origin GET discovery must remain accepted");
|
|
312
|
+
assert.equal((await request("127.0.0.1", route, { headers: { host: "attacker.example", "sec-fetch-site": "same-origin" } })).status, 403, "same-origin metadata must not bypass the loopback Host guard");
|
|
313
|
+
for (const hostAuthority of [`localhost:${port}`, `127.42.0.1:${port}`, `[::1]:${port}`]) {
|
|
314
|
+
assert.equal((await request("127.0.0.1", route, { headers: { host: hostAuthority, "sec-fetch-site": "same-origin" } })).status, 200, `loopback Host ${hostAuthority} must remain accepted`);
|
|
315
|
+
}
|
|
316
|
+
assert.equal((await request("127.0.0.1", route, { headers: { "sec-fetch-site": "cross-site" } })).status, 403, "cross-site GET discovery must be blocked");
|
|
317
|
+
|
|
318
|
+
const remoteHost = lanAddress();
|
|
319
|
+
if (remoteHost) assert.equal((await request(remoteHost, route)).status, 403, "GET discovery must be localhost-only");
|
|
320
|
+
|
|
321
|
+
const selectionRoute = "/api/append-system-selection";
|
|
322
|
+
const crossSitePost = await request("127.0.0.1", selectionRoute, {
|
|
323
|
+
method: "POST",
|
|
324
|
+
headers: { "sec-fetch-site": "cross-site" },
|
|
325
|
+
body: { tabId, path: projectCandidate },
|
|
326
|
+
});
|
|
327
|
+
assert.equal(crossSitePost.status, 403, "cross-site POST selection must be blocked");
|
|
328
|
+
const reboundPost = await request("127.0.0.1", selectionRoute, {
|
|
329
|
+
method: "POST",
|
|
330
|
+
headers: { host: `attacker.example:${port}`, "sec-fetch-site": "same-origin" },
|
|
331
|
+
body: { tabId, path: projectCandidate },
|
|
332
|
+
});
|
|
333
|
+
assert.equal(reboundPost.status, 403, "same-origin POST metadata must not bypass the loopback Host guard");
|
|
334
|
+
const textPost = await request("127.0.0.1", selectionRoute, {
|
|
335
|
+
method: "POST",
|
|
336
|
+
headers: { "content-type": "text/plain" },
|
|
337
|
+
rawBody: JSON.stringify({ tabId, path: projectCandidate }),
|
|
338
|
+
});
|
|
339
|
+
assert.equal(textPost.status, 415, "text/plain POST selection must be rejected before parsing");
|
|
340
|
+
const malformedPost = await request("127.0.0.1", selectionRoute, {
|
|
341
|
+
method: "POST",
|
|
342
|
+
headers: { "content-type": "application/json" },
|
|
343
|
+
rawBody: "{not valid JSON",
|
|
344
|
+
});
|
|
345
|
+
assert.equal(malformedPost.status, 400, "malformed JSON must return a controlled client error");
|
|
346
|
+
for (const nonObjectBody of [null, [], "selection", 42, true, false]) {
|
|
347
|
+
const rejected = await request("127.0.0.1", selectionRoute, { method: "POST", body: nonObjectBody });
|
|
348
|
+
assert.equal(rejected.status, 400, `non-object body ${JSON.stringify(nonObjectBody)} must be rejected`);
|
|
349
|
+
}
|
|
350
|
+
assert.equal((await request("127.0.0.1", selectionRoute, { method: "POST", body: { tabId, path: projectCandidate, unsupported: true } })).status, 400, "unsupported POST fields must be rejected");
|
|
351
|
+
assert.equal((await request("127.0.0.1", selectionRoute, { method: "POST", body: { path: projectCandidate } })).status, 400, "tabId is required by the POST contract");
|
|
352
|
+
|
|
353
|
+
for (const invalidPath of [outsideCandidate, path.join(cwd, "missing", "APPEND_SYSTEM.md")]) {
|
|
354
|
+
const rejected = await request("127.0.0.1", selectionRoute, { method: "POST", body: { tabId, path: invalidPath } });
|
|
355
|
+
assert.equal(rejected.status, 400, `fresh validation must reject ${invalidPath}`);
|
|
356
|
+
}
|
|
357
|
+
for (const control of ["\n", "\r", "\t", "\u007f", "\0"]) {
|
|
358
|
+
const unsafePath = `${cwd}${path.sep}unsafe${control}${path.sep}APPEND_SYSTEM.md`;
|
|
359
|
+
const rejected = await request("127.0.0.1", selectionRoute, { method: "POST", body: { tabId, path: unsafePath } });
|
|
360
|
+
assert.equal(rejected.status, 400, `selection API must reject control character ${JSON.stringify(control)}`);
|
|
361
|
+
}
|
|
362
|
+
assert.equal((await request("127.0.0.1", selectionRoute, { method: "POST", body: { tabId, path: 42 } })).status, 400);
|
|
363
|
+
if (remoteHost) {
|
|
364
|
+
assert.equal((await request(remoteHost, "/api/append-system-selection", { method: "POST", body: { tabId, path: projectCandidate } })).status, 403, "POST selection must be localhost-only");
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
let latestArgs = (await launches()).at(-1);
|
|
368
|
+
assert.equal(latestArgs.includes(globalDefaultCandidate), false, "a persisted exact global default must not become a redundant launcher override");
|
|
369
|
+
assert.equal(latestArgs.filter((arg) => arg === "--append-system-prompt").length, 1, "only the explicit launcher override should remain for Pi default discovery");
|
|
370
|
+
|
|
371
|
+
const normalizedDefault = await request("127.0.0.1", selectionRoute, {
|
|
372
|
+
method: "POST",
|
|
373
|
+
body: { tabId, path: globalDefaultCandidate },
|
|
374
|
+
});
|
|
375
|
+
assert.equal(normalizedDefault.status, 200, normalizedDefault.body?.error);
|
|
376
|
+
assert.deepEqual({
|
|
377
|
+
path: normalizedDefault.body?.data?.appendSystemPromptPath,
|
|
378
|
+
changed: normalizedDefault.body?.data?.changed,
|
|
379
|
+
restartRequired: normalizedDefault.body?.data?.restartRequired,
|
|
380
|
+
}, { path: null, changed: true, restartRequired: true }, "submitting the exact global default must clear the redundant saved override");
|
|
381
|
+
const persistedAfterDefaultNormalization = JSON.parse(await readFile(settingsFile, "utf8"));
|
|
382
|
+
assert.equal(persistedAfterDefaultNormalization.appendSystemPromptPath, null);
|
|
383
|
+
assert.equal(persistedAfterDefaultNormalization.appendSystemPromptRootPath, null);
|
|
384
|
+
|
|
385
|
+
if (rootSymlinkAvailable) {
|
|
386
|
+
const rootAliasSaved = await request("127.0.0.1", selectionRoute, { method: "POST", body: { tabId, path: nestedGlobalCandidate } });
|
|
387
|
+
assert.equal(rootAliasSaved.status, 200, rootAliasSaved.body?.error);
|
|
388
|
+
const persistedRootAlias = JSON.parse(await readFile(settingsFile, "utf8"));
|
|
389
|
+
assert.equal(persistedRootAlias.appendSystemPromptPath, nestedGlobalCandidate);
|
|
390
|
+
assert.equal(persistedRootAlias.appendSystemPromptRootPath, path.join(home, ".pi"));
|
|
391
|
+
const rootAliasTab = await request("127.0.0.1", "/api/tabs", { method: "POST", body: { cwd: otherCwd, title: "symlinked root selection" } });
|
|
392
|
+
assert.equal(rootAliasTab.status, 201, rootAliasTab.body?.error);
|
|
393
|
+
assert.ok((await launches()).at(-1).includes(nestedGlobalCandidate), "persisted launch validation must pass the visible alias below a symlinked root");
|
|
394
|
+
}
|
|
395
|
+
if (directorySymlinkAvailable) {
|
|
396
|
+
const directoryAliasSaved = await request("127.0.0.1", selectionRoute, { method: "POST", body: { tabId, path: directoryAliasCandidate } });
|
|
397
|
+
assert.equal(directoryAliasSaved.status, 200, directoryAliasSaved.body?.error);
|
|
398
|
+
const persistedDirectoryAlias = JSON.parse(await readFile(settingsFile, "utf8"));
|
|
399
|
+
assert.equal(persistedDirectoryAlias.appendSystemPromptPath, directoryAliasCandidate);
|
|
400
|
+
assert.equal(persistedDirectoryAlias.appendSystemPromptRootPath, cwd);
|
|
401
|
+
const directoryAliasTab = await request("127.0.0.1", "/api/tabs", { method: "POST", body: { cwd: otherCwd, title: "external directory alias selection" } });
|
|
402
|
+
assert.equal(directoryAliasTab.status, 201, directoryAliasTab.body?.error);
|
|
403
|
+
assert.ok((await launches()).at(-1).includes(directoryAliasCandidate), "persisted launch validation must pass an external directory's visible alias");
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const launchCountBeforeSave = (await launches()).length;
|
|
407
|
+
const saved = await request("127.0.0.1", selectionRoute, {
|
|
408
|
+
method: "POST",
|
|
409
|
+
headers: { "sec-fetch-site": "same-origin" },
|
|
410
|
+
body: { tabId, path: selectedCandidate },
|
|
411
|
+
});
|
|
412
|
+
assert.equal(saved.status, 200, saved.body?.error);
|
|
413
|
+
assert.equal(saved.body?.data?.appendSystemPromptPath, selectedCandidate);
|
|
414
|
+
assert.equal(saved.body?.data?.changed, true);
|
|
415
|
+
assert.equal(saved.body?.data?.restartRequired, true);
|
|
416
|
+
await delay(150);
|
|
417
|
+
assert.equal((await launches()).length, launchCountBeforeSave, "saving must not automatically restart the active tab");
|
|
418
|
+
const persistedAfterSave = JSON.parse(await readFile(settingsFile, "utf8"));
|
|
419
|
+
assert.equal(persistedAfterSave.appendSystemPromptPath, selectedCandidate);
|
|
420
|
+
assert.equal(persistedAfterSave.appendSystemPromptRootPath, cwd);
|
|
421
|
+
assert.deepEqual(persistedAfterSave.retainedFixture, { value: 7 }, "selection writes must preserve existing settings fields");
|
|
422
|
+
const unchangedInitialTab = (await request("127.0.0.1", "/api/tabs")).body?.data?.tabs?.find((tab) => tab.id === tabId);
|
|
423
|
+
assert.equal(unchangedInitialTab?.prompt, null, "saving a global choice must not rewrite an already-running tab's runtime metadata");
|
|
424
|
+
|
|
425
|
+
const sameSelection = await request("127.0.0.1", "/api/append-system-selection", { method: "POST", body: { tabId, path: selectedCandidate } });
|
|
426
|
+
assert.deepEqual({ changed: sameSelection.body?.data?.changed, restartRequired: sameSelection.body?.data?.restartRequired }, { changed: false, restartRequired: false });
|
|
427
|
+
|
|
428
|
+
await Promise.all(Array.from({ length: 256 }, async (_, index) => {
|
|
429
|
+
const competitor = path.join(cwd, `candidate-${String(index).padStart(3, "0")}`, "APPEND_SYSTEM.md");
|
|
430
|
+
await mkdir(path.dirname(competitor), { recursive: true });
|
|
431
|
+
await writeFile(competitor, `competitor ${index}\n`, "utf8");
|
|
432
|
+
}));
|
|
433
|
+
const crowdedDiscovery = await request("127.0.0.1", route);
|
|
434
|
+
assert.equal(crowdedDiscovery.body?.data?.limits?.truncated?.candidates, true, "the fixture must exceed fresh candidate discovery limits");
|
|
435
|
+
assert.equal(crowdedDiscovery.body?.data?.candidates?.length, 256, "the hidden global default must not consume a returned candidate slot");
|
|
436
|
+
assert.ok(crowdedDiscovery.body?.data?.candidates?.some(({ path: candidatePath }) => candidatePath === selectedCandidate), "the valid saved selection must remain visible despite candidate-cap crowd-out");
|
|
437
|
+
|
|
438
|
+
const selectedTab = await request("127.0.0.1", "/api/tabs", { method: "POST", body: { cwd: otherCwd, title: "selected prompt in another project" } });
|
|
439
|
+
assert.equal(selectedTab.status, 201, selectedTab.body?.error);
|
|
440
|
+
const otherTabId = selectedTab.body?.data?.tab?.id;
|
|
441
|
+
assert.ok(otherTabId);
|
|
442
|
+
assert.deepEqual(selectedTab.body?.data?.tab?.prompt, { kind: "append-system", path: selectedCandidate }, "a selected launch must expose only its bounded tab-local descriptor");
|
|
443
|
+
assert.equal(JSON.stringify(selectedTab.body?.data?.tab?.prompt).includes("prompt contents must remain private"), false, "tab prompt metadata must not expose prompt contents");
|
|
444
|
+
latestArgs = (await launches()).at(-1);
|
|
445
|
+
const selectedIndex = latestArgs.indexOf(selectedCandidate);
|
|
446
|
+
const explicitPromptIndex = latestArgs.indexOf("explicit-launcher-override");
|
|
447
|
+
assert.ok(selectedIndex > 0 && latestArgs[selectedIndex - 1] === "--append-system-prompt");
|
|
448
|
+
assert.ok(explicitPromptIndex > selectedIndex && latestArgs[explicitPromptIndex - 1] === "--append-system-prompt", "saved and launcher append prompts must both be passed in argument order");
|
|
449
|
+
|
|
450
|
+
const otherRoute = `/api/append-system-files?tab=${encodeURIComponent(otherTabId)}`;
|
|
451
|
+
const otherProjectDiscovery = await request("127.0.0.1", otherRoute);
|
|
452
|
+
assert.ok(otherProjectDiscovery.body?.data?.candidates?.some((candidate) => candidate.path === selectedCandidate && candidate.rootLabel === "Saved selection"), "a provenance-valid global selection must remain visible outside its source project");
|
|
453
|
+
const otherProjectNoOp = await request("127.0.0.1", "/api/append-system-selection", { method: "POST", body: { tabId: otherTabId, path: selectedCandidate } });
|
|
454
|
+
assert.deepEqual({ changed: otherProjectNoOp.body?.data?.changed, restartRequired: otherProjectNoOp.body?.data?.restartRequired }, { changed: false, restartRequired: false });
|
|
455
|
+
|
|
456
|
+
const defaultSavedForReload = await request("127.0.0.1", selectionRoute, { method: "POST", body: { tabId: otherTabId, path: null } });
|
|
457
|
+
assert.equal(defaultSavedForReload.status, 200, defaultSavedForReload.body?.error);
|
|
458
|
+
const beforeReload = (await request("127.0.0.1", "/api/tabs")).body?.data?.tabs?.find((tab) => tab.id === otherTabId);
|
|
459
|
+
assert.deepEqual(beforeReload?.prompt, { kind: "append-system", path: selectedCandidate }, "a settings change must leave the running tab's descriptor unchanged until replacement succeeds");
|
|
460
|
+
const reloadedDefault = await request("127.0.0.1", "/api/prompt", { method: "POST", body: { tab: otherTabId, message: "/reload" } });
|
|
461
|
+
assert.equal(reloadedDefault.status, 200, reloadedDefault.body?.error);
|
|
462
|
+
assert.equal(reloadedDefault.body?.tab?.prompt, null, "a successful reload must replace the tab descriptor with the prompt used by the new process");
|
|
463
|
+
|
|
464
|
+
await writeFile(settingsFile, `${JSON.stringify(persistedAfterSave)}\n`, "utf8");
|
|
465
|
+
const cwdReplacement = await request("127.0.0.1", `/api/tabs/${encodeURIComponent(otherTabId)}`, { method: "PATCH", body: { cwd: replacementCwd } });
|
|
466
|
+
assert.equal(cwdReplacement.status, 200, cwdReplacement.body?.error);
|
|
467
|
+
assert.equal(cwdReplacement.body?.data?.changed, true);
|
|
468
|
+
assert.equal(cwdReplacement.body?.data?.tab?.cwd, replacementCwd);
|
|
469
|
+
assert.deepEqual(cwdReplacement.body?.data?.tab?.prompt, { kind: "append-system", path: selectedCandidate }, "a successful direct cwd replacement must publish the replacement descriptor");
|
|
470
|
+
|
|
471
|
+
if (process.platform !== "win32") {
|
|
472
|
+
const defaultBeforeFailedReload = await request("127.0.0.1", selectionRoute, { method: "POST", body: { tabId: otherTabId, path: null } });
|
|
473
|
+
assert.equal(defaultBeforeFailedReload.status, 200, defaultBeforeFailedReload.body?.error);
|
|
474
|
+
const failedReload = await withDirectSpawnFailure(() => request("127.0.0.1", "/api/prompt", { method: "POST", body: { tab: otherTabId, message: "/reload" } }));
|
|
475
|
+
assert.equal(failedReload.status, 500, "a direct reload whose child cannot spawn must fail the request");
|
|
476
|
+
assert.deepEqual(
|
|
477
|
+
(await request("127.0.0.1", "/api/tabs")).body?.data?.tabs?.find((tab) => tab.id === otherTabId)?.prompt,
|
|
478
|
+
{ kind: "append-system", path: selectedCandidate },
|
|
479
|
+
"a failed direct reload must retain the old prompt descriptor",
|
|
480
|
+
);
|
|
481
|
+
|
|
482
|
+
await writeFile(settingsFile, `${JSON.stringify(persistedAfterSave)}\n`, "utf8");
|
|
483
|
+
const failedCwdReplacement = await withDirectSpawnFailure(() => request("127.0.0.1", `/api/tabs/${encodeURIComponent(tabId)}`, { method: "PATCH", body: { cwd: failedReplacementCwd } }));
|
|
484
|
+
assert.equal(failedCwdReplacement.status, 502, "a direct cwd replacement whose child cannot spawn must fail the request");
|
|
485
|
+
const tabAfterFailedCwdReplacement = (await request("127.0.0.1", "/api/tabs")).body?.data?.tabs?.find((tab) => tab.id === tabId);
|
|
486
|
+
assert.deepEqual(
|
|
487
|
+
{ cwd: tabAfterFailedCwdReplacement?.cwd, prompt: tabAfterFailedCwdReplacement?.prompt },
|
|
488
|
+
{ cwd, prompt: null },
|
|
489
|
+
"a failed direct cwd replacement must retain both the old cwd and old prompt descriptor",
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
await writeFile(settingsFile, `${JSON.stringify({ ...persistedAfterSave, appendSystemPromptPath: outsideCandidate, appendSystemPromptRootPath: cwd })}\n`, "utf8");
|
|
494
|
+
const tamperedTab = await request("127.0.0.1", "/api/tabs", { method: "POST", body: { cwd: otherCwd, title: "tampered provenance" } });
|
|
495
|
+
assert.equal(tamperedTab.status, 201, tamperedTab.body?.error);
|
|
496
|
+
latestArgs = (await launches()).at(-1);
|
|
497
|
+
assert.equal(latestArgs.includes(outsideCandidate), false, "a path outside its saved lexical root must not reach child arguments");
|
|
498
|
+
const tamperedDiscovery = await request("127.0.0.1", `/api/append-system-files?tab=${encodeURIComponent(tamperedTab.body?.data?.tab?.id)}`);
|
|
499
|
+
assert.ok(tamperedDiscovery.body?.data?.diagnostics?.some(({ kind, path: diagnosticPath }) => kind === "saved-selection-invalid" && diagnosticPath === outsideCandidate));
|
|
500
|
+
await writeFile(settingsFile, `${JSON.stringify(persistedAfterSave)}\n`, "utf8");
|
|
501
|
+
|
|
502
|
+
if (fileSymlinkAvailable) {
|
|
503
|
+
const replacementTarget = path.join(root, "retargeted-file", "replacement.txt");
|
|
504
|
+
await mkdir(path.dirname(replacementTarget), { recursive: true });
|
|
505
|
+
await writeFile(replacementTarget, "retargeted regular prompt\n", "utf8");
|
|
506
|
+
await rm(fileAliasCandidate);
|
|
507
|
+
await symlink(replacementTarget, fileAliasCandidate, "file");
|
|
508
|
+
const retargetedTab = await request("127.0.0.1", "/api/tabs", { method: "POST", body: { cwd: otherCwd, title: "retargeted symlink selection" } });
|
|
509
|
+
assert.equal(retargetedTab.status, 201, retargetedTab.body?.error);
|
|
510
|
+
latestArgs = (await launches()).at(-1);
|
|
511
|
+
assert.ok(latestArgs.includes(fileAliasCandidate), "a saved visible alias retargeted to another regular file must still reach child arguments");
|
|
512
|
+
await rm(replacementTarget);
|
|
513
|
+
} else {
|
|
514
|
+
await rm(projectCandidate);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
const staleDiscovery = await request("127.0.0.1", route);
|
|
518
|
+
assert.equal(staleDiscovery.body?.data?.appendSystemPromptPath, selectedCandidate, "a broken or deleted saved alias must stay visible for recovery");
|
|
519
|
+
assert.ok(staleDiscovery.body?.data?.diagnostics?.some(({ kind, path: diagnosticPath }) => kind === "saved-selection-invalid" && diagnosticPath === selectedCandidate));
|
|
520
|
+
const staleRejected = await request("127.0.0.1", "/api/append-system-selection", { method: "POST", body: { tabId, path: selectedCandidate } });
|
|
521
|
+
assert.equal(staleRejected.status, 400, "a candidate broken or deleted after save must fail a new selection scan");
|
|
522
|
+
|
|
523
|
+
const staleTab = await request("127.0.0.1", "/api/tabs", { method: "POST", body: { cwd, title: "stale prompt" } });
|
|
524
|
+
assert.equal(staleTab.status, 201, staleTab.body?.error);
|
|
525
|
+
latestArgs = (await launches()).at(-1);
|
|
526
|
+
assert.equal(latestArgs.includes(selectedCandidate), false, "a missing saved path must never be passed as an inline prompt-like argument");
|
|
527
|
+
assert.equal(latestArgs.filter((arg) => arg === "--append-system-prompt").length, 1, "only the explicit launcher override should remain");
|
|
528
|
+
|
|
529
|
+
const cleared = await request("127.0.0.1", "/api/append-system-selection", { method: "POST", body: { tabId, path: null } });
|
|
530
|
+
assert.equal(cleared.status, 200, cleared.body?.error);
|
|
531
|
+
assert.deepEqual({ path: cleared.body?.data?.appendSystemPromptPath, changed: cleared.body?.data?.changed, restartRequired: cleared.body?.data?.restartRequired }, { path: null, changed: true, restartRequired: true });
|
|
532
|
+
const persistedAfterClear = JSON.parse(await readFile(settingsFile, "utf8"));
|
|
533
|
+
assert.equal(persistedAfterClear.appendSystemPromptPath, null);
|
|
534
|
+
assert.equal(persistedAfterClear.appendSystemPromptRootPath, null);
|
|
535
|
+
assert.deepEqual(persistedAfterClear.retainedFixture, { value: 7 });
|
|
536
|
+
|
|
537
|
+
const shutdown = await request("127.0.0.1", "/api/shutdown", { method: "POST", body: {} });
|
|
538
|
+
assert.equal(shutdown.status, 200);
|
|
539
|
+
for (let attempt = 0; attempt < 50 && child.exitCode === null; attempt += 1) await delay(100);
|
|
540
|
+
assert.notEqual(child.exitCode, null, `server should stop after shutdown\n${output}`);
|
|
541
|
+
|
|
542
|
+
const supervisedAgentDir = path.join(root, "supervised-agent");
|
|
543
|
+
const validRestoredPath = path.join(home, ".pi", "agent", "minimal", "APPEND_SYSTEM.md");
|
|
544
|
+
supervisorSeed = await discoverStartAttachRpcSupervisor({
|
|
545
|
+
agentDir: supervisedAgentDir,
|
|
546
|
+
port,
|
|
547
|
+
environment: { ...process.env, HOME: home, USERPROFILE: home, PI_CODING_AGENT_DIR: supervisedAgentDir, APPEND_SYSTEM_LAUNCH_LOG: launchLog },
|
|
548
|
+
});
|
|
549
|
+
const restoredPromptCases = [
|
|
550
|
+
["valid-restored", { kind: "append-system", path: validRestoredPath }, { kind: "append-system", path: validRestoredPath }],
|
|
551
|
+
["old-restored", undefined, null],
|
|
552
|
+
["relative-restored", { kind: "append-system", path: "relative/APPEND_SYSTEM.md" }, null],
|
|
553
|
+
["oversized-restored", { kind: "append-system", path: `/${"x".repeat(4096)}` }, null],
|
|
554
|
+
["newline-restored", { kind: "append-system", path: `${validRestoredPath}\nunsafe` }, null],
|
|
555
|
+
["carriage-return-restored", { kind: "append-system", path: `${validRestoredPath}\runsafe` }, null],
|
|
556
|
+
["tab-restored", { kind: "append-system", path: `${validRestoredPath}\tunsafe` }, null],
|
|
557
|
+
["del-restored", { kind: "append-system", path: `${validRestoredPath}\u007funsafe` }, null],
|
|
558
|
+
["nul-restored", { kind: "append-system", path: `${validRestoredPath}\0unsafe` }, null],
|
|
559
|
+
["unknown-kind-restored", { kind: "system", path: validRestoredPath }, null],
|
|
560
|
+
["extra-field-restored", { kind: "append-system", path: validRestoredPath, contents: "restored secret prompt contents" }, null],
|
|
561
|
+
];
|
|
562
|
+
for (const [id, prompt] of restoredPromptCases) {
|
|
563
|
+
await supervisorSeed.createTab({
|
|
564
|
+
tabId: id,
|
|
565
|
+
metadata: { index: restoredPromptCases.findIndex(([candidate]) => candidate === id) + 1, title: id, cwd, ...(prompt === undefined ? {} : { prompt }) },
|
|
566
|
+
child: { command: process.execPath, args: [fakePiFixture], cwd },
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
output = "";
|
|
571
|
+
child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "0.0.0.0", "--port", String(port), "--pi", fakePi], {
|
|
572
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
573
|
+
env: {
|
|
574
|
+
...process.env,
|
|
575
|
+
HOME: home,
|
|
576
|
+
USERPROFILE: home,
|
|
577
|
+
PI_CODING_AGENT_DIR: supervisedAgentDir,
|
|
578
|
+
PI_WEBUI_SETTINGS_FILE: settingsFile,
|
|
579
|
+
PI_WEBUI_RPC_SUPERVISOR: "1",
|
|
580
|
+
APPEND_SYSTEM_LAUNCH_LOG: launchLog,
|
|
581
|
+
},
|
|
582
|
+
});
|
|
583
|
+
child.stdout.on("data", (chunk) => { output += String(chunk); });
|
|
584
|
+
child.stderr.on("data", (chunk) => { output += String(chunk); });
|
|
585
|
+
health = undefined;
|
|
586
|
+
for (let attempt = 0; attempt < 100; attempt += 1) {
|
|
587
|
+
if (child.exitCode !== null) break;
|
|
588
|
+
try {
|
|
589
|
+
health = await fetch(`${baseUrl}/api/health`, { signal: AbortSignal.timeout(1_000) });
|
|
590
|
+
if (health.status === 200) break;
|
|
591
|
+
} catch {
|
|
592
|
+
}
|
|
593
|
+
await delay(100);
|
|
594
|
+
}
|
|
595
|
+
assert.equal(health?.status, 200, `supervisor hydration server should become healthy\n${output}`);
|
|
596
|
+
const restoredTabsResponse = await request("127.0.0.1", "/api/tabs");
|
|
597
|
+
assert.equal(restoredTabsResponse.status, 200, restoredTabsResponse.body?.error);
|
|
598
|
+
const restoredTabsById = new Map(restoredTabsResponse.body?.data?.tabs?.map((tab) => [tab.id, tab]));
|
|
599
|
+
for (const [id, , expectedPrompt] of restoredPromptCases) {
|
|
600
|
+
assert.deepEqual(restoredTabsById.get(id)?.prompt, expectedPrompt, `${id} must normalize restored prompt metadata fail-closed`);
|
|
601
|
+
}
|
|
602
|
+
assert.equal(JSON.stringify([...restoredTabsById.values()].map((tab) => tab.prompt)).includes("restored secret prompt contents"), false, "malformed restored content-like fields must not reach HTTP prompt metadata");
|
|
603
|
+
|
|
604
|
+
await writeFile(settingsFile, `${JSON.stringify({ appendSystemPromptPath: validRestoredPath, appendSystemPromptRootPath: path.join(home, ".pi") })}\n`, "utf8");
|
|
605
|
+
const supervisedLaunch = await request("127.0.0.1", "/api/tabs", { method: "POST", body: { cwd, title: "supervised selected launch" } });
|
|
606
|
+
assert.equal(supervisedLaunch.status, 201, supervisedLaunch.body?.error);
|
|
607
|
+
assert.deepEqual(supervisedLaunch.body?.data?.tab?.prompt, { kind: "append-system", path: validRestoredPath });
|
|
608
|
+
const supervisorState = await readSupervisorState(await supervisorPaths({ agentDir: supervisedAgentDir, port }));
|
|
609
|
+
const supervisedLaunchMetadata = supervisorState?.tabs?.find((tab) => tab.id === supervisedLaunch.body?.data?.tab?.id)?.metadata;
|
|
610
|
+
assert.deepEqual(supervisedLaunchMetadata?.prompt, { kind: "append-system", path: validRestoredPath }, "successful supervised launches must persist the bounded descriptor with their child metadata");
|
|
611
|
+
|
|
612
|
+
const supervisedShutdown = await request("127.0.0.1", "/api/shutdown", { method: "POST", body: {} });
|
|
613
|
+
assert.equal(supervisedShutdown.status, 200);
|
|
614
|
+
for (let attempt = 0; attempt < 50 && child.exitCode === null; attempt += 1) await delay(100);
|
|
615
|
+
assert.notEqual(child.exitCode, null, `supervisor hydration server should stop after shutdown\n${output}`);
|
|
616
|
+
console.log("append-system-http.test.mjs passed");
|
|
617
|
+
} finally {
|
|
618
|
+
if (child?.exitCode === null) terminateProcessTree(child);
|
|
619
|
+
if (supervisorSeed?.isConnected()) await supervisorSeed.shutdown().catch(() => {});
|
|
620
|
+
supervisorSeed?.close();
|
|
621
|
+
await rm(root, { recursive: true, force: true });
|
|
622
|
+
}
|