@firstpick/pi-package-webui 0.7.7 → 0.7.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -57,7 +57,7 @@ function makeEnvironment({ importApp, stylesheetLoaded = true, stylesheetStatus
57
57
  reload: new FakeElement(),
58
58
  copyStatus: new FakeElement(),
59
59
  };
60
- const styleLink = new FakeElement({ href: "http://127.0.0.1:31415/styles.css?v=84", sheet: stylesheetLoaded ? {} : null });
60
+ const styleLink = new FakeElement({ href: "http://127.0.0.1:31415/styles.css?v=85", sheet: stylesheetLoaded ? {} : null });
61
61
  const listeners = new Map();
62
62
  const timers = new Map();
63
63
  let timerId = 0;
@@ -76,7 +76,7 @@ function makeEnvironment({ importApp, stylesheetLoaded = true, stylesheetStatus
76
76
  removeEventListener(name) { listeners.delete(name); },
77
77
  };
78
78
  const document = {
79
- currentScript: new FakeElement({ dataset: { appSrc: "/app.js?v=91" } }),
79
+ currentScript: new FakeElement({ dataset: { appSrc: "/app.js?v=92" } }),
80
80
  readyState: "complete",
81
81
  querySelector(selector) {
82
82
  return {
@@ -174,7 +174,7 @@ for (const moduleName of startupModuleNames) {
174
174
  assert.ok(serviceWorker.includes(`"/${moduleName}"`), `the PWA app shell should include every app.js startup module: ${moduleName}`);
175
175
  }
176
176
  assert.match(serviceWorker, /pi-webui-pwa-v\d+/, "the app-shell cache should retain a versioned identity");
177
- assert.ok(html.indexOf('id="webuiBootLoader"') < html.indexOf("/app.js?v=91"), "the inline loader should own app module startup");
177
+ assert.ok(html.indexOf('id="webuiBootLoader"') < html.indexOf("/app.js?v=92"), "the inline loader should own app module startup");
178
178
  assert.doesNotMatch(html, /<script type="module" src="\/app\.js/, "the app module should not bypass the guarded loader");
179
179
 
180
180
  console.log("boot-failure-diagnostics.test.mjs passed");
@@ -0,0 +1,156 @@
1
+ import assert from "node:assert/strict";
2
+ import vm from "node:vm";
3
+ import { readFile } from "node:fs/promises";
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 server = await readFile(join(root, "bin", "pi-webui.mjs"), "utf8");
9
+ const app = await readFile(join(root, "public", "app.js"), "utf8");
10
+
11
+ function functionSource(source, name) {
12
+ const start = source.indexOf(`function ${name}(`);
13
+ assert.ok(start >= 0, `${name} should exist`);
14
+ const next = source.slice(start + 1).match(/\n(?:async )?function [A-Za-z0-9_$]+\(/);
15
+ const end = next ? start + 1 + next.index : source.length;
16
+ return source.slice(start, end);
17
+ }
18
+
19
+ const context = vm.createContext({ console });
20
+ vm.runInContext(`
21
+ const TAB_ACTIVITY_IDLE_RECONCILE_GRACE_MS = 1200;
22
+ function pendingExtensionUiRequests() { return []; }
23
+ function patchTabState(tab, patch) { tab.lastState = { ...(tab.lastState || {}), ...patch }; }
24
+ function rememberTabState(tab, state) { tab.lastState = state; }
25
+
26
+ ${functionSource(server, "createTabActivity")}
27
+ ${functionSource(server, "tabActivitySnapshot")}
28
+ ${functionSource(server, "markTabWorking")}
29
+ ${functionSource(server, "markTabDone")}
30
+ ${functionSource(server, "markTabIdle")}
31
+ ${functionSource(server, "stateHasVisibleWork")}
32
+ ${functionSource(server, "activityRecentlyStarted")}
33
+ ${functionSource(server, "reconcileTabActivityFromState")}
34
+ ${functionSource(server, "updateTabActivityFromEvent")}
35
+
36
+ globalThis.activityContract = {
37
+ createTab() { return { activity: createTabActivity(), lastState: {} }; },
38
+ event(tab, event) { return updateTabActivityFromEvent(tab, event); },
39
+ submit(tab, timestamp) { markTabWorking(tab, timestamp); return tabActivitySnapshot(tab); },
40
+ start(tab, timestamp) { markTabWorking(tab, timestamp, { runStarted: true }); return tabActivitySnapshot(tab); },
41
+ reconcile(tab, state, timestamp) { return reconcileTabActivityFromState(tab, state, timestamp); },
42
+ };
43
+ `, context);
44
+
45
+ const contract = context.activityContract;
46
+ const tab = contract.createTab();
47
+ assert.equal(tab.activity.completionSerial, 0);
48
+ assert.equal(tab.activity.runStarted, false);
49
+
50
+ contract.event(tab, { type: "agent_start" });
51
+ assert.equal(tab.activity.isWorking, true);
52
+ assert.equal(tab.activity.runStarted, true);
53
+ assert.equal(tab.lastState.isStreaming, true);
54
+
55
+ contract.event(tab, { type: "agent_end" });
56
+ assert.equal(tab.activity.isWorking, true, "agent_end is only a low-level run boundary");
57
+ assert.equal(tab.activity.completionSerial, 0, "agent_end must not create a completion");
58
+ assert.equal(tab.lastState.isStreaming, true, "agent_end must not expose an idle window before continuation");
59
+
60
+ contract.event(tab, { type: "agent_settled" });
61
+ assert.equal(tab.activity.isWorking, false);
62
+ assert.equal(tab.activity.status, "done");
63
+ assert.equal(tab.activity.completionSerial, 1, "settlement should create exactly one completion");
64
+ assert.equal(tab.lastState.isStreaming, false);
65
+
66
+ contract.event(tab, { type: "agent_settled" });
67
+ assert.equal(tab.activity.status, "done", "duplicate settlement should preserve the completed state");
68
+ assert.equal(tab.activity.completionSerial, 1, "duplicate settlement must be idempotent");
69
+
70
+ const handledPromptTab = contract.createTab();
71
+ contract.submit(handledPromptTab, "2020-01-01T00:00:00.000Z");
72
+ contract.reconcile(handledPromptTab, { isStreaming: false, isCompacting: false, pendingMessageCount: 0 }, "2020-01-01T00:00:02.000Z");
73
+ assert.equal(handledPromptTab.activity.status, "idle", "a handled prompt without agent_start should return to idle");
74
+ assert.equal(handledPromptTab.activity.completionSerial, 0, "a handled prompt must not look completed");
75
+
76
+ const missedSettlementTab = contract.createTab();
77
+ contract.start(missedSettlementTab, "2020-01-01T00:00:00.000Z");
78
+ contract.reconcile(missedSettlementTab, { isStreaming: false, isCompacting: false, pendingMessageCount: 0 }, "2020-01-01T00:00:02.000Z");
79
+ assert.equal(missedSettlementTab.activity.completionSerial, 1, "authoritative idle may recover a missed settlement only after a real start");
80
+
81
+ const compactionTab = contract.createTab();
82
+ contract.event(compactionTab, { type: "compaction_start" });
83
+ contract.event(compactionTab, { type: "compaction_end" });
84
+ assert.equal(compactionTab.activity.status, "idle");
85
+ assert.equal(compactionTab.activity.completionSerial, 0, "standalone compaction must not emit agent completion");
86
+
87
+ const failedProcessTab = contract.createTab();
88
+ contract.event(failedProcessTab, { type: "agent_start" });
89
+ contract.event(failedProcessTab, { type: "pi_process_error" });
90
+ assert.equal(failedProcessTab.activity.status, "idle");
91
+ assert.equal(failedProcessTab.activity.completionSerial, 0, "a failed process must not masquerade as successful completion");
92
+
93
+ assert.match(app, /case "agent_settled":[\s\S]*?notifyAgentDone\(/, "the browser should notify only from settlement");
94
+ assert.doesNotMatch(functionSource(app, "handleInactiveTabEvent"), /event\.type === "agent_end"[\s\S]*?notifyAgentDone/, "background low-level run ends must not notify");
95
+ assert.doesNotMatch(app.match(/case "agent_end":[\s\S]*?case "message_start":/)?.[0] || "", /notifyAgentDone|isStreaming: false/, "active low-level run ends must not notify or look idle");
96
+ assert.match(functionSource(app, "markTabWorkingLocally"), /suppressPendingAgentDoneNotificationsForTab\(tabId\)/, "starting new work should cancel a delayed stale completion notification");
97
+ assert.match(functionSource(app, "queueAgentDoneBrowserNotification"), /activityForTab\(tab\)\.isWorking/, "the delayed notification should re-check that the tab is still idle");
98
+
99
+ const notificationContext = vm.createContext({ console, setTimeout, clearTimeout });
100
+ vm.runInContext(`
101
+ const AGENT_DONE_NOTIFICATION_RETRY_GRACE_MS = 5;
102
+ let tabs = [{ id: "tab-1", working: false }];
103
+ let promptRoutingTabs = new Set();
104
+ let autoRetryingTabs = new Set();
105
+ let pendingAgentDoneNotificationTimers = new Map();
106
+ let agentDoneNotificationKeys = new Set();
107
+ let shown = [];
108
+ function activityForTab(tab) { return { isWorking: tab?.working === true }; }
109
+ function isAutoRetryingTab(tabId) { return autoRetryingTabs.has(tabId); }
110
+ function showAgentDoneBrowserNotification(payload) { shown.push(payload); }
111
+
112
+ ${functionSource(app, "clearPendingAgentDoneNotification")}
113
+ ${functionSource(app, "queueAgentDoneBrowserNotification")}
114
+
115
+ globalThis.notificationContract = {
116
+ queue(key) { queueAgentDoneBrowserNotification({ key, tabId: "tab-1", title: "done", body: "done" }); },
117
+ setWorking(value) { tabs[0].working = value; },
118
+ setRouting(value) { if (value) promptRoutingTabs.add("tab-1"); else promptRoutingTabs.delete("tab-1"); },
119
+ setRetrying(value) { if (value) autoRetryingTabs.add("tab-1"); else autoRetryingTabs.delete("tab-1"); },
120
+ shown() { return shown.length; },
121
+ reset() {
122
+ for (const pending of pendingAgentDoneNotificationTimers.values()) clearTimeout(pending.timer);
123
+ pendingAgentDoneNotificationTimers.clear();
124
+ promptRoutingTabs.clear();
125
+ autoRetryingTabs.clear();
126
+ tabs[0].working = false;
127
+ shown = [];
128
+ },
129
+ };
130
+ `, notificationContext);
131
+
132
+ const notifications = notificationContext.notificationContract;
133
+ const waitForNotificationTimer = () => new Promise((resolve) => setTimeout(resolve, 20));
134
+ notifications.queue("idle");
135
+ await waitForNotificationTimer();
136
+ assert.equal(notifications.shown(), 1, "an idle settled tab should notify once");
137
+
138
+ notifications.reset();
139
+ notifications.queue("new-work");
140
+ notifications.setWorking(true);
141
+ await waitForNotificationTimer();
142
+ assert.equal(notifications.shown(), 0, "new work during the grace window should suppress the stale done notification");
143
+
144
+ notifications.reset();
145
+ notifications.queue("routing");
146
+ notifications.setRouting(true);
147
+ await waitForNotificationTimer();
148
+ assert.equal(notifications.shown(), 0, "prompt routing during the grace window should suppress the stale done notification");
149
+
150
+ notifications.reset();
151
+ notifications.queue("retry");
152
+ notifications.setRetrying(true);
153
+ await waitForNotificationTimer();
154
+ assert.equal(notifications.shown(), 0, "an automatic retry should suppress an intermediate done notification");
155
+
156
+ console.log("completion signal contract checks passed");
@@ -0,0 +1,107 @@
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, supervisor] = await Promise.all([
8
+ readFile(join(root, "public", "app.js"), "utf8"),
9
+ readFile(join(root, "bin", "pi-webui.mjs"), "utf8"),
10
+ readFile(join(root, "bin", "pi-webui-rpc-supervisor.mjs"), "utf8"),
11
+ ]);
12
+
13
+ assert.match(
14
+ app,
15
+ /function pickCwd\(tab, initialCwd[\s\S]*?if \(pathPickerState\) \{[\s\S]*?working-directory picker is already open[\s\S]*?pathPickerSearchInput\.focus/,
16
+ "a duplicate cwd action should focus the existing picker and explain why no second picker opened",
17
+ );
18
+ assert.match(
19
+ app,
20
+ /async function changeActiveTabCwd\(\)[\s\S]*?title: "Changing working folder…"[\s\S]*?The existing working folder was kept[\s\S]*?surfaceRuntimeDiagnostic\("Working folder change failed", message\)/,
21
+ "cwd restarts should show immediate progress and transcript-visible failures with an atomicity explanation",
22
+ );
23
+ assert.match(
24
+ app,
25
+ /const changedTabId = response\.data\?\.tab\?\.id \|\| tab\.id;[\s\S]*?resetGitWorkflowForTab\(changedTabId\);[\s\S]*?clearGitFooterPayloadState\(changedTabId\);[\s\S]*?if \(!isCurrentTabContext\(tabContext\)\)/,
26
+ "a cwd change that finishes after a tab switch should invalidate that tab's old footer state",
27
+ );
28
+
29
+ assert.match(
30
+ app,
31
+ /function gitFooterFallbackMessage\(\)[\s\S]*?payloadState\?\.phase === "waiting"[\s\S]*?payloadState\?\.phase === "failed"[\s\S]*?payloadState\?\.phase === "idle"[\s\S]*?if \(extensionDetected\) return "Loading git footer status…"/,
32
+ "git footer fallback copy should distinguish active loading, terminal failure, cleared status, and discovery",
33
+ );
34
+ assert.match(
35
+ app,
36
+ /function waitForGitFooterPayloadSettlement\(tabContext, requestSerial\)[\s\S]*?gitFooterPayloadRequestSerialByTab\.get\(tabContext\.tabId\) !== requestSerial[\s\S]*?settleGitFooterPayload\(tabContext\.tabId, "failed"/,
37
+ "no-payload settlement should be bounded and reject stale request callbacks",
38
+ );
39
+ assert.match(
40
+ app,
41
+ /signal: AbortSignal\.timeout\(GIT_FOOTER_PAYLOAD_REQUEST_TIMEOUT_MS\)/,
42
+ "a hung footer refresh HTTP request should be bounded",
43
+ );
44
+ assert.match(
45
+ app,
46
+ /GIT_FOOTER_PAYLOAD_SETTLEMENT_TIMEOUT_MS[\s\S]*?Git footer refresh command is unavailable — reload to retry/,
47
+ "RPC command discovery should have a bounded loading window before actionable failure",
48
+ );
49
+ assert.match(
50
+ app,
51
+ /const validPayload = !!parseGitFooterWebuiPayloadRaw\(request\.statusText\);[\s\S]*?validPayload \? "ready" : "failed"/,
52
+ "a later valid live payload should recover failed or waiting footer state",
53
+ );
54
+ assert.match(
55
+ app,
56
+ /new Set\(\[\.\.\.gitFooterPayloadStateByTab\.keys\(\), \.\.\.gitFooterPayloadSettlementTimersByTab\.keys\(\), \.\.\.gitFooterPayloadRefreshInFlightByTab\]\)\) clearGitFooterPayloadState\(tabId\)/,
57
+ "feature toggles should clear footer state, timers, and in-flight markers",
58
+ );
59
+
60
+ assert.match(
61
+ server,
62
+ /async function updateTabCwd\(id, cwd\)[\s\S]*?cwdChangeInProgress[\s\S]*?makeHttpError\(409,[\s\S]*?performTabCwdUpdate/,
63
+ "overlapping cwd changes should be rejected per tab",
64
+ );
65
+ assert.match(
66
+ server,
67
+ /function scheduleSupervisorMetadataUpdate\(tab\)[\s\S]*?if \(tab\.cwdChangeInProgress\) return;[\s\S]*?updateMetadata\(supervisedTabMetadata\(tab\)\)/,
68
+ "stale full metadata writes should be deferred during cwd replacement",
69
+ );
70
+ assert.match(
71
+ server,
72
+ /async function performTabCwdUpdate\(tab, cwd\)[\s\S]*?!tab\.rpc\.supervisor\.isCurrentVersion\(\)[\s\S]*?Fully shut down Pi WebUI \(not Restart\)[\s\S]*?oldRpc\.replace\([\s\S]*?cwd: nextCwd[\s\S]*?tab\.cwd = nextCwd/,
73
+ "the server should reject stale detached supervisors and publish tab cwd only after replacement succeeds",
74
+ );
75
+ assert.match(
76
+ server,
77
+ /webui_cwd_change_failed[\s\S]*?makeHttpError\(502, `Could not restart/,
78
+ "replacement failures should produce an actionable SSE event and HTTP error",
79
+ );
80
+
81
+ assert.match(
82
+ supervisor,
83
+ /queueTabCommand\(tabId, operation\)[\s\S]*?tab\.mutationTail = admission\.catch[\s\S]*?return admission\.then\(\(\) => response\)[\s\S]*?case "command": return this\.queueTabCommand[\s\S]*?case "write": return this\.queueTabMutation/,
84
+ "commands should release their FIFO admission barrier before the full Pi response while writes remain serialized",
85
+ );
86
+ assert.doesNotMatch(
87
+ supervisor,
88
+ /async afterTabMutation\(/,
89
+ "commands must not chase a continuously moving mutation tail",
90
+ );
91
+ assert.match(
92
+ supervisor,
93
+ /async spawnChildCandidate\(child\)[\s\S]*?return \{ processChild, cwd, startedAt[\s\S]*?commitChild\(tab/,
94
+ "replacement children should be spawned privately before atomic publication",
95
+ );
96
+ assert.match(
97
+ supervisor,
98
+ /if \(tab\.child === processChild\) this\.handlePiLine[\s\S]*?text && tab\.child === processChild/,
99
+ "retired child stdout and stderr should be generation-fenced",
100
+ );
101
+ assert.match(
102
+ supervisor,
103
+ /const stopFailures = stopResults\.filter[\s\S]*?shutdown blocked by live child[\s\S]*?return false/,
104
+ "shutdown should retain ownership and state when a child cannot be stopped",
105
+ );
106
+
107
+ console.log("cwd-footer-reliability-static.test.mjs passed");
@@ -110,6 +110,7 @@ async function readLog(logFile) {
110
110
  const work = await mkdtemp(path.join(tmpdir(), "pi-webui-continuity-harness-"));
111
111
  const agentDir = path.join(work, "agent");
112
112
  const cwd = path.join(work, "cwd");
113
+ const changedCwd = path.join(work, "changed-cwd");
113
114
  const settingsFile = path.join(work, "settings.json");
114
115
  const sessionFile = path.join(work, "fixture-session.jsonl");
115
116
  const logFile = path.join(work, "fake-pi.jsonl");
@@ -132,6 +133,7 @@ let observedTabId;
132
133
  try {
133
134
  await writeFile(settingsFile, "{}\n");
134
135
  await mkdir(cwd, { recursive: true });
136
+ await mkdir(changedCwd, { recursive: true });
135
137
  initialServer = spawnServer({ cwd, env: environment, output });
136
138
 
137
139
  const initialHealth = await waitFor("initial supervised server health", health);
@@ -147,6 +149,27 @@ try {
147
149
  assert.equal(initialTab.cwd, cwd, "tab metadata must retain the isolated cwd");
148
150
  assert.equal(initialTab.sessionFile, sessionFile, "fixture session metadata must be captured before restart");
149
151
 
152
+ const concurrentCwdChanges = await Promise.all([
153
+ request(`/api/tabs/${encodeURIComponent(observedTabId)}`, { method: "PATCH", body: { cwd: changedCwd }, timeoutMs: 12_000 }),
154
+ request(`/api/tabs/${encodeURIComponent(observedTabId)}`, { method: "PATCH", body: { cwd: changedCwd }, timeoutMs: 12_000 }),
155
+ ]);
156
+ assert.deepEqual(concurrentCwdChanges.map((response) => response.status).sort(), [200, 409], "overlapping existing-tab cwd changes should allow one restart and reject the duplicate deterministically");
157
+ const cwdChange = concurrentCwdChanges.find((response) => response.status === 200);
158
+ const rejectedCwdChange = concurrentCwdChanges.find((response) => response.status === 409);
159
+ assert.match(String(rejectedCwdChange.body?.error || ""), /already changing its working folder/i, "rejected overlapping cwd change should explain the active restart");
160
+ assert.equal(cwdChange.body?.data?.changed, true, "existing-tab cwd change should report a real restart");
161
+ assert.equal(cwdChange.body?.data?.tab?.cwd, changedCwd, "cwd change response should expose the replacement cwd");
162
+ assert.notEqual(cwdChange.body?.data?.tab?.pid, observedPiPid, "cwd change should replace the managed Pi child");
163
+ observedPiPid = cwdChange.body.data.tab.pid;
164
+ const cwdChangeState = await request(`/api/state?tab=${encodeURIComponent(observedTabId)}`);
165
+ assert.equal(cwdChangeState.status, 200, "replacement child should answer state requests before cwd PATCH resolves");
166
+ const cwdChangeCommands = await request(`/api/commands?tab=${encodeURIComponent(observedTabId)}`);
167
+ assert.equal(cwdChangeCommands.status, 200, "replacement child should answer command discovery after cwd change");
168
+ const replacementStartup = await waitFor("replacement cwd startup", async () => (
169
+ (await readLog(logFile)).find((entry) => entry.direction === "startup" && entry.pid === observedPiPid && entry.cwd === changedCwd)
170
+ ));
171
+ assert.equal(replacementStartup.cwd, changedCwd, "replacement child process should actually run in the requested cwd");
172
+
150
173
  const controlledPrompt = await request("/api/prompt", { method: "POST", body: { tab: observedTabId, message: streamPrompt } });
151
174
  assert.equal(controlledPrompt.status, 200, "controlled-restart prompt must be accepted once");
152
175
  const preRestartTab = (await tabs())[0];
@@ -162,7 +185,7 @@ try {
162
185
  assert.equal(controlledTabs.length, 1, "controlled restart must hydrate instead of spawning duplicate tabs");
163
186
  assert.deepEqual(
164
187
  controlledTabs.map((tab) => ({ id: tab.id, pid: tab.pid, cwd: tab.cwd, sessionFile: tab.sessionFile, title: tab.title, index: tab.index })),
165
- [{ id: preRestartTab.id, pid: observedPiPid, cwd, sessionFile, title: preRestartTab.title, index: preRestartTab.index }],
188
+ [{ id: preRestartTab.id, pid: observedPiPid, cwd: changedCwd, sessionFile, title: preRestartTab.title, index: preRestartTab.index }],
166
189
  "controlled restart must retain the same managed tab metadata and Pi PID",
167
190
  );
168
191
  assert.equal(restartedHealth.piPid, observedPiPid, "controlled restart must retain the active Pi process");
@@ -189,7 +212,7 @@ try {
189
212
  assert.equal(manualTabs.length, 1, "manual relaunch must not duplicate the supervised tab");
190
213
  assert.deepEqual(
191
214
  manualTabs.map((tab) => ({ id: tab.id, pid: tab.pid, cwd: tab.cwd, sessionFile: tab.sessionFile, title: tab.title, index: tab.index })),
192
- [{ id: preRestartTab.id, pid: observedPiPid, cwd, sessionFile, title: preRestartTab.title, index: preRestartTab.index }],
215
+ [{ id: preRestartTab.id, pid: observedPiPid, cwd: changedCwd, sessionFile, title: preRestartTab.title, index: preRestartTab.index }],
193
216
  "manual relaunch must retain tab ID, PID, and persisted metadata",
194
217
  );
195
218
 
@@ -152,7 +152,7 @@ assert.match(helper, /FAST_OUTPUT_FLUSH_INTERVAL_MS = 100/, "the live scheduler
152
152
  assert.match(worker, /pi-webui-pwa-v\d+[\s\S]*?"\/fast-output-live\.mjs"/, "PWA cache identity and app shell should include the compact helper");
153
153
  assert.match(html, /<label for="fastOutputModeSelect">Fast mode \(Experimental\)<\/label>/, "the sidebar should mark fast mode as experimental");
154
154
  assert.match(html, /Markdown final output; live thinking expanded; stored thinking grouped and collapsed/, "the sidebar should distinguish live and stored thinking defaults");
155
- assert.match(html, /id="webuiBootLoader"[^>]*data-app-src="\/app\.js\?v=91"/, "the guarded PWA entry point should cache-bust browser wiring");
155
+ assert.match(html, /id="webuiBootLoader"[^>]*data-app-src="\/app\.js\?v=92"/, "the guarded PWA entry point should cache-bust browser wiring");
156
156
  assert.match(JSON.parse(packageRaw).scripts.check, /node --check public\/fast-output-live\.mjs/, "package checks should parse the compact helper");
157
157
 
158
158
  const events = createFastModeOutputEvents();
File without changes
@@ -11,7 +11,7 @@
11
11
  // ({direction:"event", type}), so browser-driver tests can assert ordering.
12
12
  // - FAKE_PI_VOICE_SCRIPTS=1: prompts containing "voice test say|question|tool|slow"
13
13
  // respond success and then asynchronously emit a scripted agent event flow
14
- // (agent_start/message_*/tool_execution_*/agent_end) over stdout; the scripted
14
+ // (agent_start/message_*/tool_execution_*/agent_end/agent_settled) over stdout; the scripted
15
15
  // assistant turns are appended to a dynamic transcript returned by
16
16
  // get_messages AFTER the three baseline messages, and get_state reports
17
17
  // isStreaming=true while a scripted flow runs.
@@ -101,6 +101,7 @@ function logJsonLine(entry) {
101
101
 
102
102
  logJsonLine({
103
103
  direction: "startup",
104
+ cwd: process.cwd(),
104
105
  recoveryUrl: String(process.env.PI_WEBUI_RECOVERY_URL || ""),
105
106
  recoveryTokenConfigured: Boolean(process.env.PI_WEBUI_RECOVERY_TOKEN),
106
107
  ...(continuityModeEnabled ? { pid: process.pid, continuityMode: true } : {}),
@@ -155,7 +156,7 @@ function cancelScriptedSteps() {
155
156
  }
156
157
 
157
158
  // Emits a full scripted assistant turn: agent_start, optional tool phase,
158
- // streamed assistant text, message_end, agent_end. The final assistant text is
159
+ // streamed assistant text, message_end, agent_end, agent_settled. The final assistant text is
159
160
  // appended to the dynamic transcript so get_messages returns it afterwards.
160
161
  function runVoiceScriptFlow({ text, chunks, chunkSpacingMs = 60, toolPhase = false, toolDurationMs = 1500 }) {
161
162
  scriptedStreaming = true;
@@ -177,11 +178,12 @@ function runVoiceScriptFlow({ text, chunks, chunkSpacingMs = 60, toolPhase = fal
177
178
  emitScriptedEvent({ type: "message_end", message });
178
179
  },
179
180
  });
181
+ steps.push({ afterMs: 60, run: () => emitScriptedEvent({ type: "agent_end" }) });
180
182
  steps.push({
181
- afterMs: 60,
183
+ afterMs: 10,
182
184
  run: () => {
183
185
  scriptedStreaming = false;
184
- emitScriptedEvent({ type: "agent_end" });
186
+ emitScriptedEvent({ type: "agent_settled" });
185
187
  },
186
188
  });
187
189
  runScriptedSteps(steps);
@@ -203,9 +205,10 @@ function runContinuityDelayedStream() {
203
205
  appendDynamicMessage(message);
204
206
  emitScriptedEvent(tagged({ type: "message_end", continuityStep: "message-end", message }));
205
207
  } },
206
- { afterMs: 80, run: () => {
208
+ { afterMs: 80, run: () => emitScriptedEvent(tagged({ type: "agent_end", continuityStep: "end" })) },
209
+ { afterMs: 10, run: () => {
207
210
  scriptedStreaming = false;
208
- emitScriptedEvent(tagged({ type: "agent_end", continuityStep: "end" }));
211
+ emitScriptedEvent(tagged({ type: "agent_settled", continuityStep: "settled" }));
209
212
  } },
210
213
  ];
211
214
  runScriptedSteps(steps);
@@ -389,6 +392,7 @@ function runFastModeFixtureFlow({ barrierOnly = false } = {}) {
389
392
  const finish = () => {
390
393
  emitEvent({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: finalText }] } });
391
394
  emitEvent({ type: "agent_end" });
395
+ emitEvent({ type: "agent_settled" });
392
396
  };
393
397
  emitEvent({ type: "agent_start" });
394
398
  emitEvent({ type: "message_start", message: { role: "assistant" } });
@@ -419,6 +423,7 @@ function runFastModeHistoryFlow() {
419
423
  }
420
424
  emitEvent({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: accumulated }] } });
421
425
  emitEvent({ type: "agent_end" });
426
+ emitEvent({ type: "agent_settled" });
422
427
  }
423
428
 
424
429
  function handleFastModeFixturePrompt(command, base) {
@@ -0,0 +1,10 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+
4
+ const css = await readFile(new URL("../public/styles.css", import.meta.url), "utf8");
5
+ const progressOverlay = css.match(/\.footer-context-card\.has-context-usage::before\s*\{([^}]+)\}/)?.[1] ?? "";
6
+
7
+ assert.match(progressOverlay, /background:\s*var\(--context-card-gradient\)/, "context usage should retain its themed progress gradient");
8
+ assert.match(progressOverlay, /opacity:\s*0\.34/, "context progress should stay translucent enough for readable text");
9
+
10
+ console.log("footer context contrast static tests passed");
@@ -15,6 +15,8 @@ function functionBody(name) {
15
15
 
16
16
  const renderGitPanel = functionBody("renderGitPanel");
17
17
  const renderGitPanelFolder = functionBody("renderGitPanelFolder");
18
+ const renderGitPanelRepositoryCard = functionBody("renderGitPanelRepositoryCard");
19
+ const updateGitPanelRepositoryMeta = functionBody("updateGitPanelRepositoryMeta");
18
20
  const renderContextMeter = functionBody("renderContextMeter");
19
21
  const renderWorkspaceDashboard = functionBody("renderWorkspaceDashboard");
20
22
 
@@ -29,8 +31,16 @@ assert.doesNotMatch(renderGitPanel, /\bsectionExpanded\b/, "Git panel signature
29
31
  const gitGuard = renderGitPanel.indexOf("signature === gitPanelRenderSignature");
30
32
  const gitRebuild = renderGitPanel.indexOf("elements.gitPanelGroups.replaceChildren");
31
33
  assert.ok(gitGuard > 0 && gitGuard < gitRebuild, "Git panel signature guard should precede its DOM rebuild");
32
- assert.match(renderGitPanel, /snapshot\?\.loadedAt/, "Git panel signature should include repository snapshot versions");
34
+ assert.doesNotMatch(renderGitPanel, /snapshot\?\.loadedAt|data\?\.generatedAt/, "Git panel signature should ignore refresh timestamps");
35
+ assert.match(renderGitPanel, /!data && !!snapshot\?\.loading/, "initial repository loads should still update their loading state");
36
+ assert.match(renderGitPanel, /gitPanelDataRenderSignature\(data\)/, "Git panel signature should still track rendered repository data");
33
37
  assert.match(renderGitPanel, /gitPanelState\.activeViews\.get/, "Git panel signature should include active repository views");
38
+ assert.match(renderGitPanelRepositoryCard, /section\.dataset\.gitRoot = card\.root;/, "repository cards should expose a stable root for targeted metadata updates");
39
+ assert.match(updateGitPanelRepositoryMeta, /\.git-side-panel-repository-updated/, "refresh state should target only the update-time label");
40
+ assert.match(updateGitPanelRepositoryMeta, /snapshot\.loading \? "Refreshing…" : `Updated /, "the targeted label should reflect refresh progress and completion time");
41
+
42
+ const gitMetaUpdate = renderGitPanel.indexOf("updateGitPanelRepositoryMeta(cards)");
43
+ assert.ok(gitMetaUpdate > gitGuard && gitMetaUpdate < gitRebuild, "unchanged Git content should update metadata before returning without a DOM rebuild");
34
44
 
35
45
  const contextGuard = renderContextMeter.indexOf("signature === contextMeterSignature");
36
46
  const contextRebuild = renderContextMeter.lastIndexOf("root.replaceChildren");
@@ -0,0 +1,135 @@
1
+ import assert from "node:assert/strict";
2
+ import { createIssueBotClient, readIssueBotRuntimeConfig } from "../public/issue-bot-client.mjs";
3
+
4
+ const submissionId = "AbCdEfGhIjKlMnOpQrStUv";
5
+ const statusToken = "a".repeat(43);
6
+ const uuid = "123e4567-e89b-42d3-a456-426614174000";
7
+ const issue = Object.freeze({
8
+ categoryId: "bug",
9
+ componentId: "webui",
10
+ templateId: "bug-defect-report",
11
+ summary: "Panel fails to open",
12
+ fields: Object.freeze({
13
+ severity: "high",
14
+ expectedBehavior: "The panel opens.",
15
+ actualBehavior: "Nothing appears.",
16
+ reproductionSteps: "1. Open the deck\n2. Select the panel",
17
+ }),
18
+ });
19
+
20
+ const config = Object.freeze({
21
+ enabled: true,
22
+ gatewayBaseUrl: "https://issue-intake.example.test/",
23
+ turnstileSiteKey: "1x00000000000000000000AA",
24
+ privateSecurityReportUrl: "https://github.com/Firstp1ck/pi-coding-agent-forge/security/advisories/new",
25
+ });
26
+
27
+ assert.deepEqual(readIssueBotRuntimeConfig(), {
28
+ enabled: false,
29
+ gatewayBaseUrl: "",
30
+ turnstileSiteKey: "",
31
+ privateSecurityReportUrl: "",
32
+ }, "missing public runtime configuration must leave the bot disabled");
33
+ assert.equal(readIssueBotRuntimeConfig({ ...config, gatewayBaseUrl: "http://localhost:8787" }).enabled, false, "non-HTTPS gateway configuration must fail closed");
34
+ assert.equal(readIssueBotRuntimeConfig({ ...config, turnstileSiteKey: "contains whitespace" }).enabled, false, "invalid public Turnstile configuration must fail closed");
35
+
36
+ let disabledFetches = 0;
37
+ const disabled = createIssueBotClient({ config: readIssueBotRuntimeConfig(), fetchImpl: async () => { disabledFetches += 1; } });
38
+ const disabledResult = await disabled.submit({ issue });
39
+ assert.equal(disabled.available, false);
40
+ assert.equal(disabledResult.result.status, "unavailable");
41
+ assert.equal(disabledFetches, 0, "disabled configuration must not contact an arbitrary endpoint");
42
+
43
+ const calls = [];
44
+ const statuses = [];
45
+ const client = createIssueBotClient({
46
+ config,
47
+ uuidFactory: () => uuid,
48
+ getTurnstileToken: async ({ siteKey, idempotencyKey }) => {
49
+ assert.equal(siteKey, config.turnstileSiteKey);
50
+ assert.equal(idempotencyKey, uuid, "Turnstile cData must bind the challenge to the admission UUID");
51
+ return "fresh-turnstile-token";
52
+ },
53
+ sleep: async () => {},
54
+ fetchImpl: async (url, options) => {
55
+ calls.push({ url, options });
56
+ if (options.method === "POST") {
57
+ return new Response(JSON.stringify({
58
+ ok: true,
59
+ status: "queued",
60
+ submissionId,
61
+ statusToken,
62
+ pollAfterMs: 2_500,
63
+ }), { status: 202, headers: { "content-type": "application/json" } });
64
+ }
65
+ return new Response(JSON.stringify({
66
+ ok: true,
67
+ status: "created",
68
+ submissionId,
69
+ issueUrl: "https://github.com/Firstp1ck/pi-coding-agent-forge/issues/42",
70
+ issueNumber: 42,
71
+ }), { headers: { "content-type": "application/json" } });
72
+ },
73
+ });
74
+ const completed = await client.submit({ issue, onStatus: (status) => statuses.push(status.status) });
75
+ assert.equal(completed.result.status, "created");
76
+ assert.equal(completed.result.issueNumber, 42);
77
+ assert.equal(completed.handle.refresh instanceof Function, true, "the in-memory opaque refresh handle must support manual polling");
78
+ assert.deepEqual(Object.keys(completed.handle), ["refresh"], "the refresh handle must not expose a status capability");
79
+ assert.deepEqual(statuses, ["queued", "queued", "created"], "admission and every safe poll state should be observable without raw upstream data");
80
+ assert.equal(calls.length, 2);
81
+ assert.equal(calls[0].url, "https://issue-intake.example.test/v1/submissions");
82
+ assert.equal(calls[0].options.credentials, "omit");
83
+ const sent = JSON.parse(calls[0].options.body);
84
+ assert.deepEqual(Object.keys(sent).sort(), ["idempotencyKey", "issue", "schemaVersion", "turnstileToken"]);
85
+ assert.equal(sent.idempotencyKey, uuid, "each admission uses the injected fresh UUID-v4 source");
86
+ assert.deepEqual(sent.issue, issue, "the adapter sends structured wizard state, not canonical title/body fields");
87
+ assert.equal("title" in sent.issue, false);
88
+ assert.equal("body" in sent.issue, false);
89
+ assert.equal(calls[1].options.headers.authorization, `Bearer ${statusToken}`, "only the in-memory capability authorizes status polling");
90
+
91
+ let timeoutClock = 0;
92
+ const timeoutClient = createIssueBotClient({
93
+ config,
94
+ uuidFactory: () => uuid,
95
+ getTurnstileToken: async () => "fresh-turnstile-token",
96
+ sleep: async () => { timeoutClock += 500; },
97
+ now: () => timeoutClock,
98
+ maxPollDurationMs: 500,
99
+ fetchImpl: async (_url, options) => new Response(JSON.stringify(options.method === "POST" ? {
100
+ ok: true, status: "queued", submissionId, statusToken, pollAfterMs: 2_500,
101
+ } : {
102
+ ok: true, status: "checking", submissionId, pollAfterMs: 2_500,
103
+ }), { status: options.method === "POST" ? 202 : 200, headers: { "content-type": "application/json" } }),
104
+ });
105
+ const timedOut = await timeoutClient.submit({ issue });
106
+ assert.equal(timedOut.result.status, "checking");
107
+ assert.equal(timedOut.result.timedOut, true, "polling must stop after its bounded duration and retain a manual refresh handle");
108
+ assert.equal(typeof timedOut.handle.refresh, "function");
109
+
110
+ const invalidEnvelopeClient = createIssueBotClient({
111
+ config,
112
+ uuidFactory: () => uuid,
113
+ getTurnstileToken: async () => "fresh-turnstile-token",
114
+ sleep: async () => {},
115
+ fetchImpl: async (_url, options) => new Response(JSON.stringify(options.method === "POST" ? {
116
+ ok: true, status: "queued", submissionId, statusToken, pollAfterMs: 2_500,
117
+ } : {
118
+ ok: true, status: "created", submissionId,
119
+ issueUrl: "https://github.com/Firstp1ck/pi-coding-agent-forge/issues/43", issueNumber: 43, unexpected: true,
120
+ }), { status: options.method === "POST" ? 202 : 200, headers: { "content-type": "application/json" } }),
121
+ });
122
+ assert.equal((await invalidEnvelopeClient.submit({ issue })).result.status, "unavailable", "unknown response properties must fail closed");
123
+
124
+ const abortController = new AbortController();
125
+ const abortClient = createIssueBotClient({
126
+ config,
127
+ uuidFactory: () => uuid,
128
+ getTurnstileToken: ({ signal }) => new Promise((_resolve, reject) => signal.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")), { once: true })),
129
+ fetchImpl: async () => { throw new Error("fetch must not run after Turnstile abort"); },
130
+ });
131
+ const aborted = abortClient.submit({ issue, signal: abortController.signal });
132
+ abortController.abort();
133
+ await assert.rejects(aborted, (error) => error?.name === "AbortError", "dialog-close cancellation must abort before admission");
134
+
135
+ console.log("issue-bot-client.test.mjs passed");