@firstpick/pi-package-webui 0.7.2 → 0.7.3

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.
@@ -0,0 +1,54 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const [app, server, watcher, readme] = await Promise.all([
8
+ readFile(join(root, "public", "app.js"), "utf8"),
9
+ readFile(join(root, "bin", "pi-webui.mjs"), "utf8"),
10
+ readFile(join(root, "lib", "git-live-watcher.mjs"), "utf8"),
11
+ readFile(join(root, "README.md"), "utf8"),
12
+ ]);
13
+
14
+ function functionBody(source, name) {
15
+ const syncStart = source.indexOf(`function ${name}(`);
16
+ const asyncStart = source.indexOf(`async function ${name}(`);
17
+ const start = syncStart === -1 ? asyncStart : asyncStart === -1 ? syncStart : Math.min(syncStart, asyncStart);
18
+ assert.notEqual(start, -1, `${name} should be defined`);
19
+ const nextSync = source.indexOf("\nfunction ", start + 1);
20
+ const nextAsync = source.indexOf("\nasync function ", start + 1);
21
+ const candidates = [nextSync, nextAsync].filter((index) => index !== -1);
22
+ return source.slice(start, candidates.length ? Math.min(...candidates) : source.length);
23
+ }
24
+
25
+ const loadRepository = functionBody(app, "loadGitPanelRepository");
26
+ const invalidateRepository = functionBody(app, "invalidateGitPanelRepository");
27
+ const ensureVisibleFresh = functionBody(app, "ensureGitPanelVisibleRepositoriesFresh");
28
+ const handleEvent = functionBody(app, "handleEvent");
29
+
30
+ assert.match(watcher, /watch\(root, \{ recursive: true, persistent: false \}/, "repository watches should be recursive and non-persistent");
31
+ assert.match(watcher, /record\.timer = setTimeout[\s\S]*onChange\(\{ root, changedAt:/, "filesystem bursts should debounce to a repository invalidation");
32
+ assert.match(watcher, /maximumWaitMs[\s\S]*remainingMs[\s\S]*Math\.min\(delayMs, remainingMs\)/, "continuous writes should still invalidate within a bounded maximum wait");
33
+ assert.match(watcher, /record\.tabs:|tabs: new Set\(\)/, "shared roots should track tab subscribers");
34
+ assert.match(watcher, /if \(!record\.tabs\.size\) closeRoot/, "the last tab unsubscribe should close its root watcher");
35
+ assert.match(watcher, /function closeAll\(\)[\s\S]*closeRoot\(root\)/, "server shutdown should release every root watcher");
36
+
37
+ assert.match(server, /createGitLiveWatcher\(\{[\s\S]*type: "webui_git_changed"[\s\S]*broadcastServerEvent/, "watcher changes should use the existing server-wide SSE channel");
38
+ assert.match(server, /env: \{ GIT_OPTIONAL_LOCKS: "0" \}/, "read-only Git commands should not feed optional index refreshes back into the watcher");
39
+ assert.match(server, /trackGitRepositoryForTab\(tab, await getGitRoot\(tab\.cwd\)\)/, "Git-root discovery should register the tab watcher");
40
+ assert.match(server, /trackGitRepositoryForTab\(tab, data\.root\)/, "Git-panel reads should ensure watcher registration");
41
+ assert.match(server, /async function updateTabCwd[\s\S]*gitLiveWatcher\.unsubscribe\(tab\.id\)/, "cwd changes should release old repository subscriptions");
42
+ assert.match(server, /async function closeTab[\s\S]*gitLiveWatcher\.unsubscribe\(tab\.id\)/, "tab closure should release repository subscriptions");
43
+ assert.match(server, /function shutdown[\s\S]*gitLiveWatcher\.closeAll\(\)/, "server shutdown should close all repository watches");
44
+
45
+ assert.match(loadRepository, /existing\?\.loading[\s\S]*refreshPending: true/, "an invalidation during a request should queue a follow-up refresh");
46
+ assert.match(loadRepository, /if \(refreshAgain\) queueMicrotask\(\(\) => loadGitPanelRepository\(card, \{ force: true \}\)\)/, "queued invalidations should trigger one follow-up Git snapshot");
47
+ assert.match(invalidateRepository, /error: ""[\s\S]*loadedAt: 0/, "a fresh SSE invalidation should clear a previous read error and expire the cache");
48
+ assert.match(invalidateRepository, /if \(!gitPanelSectionExpanded\(\)\) return;/, "collapsed Git sections should defer HTTP refresh work");
49
+ assert.match(ensureVisibleFresh, /snapshot\?\.error/, "persistent Git read errors should not cause an unbounded render/reload loop");
50
+ assert.match(ensureVisibleFresh, /gitPanelSnapshotFresh\(snapshot\)[\s\S]*loadGitPanelRepository\(card\)/, "visible stale repositories should refresh on render");
51
+ assert.match(handleEvent, /case "webui_git_changed":[\s\S]*invalidateGitPanelRepository\(event\.root\)/, "the browser event stream should route Git invalidations to the cache");
52
+ assert.match(readme, /live filesystem updates[\s\S]*SSE/, "README should document live watcher-driven Git refresh behavior");
53
+
54
+ console.log("git-panel-live-updates-static.test.mjs passed");
@@ -19,7 +19,7 @@ const renderContextMeter = functionBody("renderContextMeter");
19
19
  const renderWorkspaceDashboard = functionBody("renderWorkspaceDashboard");
20
20
 
21
21
  assert.match(app, /openFolders: new Map\(\)/, "Git panel state should persist folder toggles");
22
- assert.match(renderGitPanelFolder, /const defaultOpen = depth === 0;/, "folder rendering should retain depth-based defaults");
22
+ assert.match(renderGitPanelFolder, /const defaultOpen = true;/, "folder rendering should expand every directory depth by default");
23
23
  assert.match(renderGitPanelFolder, /details\.open = gitPanelState\.openFolders\.has\(folderKey\) \? gitPanelState\.openFolders\.get\(folderKey\) : defaultOpen;/, "folder rendering should prefer a stored override over its default");
24
24
  assert.match(renderGitPanelFolder, /if \(details\.open === defaultOpen\) gitPanelState\.openFolders\.delete\(folderKey\);/, "folder toggles back to the default should remove the override");
25
25
  assert.match(renderGitPanelFolder, /else gitPanelState\.openFolders\.set\(folderKey, details\.open\);/, "folder toggles away from the default should store an override");
@@ -0,0 +1,38 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const testsDir = path.dirname(fileURLToPath(import.meta.url));
7
+ const packageDir = path.resolve(testsDir, "..");
8
+ const [app, server, artifacts] = await Promise.all([
9
+ readFile(path.join(packageDir, "public", "app.js"), "utf8"),
10
+ readFile(path.join(packageDir, "bin", "pi-webui.mjs"), "utf8"),
11
+ readFile(path.join(packageDir, "lib", "git-message-artifacts.mjs"), "utf8"),
12
+ ]);
13
+
14
+ assert.match(server, /async function createGitWorkflowMessageGeneration\(tab\)[\s\S]*id: randomUUID\(\)[\s\S]*baseline: await readStableGitMessageArtifactPair\(paths\)/, "commit generation must capture a server-owned ID and exact two-file baseline");
15
+ assert.match(server, /generationId: messageGeneration\?\.id \|\| ""/, "generation dispatch must return the server correlation ID");
16
+ assert.match(server, /tab\.gitWorkflowMessageGeneration = messageGeneration/, "the generation record must be owned by the originating tab");
17
+ assert.match(server, /case "\/api\/git-workflow\/message"[\s\S]*generationId[\s\S]*tab\?\.gitWorkflowMessageGeneration/, "fresh message reads must resolve the generation from the requested tab");
18
+ assert.match(server, /readGitWorkflowMessages\(cwd, \{ generationId = "", generation = null \} = \{\}\)[\s\S]*generation\.cwd !== messageCwd[\s\S]*expired: true/, "message readiness must reject wrong-ID, wrong-kind, and wrong-cwd generations");
19
+ assert.match(server, /gitMessageArtifactPairReadiness\(generation\.baseline, pair\)[\s\S]*GIT_WORKFLOW_MESSAGE_PAIR_SETTLE_MS[\s\S]*sameGitMessageArtifactPair\(pair, settledPair\)/, "the backend must require both changed artifacts and a stable settled pair");
20
+ assert.doesNotMatch(app, /newestMtime \+ 10000 < currentWorkflow\.messageRequestedAt/, "freshness must not use the previous wall-clock/mtime tolerance");
21
+
22
+ assert.match(app, /const gitWorkflowMessageLoadsByTab = new Map\(\)/, "browser message loading must have tab-scoped single-flight ownership");
23
+ assert.match(app, /messageGenerationId: ""/, "workflow state must retain the active commit-message generation ID");
24
+ assert.match(app, /const generationId = String\(generation\.generationId \|\| ""\)\.trim\(\)[\s\S]*setGitWorkflow\(\{ messageGenerationId: generationId \}/, "the browser must bind the returned generation ID before loading files");
25
+ assert.match(app, /const loadKey = `\$\{expectedRunId\}:\$\{expectedGenerationId \|\| "preview"\}`[\s\S]*existing\?\.key === loadKey[\s\S]*return existing\.promise/, "duplicate timer/resume/agent_end wakeups must reuse one poll promise");
26
+ assert.match(app, /gitWorkflowMessageLoadIsCurrent\(tabId, expectedRunId, expectedGenerationId\)/, "poll results must be guarded by tab, run, and generation identity");
27
+ assert.match(app, /GIT_WORKFLOW_MESSAGE_POLL_TIMEOUT_MS = 30_000[\s\S]*GIT_WORKFLOW_MESSAGE_POLL_DELAYS_MS/, "fresh message polling must be adaptive and bounded");
28
+ assert.match(app, /\?generationId=\$\{encodeURIComponent\(expectedGenerationId\)\}/, "fresh reads must send the correlation ID to the backend");
29
+ assert.match(app, /message\.ready === false[\s\S]*message\.expired[\s\S]*Regenerate/, "pending and expired generation states must remain actionable");
30
+ assert.match(app, /gitWorkflow\.step === "generating"[\s\S]*gitWorkflow\.messageGenerationId[\s\S]*Starting message generation…/, "the refresh action must stay disabled until the server correlation ID is bound");
31
+ assert.match(app, /requireFresh && !expectedGenerationId[\s\S]*workflow\.step === "generating"\) return;/, "early timer and agent_end wakeups must no-op during the generation-ID dispatch window");
32
+ assert.doesNotMatch(app, /loadGitWorkflowMessage\(\{ requireFresh: true, retries:/, "legacy competing retry chains must be removed");
33
+
34
+ assert.match(artifacts, /mtimeNs: String\(stats\.mtimeNs\)[\s\S]*ctimeNs: String\(stats\.ctimeNs\)[\s\S]*sha256: createHash\("sha256"\)/, "artifact snapshots must combine high-resolution metadata with a content hash");
35
+ assert.match(artifacts, /stat\(filePath, \{ bigint: true \}\)[\s\S]*readFile\(filePath\)[\s\S]*stat\(filePath, \{ bigint: true \}\)/, "artifact reads must verify stable metadata around the file read");
36
+ assert.match(artifacts, /for \(const key of \["short", "long"\]\)[\s\S]*unchanged\.push\(key\)[\s\S]*empty\.push\(key\)/, "pair readiness must independently validate both non-empty files");
37
+
38
+ console.log("guided Git message reliability static tests passed");
@@ -1,7 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { spawn, spawnSync } from "node:child_process";
3
3
  import { createServer } from "node:http";
4
- import { chmod, mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from "node:fs/promises";
4
+ import { chmod, mkdir, mkdtemp, readFile, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
5
5
  import { networkInterfaces, tmpdir } from "node:os";
6
6
  import path from "node:path";
7
7
  import { setTimeout as delay } from "node:timers/promises";
@@ -305,6 +305,39 @@ try {
305
305
  const tabId = tabList[0].id;
306
306
  assert.ok(tabId, "tab should have an id");
307
307
 
308
+ const malformedInlineImage = await request("127.0.0.1", "/api/prompt", {
309
+ method: "POST",
310
+ body: { tab: tabId, message: "malformed inline image fixture", images: [{ type: "image", mimeType: "image/png", data: "137,80,78,71,13,10,26,10" }] },
311
+ });
312
+ assert.equal(malformedInlineImage.status, 400, "comma-separated image bytes should be rejected before RPC dispatch");
313
+ assert.match(String(malformedInlineImage.body?.error || ""), /image 1 data must be canonical base64/i);
314
+
315
+ const unpaddedInlineImage = await request("127.0.0.1", "/api/prompt", {
316
+ method: "POST",
317
+ body: { tab: tabId, message: "unpadded inline image fixture", images: [{ type: "image", mimeType: "image/png", data: "iVBORw0KGgo" }] },
318
+ });
319
+ assert.equal(unpaddedInlineImage.status, 400, "non-canonical unpadded image base64 should be rejected before RPC dispatch");
320
+ assert.match(String(unpaddedInlineImage.body?.error || ""), /image 1 data must be canonical base64/i);
321
+
322
+ const malformedAttachment = await request("127.0.0.1", "/api/attachments", {
323
+ method: "POST",
324
+ body: { tab: tabId, files: [{ id: "bad-image", name: "bad.png", mimeType: "image/png", data: "137,80,78,71" }] },
325
+ });
326
+ assert.equal(malformedAttachment.status, 400, "malformed attachment data should be rejected before a file is written");
327
+ assert.match(String(malformedAttachment.body?.error || ""), /attachment data must be canonical base64/i);
328
+
329
+ const canonicalPng = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).toString("base64");
330
+ const validInlineImage = await request("127.0.0.1", "/api/prompt", {
331
+ method: "POST",
332
+ body: { tab: tabId, message: "canonical inline image fixture", images: [{ type: "image", mimeType: "image/png", data: canonicalPng }] },
333
+ });
334
+ assert.equal(validInlineImage.status, 200, `canonical inline image should reach Pi unchanged: ${validInlineImage.body?.error || ""}`);
335
+ const imageCommands = (await readFile(fakePiCommandLog, "utf8")).trim().split(/\r?\n/).filter(Boolean).map((line) => JSON.parse(line));
336
+ assert.equal(imageCommands.some((entry) => entry.direction === "command" && entry.message === "malformed inline image fixture"), false, "malformed inline images must not reach Pi");
337
+ assert.equal(imageCommands.some((entry) => entry.direction === "command" && entry.message === "unpadded inline image fixture"), false, "non-canonical inline images must not reach Pi");
338
+ const validImageCommand = imageCommands.find((entry) => entry.direction === "command" && entry.message === "canonical inline image fixture");
339
+ assert.deepEqual(validImageCommand?.images, [{ type: "image", data: canonicalPng, mimeType: "image/png" }], "canonical image bytes and MIME type should be forwarded unchanged");
340
+
308
341
  const optionalFeatures = await request("127.0.0.1", "/api/optional-features");
309
342
  assert.equal(optionalFeatures.status, 200, "optional feature status should load");
310
343
  const aurReviewFeature = optionalFeatures.body?.data?.features?.find((feature) => feature.featureId === "aurReview");
@@ -847,6 +880,15 @@ try {
847
880
  assert.equal(gitRoot.body?.ok, true, "git-root endpoint should discover the tab repository");
848
881
  assert.equal(gitRoot.body?.data?.root, stagingRepo, "git-root should return the canonical fixture root");
849
882
 
883
+ const liveFile = path.join(stagingRepo, "live-update.txt");
884
+ const renamedLiveFile = path.join(stagingRepo, "live-update-renamed.txt");
885
+ const isLiveGitEvent = (event) => event.type === "webui_git_changed" && event.root === stagingRepo;
886
+ const createdLiveEvent = await waitForSseEvent(stagingTab, isLiveGitEvent, () => writeFile(liveFile, "created\n"));
887
+ assert.match(createdLiveEvent.event.changedAt || "", /^\d{4}-\d{2}-\d{2}T/, "file creation should broadcast a timestamped Git invalidation");
888
+ await waitForSseEvent(stagingTab, isLiveGitEvent, () => writeFile(liveFile, "modified\n"));
889
+ await waitForSseEvent(stagingTab, isLiveGitEvent, () => rename(liveFile, renamedLiveFile));
890
+ await waitForSseEvent(stagingTab, isLiveGitEvent, () => rm(renamedLiveFile));
891
+
850
892
  const gitPanel = await request("127.0.0.1", `/api/git-panel?tab=${encodeURIComponent(stagingTab)}`);
851
893
  assert.equal(gitPanel.body?.ok, true, "git-panel endpoint should return compact local status and history");
852
894
  assert.equal(gitPanel.body?.data?.root, stagingRepo);
@@ -1285,7 +1327,7 @@ try {
1285
1327
  await writeFile(path.join(cwd, "interactive-runner.mjs"), [
1286
1328
  "import readline from 'node:readline';",
1287
1329
  "const rl = readline.createInterface({ input: process.stdin, output: process.stdout });",
1288
- "console.log('interactive ready');",
1330
+ "console.log(`interactive ready; stdin tty=${Boolean(process.stdin.isTTY)}`);",
1289
1331
  "rl.question('name? ', (answer) => {",
1290
1332
  " console.log(`hello ${answer}`);",
1291
1333
  " rl.close();",
@@ -1306,6 +1348,9 @@ try {
1306
1348
  timeoutMs: 10_000,
1307
1349
  });
1308
1350
  assert.equal(interactiveRunStart.status, 200, `interactive runner start should return ok: ${interactiveRunStart.body?.error || ""}`);
1351
+ if (process.platform === "win32") {
1352
+ assert.equal(interactiveRunStart.body?.data?.activeRun?.executionMode, "conpty", "Windows interactive runners should use the node-pty ConPTY backend");
1353
+ }
1309
1354
  let interactiveRunState = interactiveRunStart;
1310
1355
  for (let attempt = 0; attempt < 50; attempt++) {
1311
1356
  interactiveRunState = await request("127.0.0.1", `/api/app-runners?tab=${encodeURIComponent(tabId)}`, { timeoutMs: 5_000 });
@@ -1334,13 +1379,14 @@ try {
1334
1379
  assert.equal(interactiveRunState.body?.data?.activeRun?.status, "done", "interactive custom runner should finish after stdin");
1335
1380
  const interactiveOutput = (interactiveRunState.body?.data?.activeRun?.lines || []).join("\n");
1336
1381
  assert.match(interactiveOutput, /hello webui/, "interactive custom runner should receive stdin from the app-runner input endpoint");
1382
+ if (process.platform === "win32") assert.match(interactiveOutput, /stdin tty=true/, "Windows ConPTY runners should expose a real TTY to the child process");
1337
1383
  assert.match(interactiveOutput, /# stdin sent \(5 chars\) and closed/, "app runner output should show that stdin was sent without echoing the input text itself");
1338
1384
  await request("127.0.0.1", "/api/app-runner/clear", { method: "POST", body: { tab: tabId } });
1339
1385
 
1340
1386
  const scriptVersion = spawnSync("script", ["--version"], { encoding: "utf8" });
1341
1387
  const utilLinuxScriptAvailable = process.platform !== "win32" && scriptVersion.status === 0 && /util-linux/i.test(`${scriptVersion.stdout}\n${scriptVersion.stderr}`);
1342
1388
  const bashAvailable = spawnSync("bash", ["--version"], { encoding: "utf8" }).status === 0;
1343
- if (utilLinuxScriptAvailable && bashAvailable) {
1389
+ if ((utilLinuxScriptAvailable || process.platform === "win32") && bashAvailable) {
1344
1390
  await mkdir(path.join(cwd, "qa"), { recursive: true });
1345
1391
  await writeFile(path.join(cwd, "qa", "read-p-runner.sh"), [
1346
1392
  "#!/usr/bin/env bash",
@@ -1363,7 +1409,8 @@ try {
1363
1409
  timeoutMs: 10_000,
1364
1410
  });
1365
1411
  assert.equal(readPromptStart.status, 200, `bash read -p runner start should return ok: ${readPromptStart.body?.error || ""}`);
1366
- assert.equal(readPromptStart.body?.data?.activeRun?.executionMode, "pty", "bash read -p runner should use the PTY-backed execution path when util-linux script is available");
1412
+ const expectedPtyMode = process.platform === "win32" ? "conpty" : "pty";
1413
+ assert.equal(readPromptStart.body?.data?.activeRun?.executionMode, expectedPtyMode, "bash read -p runner should use the platform PTY-backed execution path");
1367
1414
  let readPromptState = readPromptStart;
1368
1415
  for (let attempt = 0; attempt < 50; attempt++) {
1369
1416
  readPromptState = await request("127.0.0.1", `/api/app-runners?tab=${encodeURIComponent(tabId)}`, { timeoutMs: 5_000 });
@@ -1392,7 +1439,7 @@ try {
1392
1439
  assert.equal(readPromptState.body?.data?.activeRun?.status, "done", "bash read -p runner should finish after stdin");
1393
1440
  const readPromptOutput = (readPromptState.body?.data?.activeRun?.lines || []).join("\n");
1394
1441
  assert.match(readPromptOutput, /selected:alpha/, "bash read -p runner should receive stdin from the app-runner input endpoint");
1395
- assert.doesNotMatch(readPromptOutput, /^alpha$/m, "PTY-backed app runner should not echo raw stdin into captured output");
1442
+ if (process.platform !== "win32") assert.doesNotMatch(readPromptOutput, /^alpha$/m, "script-backed PTY runner should not echo raw stdin into captured output");
1396
1443
  await request("127.0.0.1", "/api/app-runner/clear", { method: "POST", body: { tab: tabId } });
1397
1444
  }
1398
1445
 
@@ -0,0 +1,115 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { chmod, mkdtemp, readFile, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import path from "node:path";
6
+ import { setTimeout as delay } from "node:timers/promises";
7
+ import { dirname, join } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
11
+ const serverScript = join(root, "bin", "pi-webui.mjs");
12
+ const fakePi = join(root, "tests", "fixtures", "fake-pi.mjs");
13
+ const port = 32000 + Math.floor(Math.random() * 20000);
14
+ const cwd = await mkdtemp(path.join(tmpdir(), "pi-webui-image-payload-"));
15
+ const commandLog = path.join(cwd, "fake-pi-commands.jsonl");
16
+ let child;
17
+
18
+ async function request(pathname, { method = "GET", body, timeoutMs = 5_000 } = {}) {
19
+ const response = await fetch(`http://127.0.0.1:${port}${pathname}`, {
20
+ method,
21
+ headers: body === undefined ? undefined : { "content-type": "application/json" },
22
+ body: body === undefined ? undefined : JSON.stringify(body),
23
+ signal: AbortSignal.timeout(timeoutMs),
24
+ });
25
+ return { status: response.status, body: await response.json().catch(() => undefined) };
26
+ }
27
+
28
+ async function stopChild() {
29
+ if (!child || child.exitCode !== null || child.signalCode !== null) return;
30
+ const exited = new Promise((resolve) => child.once("exit", resolve));
31
+ child.kill("SIGKILL");
32
+ await exited;
33
+ }
34
+
35
+ async function cleanup() {
36
+ await stopChild();
37
+ for (let attempt = 0; attempt < 8; attempt++) {
38
+ try {
39
+ await rm(cwd, { recursive: true, force: true });
40
+ return;
41
+ } catch (error) {
42
+ if (!["EBUSY", "EPERM", "ENOTEMPTY"].includes(error?.code) || attempt === 7) throw error;
43
+ await delay(100 * (attempt + 1));
44
+ }
45
+ }
46
+ }
47
+
48
+ try {
49
+ await chmod(fakePi, 0o755);
50
+ let output = "";
51
+ child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
52
+ stdio: ["ignore", "pipe", "pipe"],
53
+ env: {
54
+ ...process.env,
55
+ PI_CODING_AGENT_DIR: path.join(cwd, "agent"),
56
+ FAKE_PI_LOG_FILE: commandLog,
57
+ },
58
+ });
59
+ child.stdout.on("data", (chunk) => { output += String(chunk); });
60
+ child.stderr.on("data", (chunk) => { output += String(chunk); });
61
+
62
+ let health;
63
+ for (let attempt = 0; attempt < 100; attempt++) {
64
+ if (child.exitCode !== null) break;
65
+ try {
66
+ health = await request("/api/health", { timeoutMs: 1_000 });
67
+ if (health.status === 200) break;
68
+ } catch {
69
+ // Server is still starting.
70
+ }
71
+ await delay(50);
72
+ }
73
+ assert.equal(health?.status, 200, `server should become healthy:\n${output}`);
74
+ const tabs = await request("/api/tabs");
75
+ const tabId = tabs.body?.data?.tabs?.[0]?.id;
76
+ assert.ok(tabId, "server should create a tab");
77
+
78
+ const malformedInline = await request("/api/prompt", {
79
+ method: "POST",
80
+ body: { tab: tabId, message: "malformed inline image fixture", images: [{ type: "image", mimeType: "image/png", data: "137,80,78,71,13,10,26,10" }] },
81
+ });
82
+ assert.equal(malformedInline.status, 400);
83
+ assert.match(String(malformedInline.body?.error || ""), /image 1 data must be canonical base64/i);
84
+
85
+ const unpaddedInline = await request("/api/prompt", {
86
+ method: "POST",
87
+ body: { tab: tabId, message: "unpadded inline image fixture", images: [{ type: "image", mimeType: "image/png", data: "iVBORw0KGgo" }] },
88
+ });
89
+ assert.equal(unpaddedInline.status, 400);
90
+ assert.match(String(unpaddedInline.body?.error || ""), /image 1 data must be canonical base64/i);
91
+
92
+ const malformedAttachment = await request("/api/attachments", {
93
+ method: "POST",
94
+ body: { tab: tabId, files: [{ id: "bad-image", name: "bad.png", mimeType: "image/png", data: "137,80,78,71" }] },
95
+ });
96
+ assert.equal(malformedAttachment.status, 400);
97
+ assert.match(String(malformedAttachment.body?.error || ""), /attachment data must be canonical base64/i);
98
+
99
+ const canonicalPng = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).toString("base64");
100
+ const validInline = await request("/api/prompt", {
101
+ method: "POST",
102
+ body: { tab: tabId, message: "canonical inline image fixture", images: [{ type: "image", mimeType: "image/png", data: canonicalPng }] },
103
+ });
104
+ assert.equal(validInline.status, 200, validInline.body?.error || "canonical image should be accepted");
105
+
106
+ const commands = (await readFile(commandLog, "utf8")).trim().split(/\r?\n/).filter(Boolean).map((line) => JSON.parse(line));
107
+ assert.equal(commands.some((entry) => entry.direction === "command" && entry.message === "malformed inline image fixture"), false);
108
+ assert.equal(commands.some((entry) => entry.direction === "command" && entry.message === "unpadded inline image fixture"), false);
109
+ const validCommand = commands.find((entry) => entry.direction === "command" && entry.message === "canonical inline image fixture");
110
+ assert.deepEqual(validCommand?.images, [{ type: "image", data: canonicalPng, mimeType: "image/png" }]);
111
+ } finally {
112
+ await cleanup();
113
+ }
114
+
115
+ console.log("image payload hardening harness passed");
@@ -39,17 +39,17 @@ const companionDependencies = {
39
39
  "@firstpick/pi-extension-bang-command-autocomplete": "^0.2.1",
40
40
  "@firstpick/pi-extension-btw": "^0.1.3",
41
41
  "@firstpick/pi-extension-fish-user-bash": "^0.2.1",
42
- "@firstpick/pi-extension-git-footer-status": "^0.4.0",
42
+ "@firstpick/pi-extension-git-footer-status": "^0.4.1",
43
43
  "@firstpick/pi-extension-release-aur": "^0.1.7",
44
- "@firstpick/pi-extension-release-npm": "^0.4.1",
44
+ "@firstpick/pi-extension-release-npm": "^0.4.3",
45
45
  "@firstpick/pi-extension-safety-guard": "^0.2.5",
46
46
  "@firstpick/pi-extension-setup-skills": "^0.1.8",
47
47
  "@firstpick/pi-extension-stats": "^0.2.8",
48
48
  "@firstpick/pi-extension-todo-progress": "^0.2.8",
49
49
  "@firstpick/pi-extension-tools": "^0.1.6",
50
- "@firstpick/pi-extension-workflows": "^0.1.3",
51
- "@firstpick/pi-package-remote-webui": "^0.1.5",
52
- "@firstpick/pi-prompts-git-pr": "^0.1.3",
50
+ "@firstpick/pi-extension-workflows": "^0.1.4",
51
+ "@firstpick/pi-package-remote-webui": "^0.1.6",
52
+ "@firstpick/pi-prompts-git-pr": "^0.1.4",
53
53
  "@firstpick/pi-themes-bundle": "^0.1.4",
54
54
  };
55
55
 
@@ -137,7 +137,7 @@ assert.doesNotMatch(app, /function renderGitPanelGroup\(/, "Git panel should not
137
137
  assert.match(app, /function gitPanelContextMenuItems\(context\)[\s\S]*kind === "repository"[\s\S]*"View Diff"[\s\S]*"Stage All"[\s\S]*"Unstage All"[\s\S]*"Discard changes…"[\s\S]*"Delete file…"/, "repository and path actions should be provided by the Git context menu");
138
138
  assert.match(app, /function bindGitPanelContextMenu\(trigger, context\)[\s\S]*"contextmenu"[\s\S]*"ContextMenu"[\s\S]*event\.shiftKey && event\.key === "F10"/, "Git context actions should support right click and keyboard-equivalent invocation");
139
139
  assert.doesNotMatch(app, /git-side-panel-file-actions|git-side-panel-toolbar-actions|git-side-panel-stage-select|gitPanelSmallButton/, "Git rows should not render the removed inline action controls");
140
- assert.match(app, /function renderGitPanelFolder\(node, card, category, depth = 0\)[\s\S]*const defaultOpen = depth === 0[\s\S]*details\.open =[\s\S]*git-side-panel-folder-chevron[\s\S]*aria-hidden/, "Git folders should render an explicit decorative disclosure arrow");
140
+ assert.match(app, /function renderGitPanelFolder\(node, card, category, depth = 0\)[\s\S]*const defaultOpen = true[\s\S]*details\.open = gitPanelState\.openFolders\.has\(folderKey\) \? gitPanelState\.openFolders\.get\(folderKey\) : defaultOpen[\s\S]*details\.open === defaultOpen[\s\S]*gitPanelState\.openFolders\.set\(folderKey, details\.open\)[\s\S]*git-side-panel-folder-chevron[\s\S]*aria-hidden/, "Git folders should start expanded at every depth while retaining explicit user collapse overrides");
141
141
  assert.match(css, /\.git-side-panel-folder-chevron[\s\S]*transform: rotate\(0deg\)[\s\S]*\.git-side-panel-folder\[open\][\s\S]*transform: rotate\(90deg\)/, "Git folder arrows should indicate collapsed and expanded states");
142
142
  assert.match(css, /\.git-side-panel-repository[\s\S]*\.git-side-panel-file[\s\S]*grid-template-columns: 1\.3rem minmax\(5rem, 1fr\) auto[\s\S]*\.git-side-panel-context-menu[\s\S]*\.git-side-panel-commit/, "Git side panel should prioritize filename width and style repository, context-menu, and history surfaces");
143
143
  assert.match(server, /async function readGitPanel\(cwd\)[\s\S]*GIT_PANEL_HISTORY_LIMIT[\s\S]*"status", "--porcelain=v1", "-z"[\s\S]*"--numstat", "-z"/, "server should build compact bounded local Git snapshots without full file contents");
@@ -330,6 +330,8 @@ assert.match(css, /button\.composer-skill-tag:hover,[\s\S]*?button\.composer-ski
330
330
  assert.match(css, /\.extension-dialog\.skill-editor-dialog \{[\s\S]*?--skill-editor-size:\s*min\(152rem[\s\S]*?width:\s*var\(--skill-editor-size\);[\s\S]*?height:\s*var\(--skill-editor-size\);[\s\S]*?aspect-ratio:\s*1 \/ 1/, "skill editor should use a square viewport-bounded modal layout");
331
331
  assert.match(css, /\.skill-editor-dialog form \{[\s\S]*?height:\s*100%;[\s\S]*?min-height:\s*0/, "skill editor form should fill the square modal without forcing overflow");
332
332
  assert.match(css, /\.skill-editor-text \{[\s\S]*?overflow-x:\s*hidden;[\s\S]*?overflow-wrap:\s*anywhere;[\s\S]*?white-space:\s*pre-wrap/, "skill editor text should wrap long lines instead of horizontal scrolling");
333
+ assert.match(html, /<textarea id="fileViewerEditor"[^>]*\bwrap="soft"/, "file viewer source mode should enable soft wrapping");
334
+ assert.match(css, /\.file-viewer-editor \{[\s\S]*?overflow-x:\s*hidden;[\s\S]*?overflow-y:\s*auto;[\s\S]*?overflow-wrap:\s*anywhere;[\s\S]*?white-space:\s*pre-wrap/, "file viewer source mode should wrap long lines to the available preview width");
333
335
  assert.match(css, /\.composer-busy-mode-menu \{[\s\S]*?bottom:\s*calc\(100% \+ 0\.22rem\);[\s\S]*?background:\s*var\(--ctp-crust\)/, "busy prompt behavior dropdown should expand above the tag with an opaque background");
334
336
  assert.match(css, /\.sticky-user-prompt-button \{[\s\S]*?grid-template-columns:\s*auto minmax\(0, 1fr\) auto/, "last-user-prompt jump control should render as a fixed transcript header");
335
337
  assert.match(css, /@media \(max-width: 720px\), \(max-device-width: 720px\), \(pointer: coarse\) and \(hover: none\)[\s\S]*?\.sticky-user-prompt-button \{\n\s+grid-template-columns:\s*minmax\(0, 1fr\) auto;\n\s+min-height:\s*36px;[\s\S]*?\.sticky-user-prompt-text \{[\s\S]*?font-size:\s*var\(--text-xs\)/, "mobile last-user-prompt card should preserve compact height while respecting the text floor");
@@ -408,6 +410,7 @@ assert.match(css, /\.release-npm-stream-header \{[\s\S]*?text-transform:\s*upper
408
410
  assert.match(css, /\.release-npm-output-summary \{[\s\S]*?cursor:\s*pointer/, "release-npm output should expose a local expand/collapse summary");
409
411
  assert.match(css, /\.release-npm-output-details\[open\] \.release-npm-output-toggle/, "release-npm expanded output should rotate the summary chevron");
410
412
  assert.match(css, /\.widget-area:has\(\.release-npm-live-widget \.release-npm-output-details\[open\]\)[\s\S]*?flex:\s*0 0 min\(44rem, 68dvh\)/, "live release output should reserve a stable widget slot instead of resizing the transcript while streaming");
413
+ assert.match(css, /\.widget-area:has\(\.workflow-widget\) \{[\s\S]*?flex:\s*0 1 auto;[\s\S]*?max-height:\s*min\(34rem, 52dvh\);[\s\S]*?overflow:\s*auto/, "workflow widgets should stay within a scrollable output-sized slot so the composer and footer remain visible");
411
414
  assert.match(css, /\.release-npm-live-widget \.release-npm-output-details\[open\] \.release-npm-terminal,[\s\S]*?height:\s*clamp\(15rem, 42dvh, 31rem\)/, "live release terminals should keep a fixed viewport height while output streams");
412
415
  assert.match(css, /\.release-npm-terminal \{[\s\S]*?rgba\(3, 4, 10, 0\.98\)/, "release-npm terminal should use a high-contrast stream panel");
413
416
  assert.match(css, /\.release-aur-widget \{[\s\S]*?border-color/, "release-aur output should render as a specialized Web UI widget variant");
@@ -517,7 +520,10 @@ assert.match(css, /\.git-current-file-header \{[\s\S]*?position:\s*sticky[\s\S]*
517
520
  assert.match(css, /\.git-changes-file-list \{[\s\S]*?grid-template-columns:\s*repeat\(2, minmax\(0, 1fr\)\)/, "git changes modal should show changed-file jump buttons in two columns without horizontal scrolling");
518
521
  assert.match(css, /\.git-diff-grid \{[\s\S]*?grid-template-columns:\s*3\.8rem minmax\(22rem, 1fr\) 3\.8rem minmax\(22rem, 1fr\)/, "git changes modal should render a side-by-side diff grid");
519
522
  assert.match(html, /id="gitChangesDialog"[\s\S]*id="gitChangesRefreshButton"[\s\S]*id="gitChangesPullButton"[\s\S]*id="gitChangesBody"/, "git changes modal should expose refresh, pull controls, and a diff body");
520
- assert.match(app, /chip\.key === "changes"[\s\S]*?options\.onClick = openGitChangesDialog/, "footer CHANGES chip should open the git changes modal");
523
+ assert.match(app, /chip\.key === "changes"[\s\S]*?options\.onClick = \(\) => openGitChangesDialog\(tab\?\.id \|\| activeTabId\)/, "footer CHANGES chip should pass its tab ID without forwarding the browser click event");
524
+ assert.match(app, /chip\.key === "git-state"[\s\S]*?options\.onClick = \(\) => openGitChangesDialog\(tab\?\.id \|\| activeTabId\)/, "footer git-state chip should pass its tab ID without forwarding the browser click event");
525
+ assert.match(app, /function openGitChangesDialog\(requestedTabId = activeTabId\)[\s\S]*?typeof requestedTabId === "string" && requestedTabId \? requestedTabId : activeTabId/, "git changes dialog should reject event objects and other non-string tab IDs defensively");
526
+ assert.doesNotMatch(app, /options\.onClick = openGitChangesDialog/, "git changes handlers must not forward click events as tab IDs");
521
527
  assert.match(app, /async function loadGitChangesDialog[\s\S]*api\("\/api\/git-changes"/, "git changes modal should load diff data from the server endpoint");
522
528
  assert.match(app, /"Resolve with agent"[\s\S]*api\("\/api\/git-operation\/resolve-with-agent", \{ method: "POST"[\s\S]*switchToResponseTab\(response\)/, "conflict panel should open the resolution agent in the new tab returned by the server");
523
529
  assert.match(server, /function gitConflictResolutionAgentPrompt\(operation\)[\s\S]*Conflicted files:[\s\S]*Do not continue, skip, abort, commit, reset, or push[\s\S]*diff-filter=U is empty/, "server should build a bounded conflict handoff with operation safety and verification instructions");
@@ -545,6 +551,7 @@ assert.match(css, /\.footer-model-picker[\s\S]*?position:\s*absolute[\s\S]*?left
545
551
  assert.match(css, /@media \(max-width: 720px\), \(max-device-width: 720px\), \(pointer: coarse\) and \(hover: none\)[\s\S]*?\.footer-model-picker \{[\s\S]*?position:\s*fixed/, "mobile footer model picker should escape footer-details stacking as a fixed overlay on narrow, device-width-narrow, or touch-only devices");
546
552
  assert.match(css, /bottom:\s*var\(--footer-model-picker-bottom/, "mobile footer model picker should be anchored by a JS-computed viewport offset");
547
553
  assert.match(css, /\.footer-model-option\.active/, "footer model picker should style the selected scoped model");
554
+ assert.match(css, /\.model-search-result-main,\n\.model-search-result-name \{[\s\S]*?line-height:\s*1\.3;/, "side-panel model titles should reserve enough line height to avoid clipping heavy font glyphs");
548
555
  assert.match(app, /async function createPathPickerDirectory\(\)/, "cwd picker should implement create-directory behavior in the browser");
549
556
  assert.match(app, /function renderPathPickerDirectoryList\(\)[\s\S]*pathPickerDirectoryMatchesSearch/, "cwd picker should filter current-directory entries in the browser");
550
557
  assert.match(app, /elements\.pathPickerSearchInput\.addEventListener\("input", renderPathPickerDirectoryList\)/, "cwd picker should update directory matches as the user types");
@@ -885,7 +892,10 @@ assert.match(app, /function parseGitFooterWebuiPayloadRaw\(raw\)[\s\S]*GIT_FOOTE
885
892
  assert.match(app, /function normalizeFooterPayloadChangedFile\(value\)[\s\S]*FOOTER_CHANGED_FILE_KINDS\.has\(value\.kind\)[\s\S]*oldPath/, "git footer payload parsing should preserve changed-file details for changes popovers");
886
893
  assert.match(app, /const files = value\.files\.map\(normalizeFooterPayloadChangedFile\)\.filter\(Boolean\)\.slice\(0, 80\);[\s\S]*chip\.files = files;/, "git footer payload chips should retain bounded changed-file lists");
887
894
  assert.match(app, /FOOTER_PAYLOAD_ACTIONS = new Set\(\["calibrate-current", "calibrate-probe"\]\)[\s\S]*chip\.action = value\.action;/, "git footer payload chips should preserve allowlisted actions such as PI calibration");
888
- assert.match(app, /async function runGitFooterPiCalibration\(mode = "current", tabContext = activeTabContext\(\)\)[\s\S]*resolveAvailableCommandName\("calibrate", \{ rpcOnly: true \}\)[\s\S]*mode === "probe" \? `\/\$\{commandName\}` : `\/\$\{commandName\} current`[\s\S]*scheduleGitFooterPiCalibrationRefresh\(tabContext, mode === "probe" \? \[5000, 14000\] : \[600, 1600\]\)/, "clicking an uncalibrated PI footer chip should run current/probe calibration and refresh the git footer value");
895
+ assert.match(app, /async function runGitFooterPiCalibration\(tabContext = activeTabContext\(\)\)[\s\S]*resolveAvailableCommandName\("calibrate", \{ rpcOnly: true \}\)[\s\S]*sendPrompt\("prompt", `\/\$\{commandName\}`[\s\S]*scheduleGitFooterPiCalibrationRefresh\(tabContext\)/, "clicking the PI footer chip should dispatch exactly /calibrate and schedule a refreshed footer value");
896
+ assert.match(app, /function applyGitFooterPiCalibrationOptions\(chip, options\) \{\s+if \(chip\?\.key !== "pi"\) return "";[\s\S]*void runGitFooterPiCalibration\(\)/, "every PI footer chip should remain clickable regardless of payload calibration action metadata");
897
+ assert.doesNotMatch(app.match(/async function runGitFooterPiCalibration[\s\S]*?\n\}/)?.[0] || "", /commandName\} current|appConfirmText/, "PI footer calibration should neither append the current-mode argument nor open a probe confirmation dialog");
898
+
889
899
  assert.match(app, /title: cleanFooterPayloadText\(value\.title, "", 4000\)/, "git footer tooltip titles should preserve long cwd paths instead of truncating at chip display length");
890
900
  assert.match(app, /const sourceTitle = cleanFooterPayloadText\(chip\?\.title, "", 4000\)/, "git footer tooltip rendering should keep full source titles for long cwd paths");
891
901
  assert.match(app, /function renderFooter\(\)[\s\S]*parseGitFooterWebuiPayload\(\)[\s\S]*renderGitFooterPayload\(footerPayloadWithLiveModel\(gitFooterPayload\)\)/, "detailed footer rendering should prefer the git-footer-status extension payload");
@@ -1011,10 +1021,14 @@ assert.match(app, /function renderWorkflowInspectorWidget\(\)[\s\S]*workflow-ins
1011
1021
  assert.match(app, /function renderWorkflowInspectorAgent\(agent, run\)[\s\S]*Prompt[\s\S]*Recent activity[\s\S]*Result and usage[\s\S]*Retry agent/, "agent drilldown should expose prompt, activity, result, usage, and retry");
1012
1022
  assert.match(app, /canPause[\s\S]*`\/workflow pause \$\{run\.runId\}`[\s\S]*canAbort[\s\S]*`\/workflow abort \$\{run\.runId\}`[\s\S]*Save user[\s\S]*Save project[\s\S]*Raw workflow script/, "WebUI Workflow controls should send canonical extension commands and expose raw scripts");
1013
1023
  assert.match(app, /confirmMessage && !window\.confirm\(confirmMessage\)/, "destructive WebUI Workflow actions should require browser confirmation");
1014
- assert.match(app, /const workflowInspectorByTab = new Map\(\)[\s\S]*workflowInspectorSelectionByTab = new Map\(\)/, "Workflow inspector state and drilldown selection should be per tab");
1024
+ assert.match(app, /const workflowInspectorByTab = new Map\(\)[\s\S]*workflowInspectorSelectionByTab = new Map\(\)[\s\S]*workflowInspectorMinimizedByTab = new Set\(\)/, "Workflow inspector run, selection, and minimized state should be per tab");
1025
+ assert.match(app, /function workflowInspectorSetMinimized\(minimized\)[\s\S]*workflowInspectorMinimizedByTab\.(?:add|delete)[\s\S]*renderWidgets\(\)[\s\S]*requestAnimationFrame[\s\S]*workflow-inspector-minimize-button[\s\S]*focus\(\{ preventScroll: true \}\)/, "Workflow inspector minimize state should survive rerenders and restore focus to the replacement control");
1026
+ assert.match(app, /function renderWorkflowInspectorWidget\(\)[\s\S]*workflow-inspector-body[\s\S]*workflow-inspector-minimize-button[\s\S]*minimized \? "Restore" : "Minimize"[\s\S]*minimizeButton\.type = "button"[\s\S]*aria-controls[\s\S]*aria-expanded[\s\S]*aria-label[\s\S]*if \(minimized\) return node/, "Workflow inspector should expose an accessible minimize and restore disclosure control");
1027
+ assert.match(app, /workflowInspectorMinimizedByTab\.delete\(tabId\)/, "closing a terminal tab should discard its Workflow inspector minimize state");
1015
1028
  assert.match(app, /handleInactiveTabEvent\(event\)[\s\S]*WORKFLOW_INSPECTOR_WIDGET_KEY[\s\S]*updateWorkflowInspectorForTab\(event\.tabId, inspector\)[\s\S]*renderTabs\(\)/, "inactive tabs should consume replayed Workflow inspector payloads for badges");
1016
1029
  assert.match(app, /terminal-tab-workflow-indicator[\s\S]*workflowRunningCountForTab/, "terminal tabs should display Workflow Mode or active-run badges");
1017
1030
  assert.match(css, /\.workflow-inspector-layout \{[\s\S]*grid-template-columns:[\s\S]*\.workflow-inspector-run-list[\s\S]*\.workflow-inspector-agent/, "Workflow inspector should have responsive run and agent layout styling");
1031
+ assert.match(css, /\.workflow-inspector-widget\.minimized \{[\s\S]*\.workflow-inspector-minimize-button/, "Workflow inspector should style its minimized state and toggle control");
1018
1032
  assert.match(css, /\.terminal-tab-workflow-indicator \{[\s\S]*color: var\(--ctp-mauve\)/, "inactive-tab Workflow badges should have a distinct accessible style");
1019
1033
  assert.match(css, /\.composer-workflow-mode-button\.active,[\s\S]*aria-pressed="true"/, "active Workflow Mode toggle should have persistent pressed styling");
1020
1034
  assert.match(css, /\.composer\.workflow-mode-active[\s\S]*body\.workflow-mode-active \.composer::before/, "active Workflow Mode should visibly accent the composer");
@@ -1282,6 +1296,7 @@ assert.match(app, /case "agent_end":[\s\S]*?clearRunIndicatorActivity\(\)/, "age
1282
1296
  assert.match(app, /case "agent_end":[\s\S]*?notifyAgentDone\(event\.tabId \|\| activeTabId/, "agent completion should trigger optional done notifications");
1283
1297
  assert.match(app, /function getPathTrigger\(\)/, "prompt composer should detect @ file\/path reference triggers");
1284
1298
  assert.match(app, /api\(`\/api\/path-suggestions\?query=\$\{encodeURIComponent\(trigger\.query\)\}`/, "@ reference suggestions should load from the server as the user types");
1299
+ assert.match(app, /async function api\([\s\S]*?if \(signal\?\.aborted \|\| error\?\.name === "AbortError"\) throw error;[\s\S]*?setBackendOffline\(true, offlineError\)/, "cancelled @ autocomplete requests should not mark the server offline");
1285
1300
  assert.match(app, /formatPathReference\(suggestion\.path, trigger\.quoted\)/, "accepting a path suggestion should insert an @ reference into the prompt");
1286
1301
  assert.match(app, /let pathSuggestActiveQuery = null/, "@ autocomplete should track the active path query to avoid duplicate refresh flicker");
1287
1302
  assert.match(app, /pathSuggestActiveQuery === trigger\.query[\s\S]*?return;/, "@ autocomplete should skip duplicate same-query fetches from input and keyup events");
@@ -0,0 +1,55 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { test } from "node:test";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
8
+ const [app, gitFooterExtension] = await Promise.all([
9
+ readFile(join(root, "public", "app.js"), "utf8"),
10
+ readFile(join(root, "..", "pi-extension-git-footer-status", "index.ts"), "utf8"),
11
+ ]);
12
+ const readFunction = (name) => app.match(new RegExp(`(?:async )?function ${name}\\([^]*?\\n\\}`))?.[0] || "";
13
+
14
+ test("PI footer metric always exposes the calibration click action", () => {
15
+ const applyOptions = readFunction("applyGitFooterPiCalibrationOptions");
16
+ assert.match(applyOptions, /if \(chip\?\.key !== "pi"\) return "";/);
17
+ assert.doesNotMatch(applyOptions, /chip\?\.action|FOOTER_PAYLOAD_ACTIONS/);
18
+ assert.match(applyOptions, /void runGitFooterPiCalibration\(\)/);
19
+ assert.match(applyOptions, /ariaBusy/);
20
+ });
21
+
22
+ test("PI footer click dispatches exactly /calibrate in the background", () => {
23
+ const runCalibration = readFunction("runGitFooterPiCalibration");
24
+ assert.match(runCalibration, /resolveAvailableCommandName\("calibrate", \{ rpcOnly: true \}\)/);
25
+ assert.match(runCalibration, /await sendPrompt\("prompt", `\/\$\{commandName\}`, \{ targetTabId: tabContext\.tabId, throwOnError: true \}\)/);
26
+ assert.doesNotMatch(runCalibration, /commandName\} current|appConfirmText/);
27
+ assert.match(runCalibration, /gitFooterPiCalibrationInFlightByTab\.has\(tabContext\.tabId\)/);
28
+ assert.match(runCalibration, /currentState\?\.isStreaming \|\| currentState\?\.isCompacting/);
29
+ });
30
+
31
+ test("PI calibration schedules bounded delayed footer refreshes", () => {
32
+ const scheduleRefresh = readFunction("scheduleGitFooterPiCalibrationRefresh");
33
+ const runCalibration = readFunction("runGitFooterPiCalibration");
34
+ assert.match(scheduleRefresh, /delays = \[5000, 14000, 30000\]/);
35
+ assert.match(scheduleRefresh, /requestGitFooterWebuiPayload\(tabContext, \{ force: true \}\)/);
36
+ assert.match(runCalibration, /scheduleGitFooterPiCalibrationRefresh\(tabContext\)/);
37
+ });
38
+
39
+ test("PI calibration busy state invalidates the footer render cache key", () => {
40
+ const pickerStateKey = readFunction("gitFooterPickerStateKey");
41
+ assert.match(pickerStateKey, /gitFooterPiCalibrationInFlightByTab\.has\(tabContext\.tabId\)/);
42
+ assert.match(pickerStateKey, /piCalibrationInFlight \? 1 : 0/);
43
+ });
44
+
45
+ test("PI refresh scheduling survives an immediate tab switch", () => {
46
+ const runCalibration = readFunction("runGitFooterPiCalibration");
47
+ assert.match(runCalibration, /scheduleGitFooterPiCalibrationRefresh\(tabContext\);\s+if \(!isCurrentTabContext\(tabContext\)\) return;/);
48
+ });
49
+
50
+ test("explicit git-footer refresh invalidates stale calibration records", () => {
51
+ assert.match(
52
+ gitFooterExtension,
53
+ /pi\.registerCommand\("git-footer-refresh"[\s\S]*promptCalibrationCache = null;\s+await refreshPromptInjectionEstimate\(ctx\)/,
54
+ );
55
+ });
@@ -0,0 +1,63 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const app = await readFile(join(root, "public", "app.js"), "utf8");
8
+
9
+ assert.match(
10
+ app,
11
+ /function surfaceRuntimeDiagnostic\(title, content, level = "error"\)[\s\S]*?addEvent\(message, level\);[\s\S]*?addTransientMessage\(\{ role: level === "error" \? "error" : "warn", title, content: message, level \}\);/,
12
+ "runtime diagnostics should be written to both the event log and the visible transcript",
13
+ );
14
+ assert.match(
15
+ app,
16
+ /function assistantStreamErrorMessage\(event,[\s\S]*?update\.error\?\.errorMessage[\s\S]*?update\.partial\?\.errorMessage[\s\S]*?event\?\.message\?\.errorMessage/,
17
+ "assistant stream errors should prefer the provider's detailed final error message",
18
+ );
19
+ assert.match(
20
+ app,
21
+ /update\.type === "error"[\s\S]*?streamProviderErrorText = assistantStreamErrorMessage\(event, update\)[\s\S]*?content: streamProviderErrorText/,
22
+ "streaming provider errors should immediately render their detailed text",
23
+ );
24
+ assert.match(
25
+ app,
26
+ /case "message_end":[\s\S]*?event\.message\.stopReason === "error"[\s\S]*?surfaceRuntimeDiagnostic\("Assistant error", message\)[\s\S]*?assistantErrorSurfacedThisRun = true/,
27
+ "final assistant errors should remain visible after transcript reconciliation",
28
+ );
29
+ assert.match(
30
+ app,
31
+ /function assistantErrorFromAgentEnd\(event\)[\s\S]*?event\?\.messages[\s\S]*?findLast\(\(item\) => item\?\.role === "assistant"\)[\s\S]*?message\?\.stopReason !== "error"[\s\S]*?message\.errorMessage/,
32
+ "agent_end should recover provider errors from its terminal assistant message",
33
+ );
34
+ assert.match(
35
+ app,
36
+ /case "agent_end":[\s\S]*?!assistantErrorSurfacedThisRun && event\.willRetry !== true[\s\S]*?assistantErrorFromAgentEnd\(event\)[\s\S]*?surfaceRuntimeDiagnostic\("Assistant error", message\)/,
37
+ "agent_end should visibly surface a non-retrying provider error when message_end was absent",
38
+ );
39
+ assert.match(
40
+ app,
41
+ /function toolImagePayloadError\(event\)[\s\S]*?event\?\.result\?\.content[\s\S]*?block\?\.type !== "image"[\s\S]*?btoa\(atob\(data\)\) === data[\s\S]*?invalid base64 data/,
42
+ "tool image payloads should be checked for canonical base64 without exposing their contents",
43
+ );
44
+ assert.match(
45
+ app,
46
+ /case "tool_execution_end":[\s\S]*?toolImagePayloadError\(event\)[\s\S]*?surfaceRuntimeDiagnostic\("Tool image payload error", imagePayloadError\)/,
47
+ "malformed tool image payloads should immediately surface in the transcript",
48
+ );
49
+ for (const eventType of ["pi_process_exit", "pi_process_error", "pi_stderr", "pi_stderr_sink_error", "pi_stdout_line_too_large", "pi_stdout_parse_error"]) {
50
+ assert.match(app, new RegExp(`case "${eventType}":[\\s\\S]*?surfaceRuntimeDiagnostic\\(`), `${eventType} should surface in the transcript`);
51
+ }
52
+ assert.match(
53
+ app,
54
+ /case "compaction_end":[\s\S]*?event\.errorMessage[\s\S]*?surfaceRuntimeDiagnostic\("Compaction error", event\.errorMessage\)/,
55
+ "compaction failures should surface in the transcript",
56
+ );
57
+ assert.match(
58
+ app,
59
+ /case "response":[\s\S]*?event\.success === false[\s\S]*?surfaceRuntimeDiagnostic\(/,
60
+ "failed RPC command responses should surface in the transcript",
61
+ );
62
+
63
+ console.log("runtime error visibility test passed");