@firstpick/pi-package-webui 0.7.7 → 0.7.9

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.
Files changed (50) hide show
  1. package/README.md +23 -0
  2. package/bin/pi-webui-rpc-supervisor.mjs +115 -21
  3. package/bin/pi-webui.mjs +447 -88
  4. package/lib/queue-mutation.mjs +109 -0
  5. package/lib/rpc-supervisor-client.mjs +18 -2
  6. package/lib/rpc-supervisor-protocol.mjs +11 -2
  7. package/lib/scoped-models.mjs +19 -0
  8. package/lib/webui-workspaces.mjs +265 -0
  9. package/package.json +4 -4
  10. package/public/app.js +2227 -195
  11. package/public/index.html +143 -2
  12. package/public/issue-bot-client.mjs +344 -0
  13. package/public/issue-wizard-state.mjs +443 -0
  14. package/public/service-worker.js +3 -1
  15. package/public/styles.css +787 -56
  16. package/public/voice-conversation.mjs +1 -1
  17. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  18. package/tests/compaction-mutation-contract.test.mjs +166 -0
  19. package/tests/compaction-resume-harness.test.mjs +113 -2
  20. package/tests/compaction-static.test.mjs +5 -0
  21. package/tests/completion-signal-contract.test.mjs +156 -0
  22. package/tests/cwd-footer-reliability-static.test.mjs +112 -0
  23. package/tests/durable-rpc-supervisor-harness.test.mjs +25 -2
  24. package/tests/fast-mode-client-static.test.mjs +1 -1
  25. package/tests/file-selection-overlay-static.test.mjs +21 -0
  26. package/tests/file-viewer-search-static.test.mjs +65 -0
  27. package/tests/fixtures/compacting-pi.mjs +0 -0
  28. package/tests/fixtures/fake-pi.mjs +186 -49
  29. package/tests/footer-context-contrast-static.test.mjs +10 -0
  30. package/tests/git-panel-file-preview-static.test.mjs +20 -5
  31. package/tests/git-panel-render-stability-static.test.mjs +11 -1
  32. package/tests/http-endpoints-harness.test.mjs +160 -1
  33. package/tests/issue-bot-client.test.mjs +135 -0
  34. package/tests/issue-wizard-state.test.mjs +126 -0
  35. package/tests/mobile-static.test.mjs +61 -42
  36. package/tests/native-parity.test.mjs +3 -3
  37. package/tests/open-issue-wizard-static.test.mjs +75 -0
  38. package/tests/prompt-routing-tab-status.test.mjs +5 -0
  39. package/tests/queue-edit-reorder-static.test.mjs +101 -0
  40. package/tests/queue-mutation-contract.test.mjs +143 -0
  41. package/tests/rpc-supervisor-host.test.mjs +135 -2
  42. package/tests/rpc-supervisor-protocol.test.mjs +26 -0
  43. package/tests/scoped-models.test.mjs +42 -0
  44. package/tests/streaming-ui-coupling.test.mjs +3 -2
  45. package/tests/subagents-helper.test.mjs +216 -3
  46. package/tests/terminal-tab-workspace-static.test.mjs +101 -0
  47. package/tests/webui-workspaces-harness.test.mjs +223 -0
  48. package/tests/webui-workspaces.test.mjs +106 -0
  49. package/tests/workspace-save-load-static.test.mjs +69 -0
  50. package/webui-rpc-helper.mjs +300 -41
@@ -3,7 +3,7 @@
3
3
  // timers, and delivery callbacks all arrive through options so Node tests can
4
4
  // drive the full listen -> prompt -> speak -> listen loop without a browser.
5
5
  //
6
- // Turn-taking contract (see docs/webui/natural-conversation/NATURAL_CONVERSATION_MODE_PLAN.md):
6
+ // Turn-taking contract (see docs/planned/webui/natural-conversation/NATURAL_CONVERSATION_MODE_PLAN.md):
7
7
  // - Final transcripts while Pi is idle are sent as normal prompts.
8
8
  // - Transcripts while the assistant streams final text are interruptions.
9
9
  // - Transcripts during a tool call/execution are queued until the tool phase
@@ -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,166 @@
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
+ import vm from "node:vm";
6
+
7
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
8
+ const server = await readFile(join(root, "bin", "pi-webui.mjs"), "utf8");
9
+
10
+ function sourceForFunction(name) {
11
+ const start = server.indexOf(`function ${name}(`);
12
+ assert.notEqual(start, -1, `${name} should remain a server helper`);
13
+ const openingBrace = server.indexOf(") {", start) + 2;
14
+ assert.ok(openingBrace > start, `${name} should have a function body`);
15
+ let depth = 0;
16
+ let quote = "";
17
+ for (let index = openingBrace; index < server.length; index += 1) {
18
+ const character = server[index];
19
+ if (quote) {
20
+ if (character === "\\") {
21
+ index += 1;
22
+ } else if (character === quote) {
23
+ quote = "";
24
+ }
25
+ continue;
26
+ }
27
+ if (character === '"' || character === "'" || character === "`") {
28
+ quote = character;
29
+ continue;
30
+ }
31
+ if (character === "{") depth += 1;
32
+ if (character === "}" && --depth === 0) return server.slice(start, index + 1);
33
+ }
34
+ assert.fail(`${name} should have a balanced function body`);
35
+ }
36
+
37
+ function plain(value) {
38
+ return JSON.parse(JSON.stringify(value));
39
+ }
40
+
41
+ const events = [];
42
+ const context = {
43
+ broadcastTabEvent(tab, event) {
44
+ events.push({ tab, event });
45
+ },
46
+ tabActivitySnapshot(tab) {
47
+ return { tabId: tab.id };
48
+ },
49
+ };
50
+ vm.createContext(context);
51
+ const functions = [
52
+ "compactionQueueForTab",
53
+ "compactionQueueRevision",
54
+ "advanceCompactionQueueRevision",
55
+ "compactionQueueSnapshot",
56
+ "compactionQueueEvent",
57
+ "sameQueueSnapshot",
58
+ "compactionFollowUpSlots",
59
+ "mutateCompactionFollowUpQueue",
60
+ ].map(sourceForFunction).join("\n\n");
61
+ vm.runInContext(`${functions}\nglobalThis.mutate = mutateCompactionFollowUpQueue;`, context);
62
+
63
+ const firstImage = { type: "image", mimeType: "image/png", data: "first-image" };
64
+ const secondImage = { type: "image", mimeType: "image/png", data: "second-image" };
65
+ const editedCommand = {
66
+ type: "follow_up",
67
+ mode: "followUp",
68
+ message: "first follow-up",
69
+ images: [firstImage],
70
+ metadata: { origin: "fixture", sequence: 1 },
71
+ };
72
+ const movedCommand = {
73
+ type: "prompt",
74
+ mode: "followUp",
75
+ message: "second follow-up",
76
+ images: [secondImage],
77
+ metadata: { origin: "fixture", sequence: 2 },
78
+ };
79
+ const tab = {
80
+ id: "compaction-contract-tab",
81
+ title: "Compaction contract",
82
+ compactionQueue: [
83
+ { id: "steer", command: { type: "steer", mode: "steer", message: "fixed steering", metadata: { origin: "fixture" } } },
84
+ { id: "edit", command: editedCommand },
85
+ { id: "move", command: movedCommand },
86
+ ],
87
+ };
88
+
89
+ const edit = context.mutate(tab, {
90
+ source: "webui-compaction",
91
+ kind: "followUp",
92
+ revision: 0,
93
+ expected: { steering: ["fixed steering"], followUp: ["first follow-up", "second follow-up"] },
94
+ operation: { type: "edit", index: 0, expectedText: "first follow-up", text: "edited follow-up" },
95
+ });
96
+ assert.deepEqual(plain(edit), {
97
+ mutated: true,
98
+ source: "webui-compaction",
99
+ queue: {
100
+ source: "webui-compaction",
101
+ revision: 1,
102
+ steering: ["fixed steering"],
103
+ followUp: ["edited follow-up", "second follow-up"],
104
+ draining: false,
105
+ },
106
+ }, "a successful edit returns the authoritative advanced snapshot");
107
+ assert.strictEqual(tab.compactionQueue[1].command, editedCommand, "edit must retain the original queued command object");
108
+ assert.strictEqual(editedCommand.images[0], firstImage, "edit must retain the original image object");
109
+ assert.deepEqual(editedCommand.metadata, { origin: "fixture", sequence: 1 }, "edit must retain command metadata");
110
+ assert.equal(editedCommand.type, "follow_up", "edit must retain the command type");
111
+ assert.equal(editedCommand.mode, "followUp", "edit must retain the command mode");
112
+ assert.equal(events.length, 1, "a successful compaction edit emits exactly one queue update");
113
+ assert.deepEqual(plain(events[0].event), {
114
+ type: "webui_compaction_queue_update",
115
+ tabId: "compaction-contract-tab",
116
+ tabTitle: "Compaction contract",
117
+ queueLength: 3,
118
+ pendingMessageCount: 3,
119
+ source: "webui-compaction",
120
+ revision: 1,
121
+ steering: ["fixed steering"],
122
+ followUp: ["edited follow-up", "second follow-up"],
123
+ draining: false,
124
+ tabActivity: { tabId: "compaction-contract-tab" },
125
+ }, "the successful edit emits its one authoritative snapshot");
126
+
127
+ const stale = context.mutate(tab, {
128
+ source: "webui-compaction",
129
+ kind: "followUp",
130
+ revision: 0,
131
+ expected: { steering: ["fixed steering"], followUp: ["first follow-up", "second follow-up"] },
132
+ operation: { type: "move", from: 1, to: 0, expectedText: "second follow-up" },
133
+ });
134
+ assert.equal(stale.mutated, false, "a stale compaction request is rejected");
135
+ assert.equal(stale.reason, "queue-changed");
136
+ assert.equal(events.length, 1, "a rejected stale mutation emits no queue update");
137
+ assert.strictEqual(tab.compactionQueue[1].command, editedCommand, "a rejected stale mutation leaves command identity intact");
138
+
139
+ const move = context.mutate(tab, {
140
+ source: "webui-compaction",
141
+ kind: "followUp",
142
+ revision: 1,
143
+ expected: { steering: ["fixed steering"], followUp: ["edited follow-up", "second follow-up"] },
144
+ operation: { type: "move", from: 1, to: 0, expectedText: "second follow-up" },
145
+ });
146
+ assert.equal(move.mutated, true, "a current move is accepted");
147
+ assert.deepEqual([...move.queue.followUp], ["second follow-up", "edited follow-up"], "move uses the final follow-up index while steering remains fixed");
148
+ assert.strictEqual(tab.compactionQueue[1].command, movedCommand, "move keeps the full command object paired with its queue slot");
149
+ assert.strictEqual(movedCommand.images[0], secondImage, "move retains the moved command image object");
150
+ assert.deepEqual(movedCommand.metadata, { origin: "fixture", sequence: 2 }, "move retains moved command metadata");
151
+ assert.equal(events.length, 2, "a successful compaction move emits exactly one additional queue update");
152
+
153
+ tab.compactionQueueDraining = true;
154
+ const draining = context.mutate(tab, {
155
+ source: "webui-compaction",
156
+ kind: "followUp",
157
+ revision: 2,
158
+ expected: { steering: ["fixed steering"], followUp: ["second follow-up", "edited follow-up"] },
159
+ operation: { type: "edit", index: 0, expectedText: "second follow-up", text: "must not apply" },
160
+ });
161
+ assert.equal(draining.mutated, false, "a draining compaction queue rejects mutation");
162
+ assert.equal(draining.reason, "queue-draining");
163
+ assert.equal(events.length, 2, "a rejected draining mutation emits no queue update");
164
+ assert.strictEqual(tab.compactionQueue[1].command, movedCommand, "a rejected draining mutation leaves the moved command untouched");
165
+
166
+ console.log("compaction-mutation-contract.test.mjs passed");
@@ -35,6 +35,36 @@ async function request(pathname, { method = "GET", body, timeoutMs = 5_000 } = {
35
35
  return { status: response.status, body: payload };
36
36
  }
37
37
 
38
+ async function waitForSseEvent(tabId, predicate) {
39
+ const controller = new AbortController();
40
+ const timeout = setTimeout(() => controller.abort(new Error("timed out waiting for SSE event")), 8_000);
41
+ try {
42
+ const response = await fetch(`http://127.0.0.1:${port}/api/events?tab=${encodeURIComponent(tabId)}`, { signal: controller.signal });
43
+ assert.equal(response.status, 200, "SSE connection should open");
44
+ const reader = response.body.getReader();
45
+ const decoder = new TextDecoder();
46
+ let buffer = "";
47
+ while (true) {
48
+ const { done, value } = await reader.read();
49
+ if (done) break;
50
+ buffer += decoder.decode(value, { stream: true });
51
+ let boundary;
52
+ while ((boundary = buffer.indexOf("\n\n")) >= 0) {
53
+ const block = buffer.slice(0, boundary);
54
+ buffer = buffer.slice(boundary + 2);
55
+ const data = block.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).join("\n");
56
+ if (!data) continue;
57
+ const event = JSON.parse(data);
58
+ if (predicate(event)) return { event };
59
+ }
60
+ }
61
+ throw new Error("SSE stream ended before the expected event");
62
+ } finally {
63
+ clearTimeout(timeout);
64
+ controller.abort();
65
+ }
66
+ }
67
+
38
68
  async function waitFor(description, probe, { attempts = 60, intervalMs = 100 } = {}) {
39
69
  let last;
40
70
  for (let attempt = 0; attempt < attempts; attempt += 1) {
@@ -53,6 +83,7 @@ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "12
53
83
  stdio: ["ignore", "pipe", "pipe"],
54
84
  env: { ...process.env, PI_WEBUI_SETTINGS_FILE: settingsFile },
55
85
  });
86
+ const childClosed = new Promise((resolve) => child.once("close", resolve));
56
87
  let serverOutput = "";
57
88
  child.stdout.on("data", (chunk) => { serverOutput += String(chunk); });
58
89
  child.stderr.on("data", (chunk) => { serverOutput += String(chunk); });
@@ -113,6 +144,85 @@ try {
113
144
  assert.equal(queuedSlashPrompt.status, 202, "slash prompt sent during compaction should remain a prompt in the resume queue");
114
145
  assert.equal(queuedSlashPrompt.body?.data?.queueLength, 4);
115
146
 
147
+ const compactionQueueBeforeMutation = {
148
+ source: "webui-compaction",
149
+ revision: 4,
150
+ steering: [RESUME_PROMPT, STEER_PROMPT],
151
+ followUp: [FOLLOW_UP_PROMPT, QUEUED_SLASH_PROMPT],
152
+ };
153
+ const editedFollowUp = `${FOLLOW_UP_PROMPT} edited`;
154
+ const compactionEdit = await request("/api/queue/mutate", {
155
+ method: "POST",
156
+ body: {
157
+ tab: tabId,
158
+ source: "webui-compaction",
159
+ kind: "followUp",
160
+ revision: compactionQueueBeforeMutation.revision,
161
+ expected: { steering: compactionQueueBeforeMutation.steering, followUp: compactionQueueBeforeMutation.followUp },
162
+ operation: { type: "edit", index: 0, expectedText: FOLLOW_UP_PROMPT, text: ` ${editedFollowUp} ` },
163
+ },
164
+ });
165
+ assert.equal(compactionEdit.status, 200, `compaction follow-up edits should succeed before draining: ${compactionEdit.body?.error || ""}`);
166
+ assert.deepEqual(compactionEdit.body?.data, {
167
+ mutated: true,
168
+ source: "webui-compaction",
169
+ queue: {
170
+ source: "webui-compaction",
171
+ revision: 5,
172
+ steering: [RESUME_PROMPT, STEER_PROMPT],
173
+ followUp: [editedFollowUp, QUEUED_SLASH_PROMPT],
174
+ draining: false,
175
+ },
176
+ }, "compaction edits return an authoritative source-tagged revisioned snapshot");
177
+
178
+ const staleCompactionMove = await request("/api/queue/mutate", {
179
+ method: "POST",
180
+ body: {
181
+ tab: tabId,
182
+ source: "webui-compaction",
183
+ kind: "followUp",
184
+ revision: compactionQueueBeforeMutation.revision,
185
+ expected: { steering: compactionQueueBeforeMutation.steering, followUp: compactionQueueBeforeMutation.followUp },
186
+ operation: { type: "move", from: 1, to: 0, expectedText: QUEUED_SLASH_PROMPT },
187
+ },
188
+ });
189
+ assert.equal(staleCompactionMove.status, 409, "compaction mutations reject stale revisions and snapshots");
190
+ assert.equal(staleCompactionMove.body?.data?.reason, "queue-changed");
191
+
192
+ const compactionMove = await request("/api/queue/mutate", {
193
+ method: "POST",
194
+ body: {
195
+ tab: tabId,
196
+ source: "webui-compaction",
197
+ kind: "followUp",
198
+ revision: 5,
199
+ expected: { steering: [RESUME_PROMPT, STEER_PROMPT], followUp: [editedFollowUp, QUEUED_SLASH_PROMPT] },
200
+ operation: { type: "move", from: 1, to: 0, expectedText: QUEUED_SLASH_PROMPT },
201
+ },
202
+ });
203
+ assert.equal(compactionMove.status, 200, "compaction follow-up moves should reorder among the fixed follow-up slots");
204
+ assert.deepEqual(compactionMove.body?.data?.queue?.followUp, [QUEUED_SLASH_PROMPT, editedFollowUp]);
205
+ assert.deepEqual(compactionMove.body?.data?.queue?.steering, [RESUME_PROMPT, STEER_PROMPT], "compaction reordering must leave steering slots fixed");
206
+
207
+ const drainingCompactionQueue = await waitForSseEvent(
208
+ tabId,
209
+ (event) => event.type === "webui_compaction_queue_update" && event.source === "webui-compaction" && event.draining === true,
210
+ );
211
+ const drainingMutation = await request("/api/queue/mutate", {
212
+ method: "POST",
213
+ body: {
214
+ tab: tabId,
215
+ source: "webui-compaction",
216
+ kind: "followUp",
217
+ revision: 6,
218
+ expected: { steering: [RESUME_PROMPT, STEER_PROMPT], followUp: [QUEUED_SLASH_PROMPT, editedFollowUp] },
219
+ operation: { type: "edit", index: 0, expectedText: QUEUED_SLASH_PROMPT, text: "must not apply while draining" },
220
+ },
221
+ });
222
+ assert.equal(drainingCompactionQueue.event.revision, 7, "draining queue transition advances the monotonic queue revision");
223
+ assert.equal(drainingMutation.status, 409, "compaction mutations are rejected while draining");
224
+ assert.equal(drainingMutation.body?.data?.reason, "queue-draining");
225
+
116
226
  const messagesBeforeEnd = await request(`/api/messages?tab=${encodeURIComponent(tabId)}`);
117
227
  assert.equal(messagesBeforeEnd.status, 200);
118
228
  const queuedMessages = [RESUME_PROMPT, STEER_PROMPT, FOLLOW_UP_PROMPT, QUEUED_SLASH_PROMPT];
@@ -128,7 +238,7 @@ try {
128
238
  const resumedMessages = await waitFor("queued prompts to resume after compaction", async () => {
129
239
  const messages = await request(`/api/messages?tab=${encodeURIComponent(tabId)}`);
130
240
  const entries = messages.body?.data?.messages || [];
131
- const expected = [`prompt:${RESUME_PROMPT}`, `steer:${STEER_PROMPT}`, `follow_up:${FOLLOW_UP_PROMPT}`, `prompt:${QUEUED_SLASH_PROMPT}`];
241
+ const expected = [`prompt:${RESUME_PROMPT}`, `steer:${STEER_PROMPT}`, `prompt:${QUEUED_SLASH_PROMPT}`, `follow_up:${editedFollowUp}`];
132
242
  return expected.every((content, index) => String(entries[index]?.content || "") === content) ? messages : false;
133
243
  }, { attempts: 80, intervalMs: 100 });
134
244
  assert.equal(resumedMessages.status, 200);
@@ -160,7 +270,8 @@ try {
160
270
  assert.notEqual(child.exitCode, null, "server should exit after /api/shutdown");
161
271
  } finally {
162
272
  if (child.exitCode === null) child.kill("SIGKILL");
163
- await rm(cwd, { recursive: true, force: true });
273
+ await childClosed;
274
+ await rm(cwd, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
164
275
  }
165
276
 
166
277
  console.log("compaction-resume-harness.test.mjs passed");
@@ -17,6 +17,11 @@ assert.match(server, /async function flushCompactionQueue\(tab, event = \{\}\)[\
17
17
  assert.match(server, /async function flushCompactionQueue\(tab, event = \{\}\)[\s\S]*queuedPromptCommand\(item\)/, "compaction queue flush should start a new prompt when no run resumes automatically");
18
18
  assert.match(server, /function queuedRetryCommand\(item\)[\s\S]*queuedStreamingCommand\(item\)/, "post-compaction continuation should send later queued items as steering or follow-up messages");
19
19
  assert.match(server, /function stateWithPendingThinking\(tab, state\)[\s\S]*compactionQueueForTab\(tab\)\.length[\s\S]*pendingMessageCount/, "state responses should include Web UI compaction queue length while prompts wait to resume");
20
+ assert.match(server, /function eventForTabClients\(tab, event\)[\s\S]*event\?\.type === "queue_update"[\s\S]*source: "pi-runtime"/, "Pi runtime queue events should be decorated with their source at the server boundary");
21
+ assert.match(server, /function compactionQueueSnapshot\(tab\)[\s\S]*source: "webui-compaction"[\s\S]*revision: compactionQueueRevision\(tab\)[\s\S]*draining:/, "compaction queue snapshots should include source, monotonic revision, and draining state");
22
+ assert.match(server, /function mutateCompactionFollowUpQueue\(tab, request\)[\s\S]*if \(current\.draining\) return failed\("queue-draining"\)[\s\S]*request\.revision !== current\.revision[\s\S]*slots\.forEach\(\(slot, index\) => \{ queue\[slot\] = followUps\[index\]; \}\)/, "compaction mutations should reject draining/stale requests and only permute follow-up slots");
23
+ assert.match(server, /function mutateCompactionFollowUpQueue\(tab, request\)[\s\S]*queue\[slots\[operation\.index\]\]\.command\.message = operation\.text[\s\S]*advanceCompactionQueueRevision\(tab\)[\s\S]*broadcastTabEvent\(tab, compactionQueueEvent\(tab\)\)/, "compaction edits should preserve command metadata and emit one authoritative update after revision advancement");
24
+ assert.match(server, /url\.pathname === "\/api\/queue\/mutate" && req\.method === "POST"[\s\S]*request\.source === "webui-compaction"[\s\S]*mutateCompactionFollowUpQueue[\s\S]*status = data\?\.mutated === true \? 200 : conflict \? 409 : 400/, "queue mutation HTTP handling should keep compaction mutations source-specific and map conflicts to 409");
20
25
 
21
26
  assert.match(app, /function isRunActive\(\) \{\n\s+return !!currentState\?\.isStreaming \|\| !!currentState\?\.isCompacting/, "frontend should treat compaction as an active run for composer controls");
22
27
  assert.match(app, /const targetWasCompacting = !!currentState\?\.isCompacting;[\s\S]*const targetWasBusy = targetWasStreaming \|\| targetWasCompacting[\s\S]*if \(targetWasBusy\) body\.streamingBehavior = streamingBehavior \|\| busyBehavior/, "prompt send should use busy behavior while streaming or compacting");
@@ -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,112 @@
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
+ assert.match(
29
+ app,
30
+ /if \(response\.data\?\.changed !== false\) closeFileViewer\(\);\s*const nextContext = setActiveTabId\(response\.data\?\.tab\?\.id \|\| activeTabId\);\s*resetActiveTabUi\(\);/,
31
+ "a successful cwd change should discard the old workspace viewer instead of restoring its path in the replacement workspace",
32
+ );
33
+
34
+ assert.match(
35
+ app,
36
+ /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…"/,
37
+ "git footer fallback copy should distinguish active loading, terminal failure, cleared status, and discovery",
38
+ );
39
+ assert.match(
40
+ app,
41
+ /function waitForGitFooterPayloadSettlement\(tabContext, requestSerial\)[\s\S]*?gitFooterPayloadRequestSerialByTab\.get\(tabContext\.tabId\) !== requestSerial[\s\S]*?settleGitFooterPayload\(tabContext\.tabId, "failed"/,
42
+ "no-payload settlement should be bounded and reject stale request callbacks",
43
+ );
44
+ assert.match(
45
+ app,
46
+ /signal: AbortSignal\.timeout\(GIT_FOOTER_PAYLOAD_REQUEST_TIMEOUT_MS\)/,
47
+ "a hung footer refresh HTTP request should be bounded",
48
+ );
49
+ assert.match(
50
+ app,
51
+ /GIT_FOOTER_PAYLOAD_SETTLEMENT_TIMEOUT_MS[\s\S]*?Git footer refresh command is unavailable — reload to retry/,
52
+ "RPC command discovery should have a bounded loading window before actionable failure",
53
+ );
54
+ assert.match(
55
+ app,
56
+ /const validPayload = !!parseGitFooterWebuiPayloadRaw\(request\.statusText\);[\s\S]*?validPayload \? "ready" : "failed"/,
57
+ "a later valid live payload should recover failed or waiting footer state",
58
+ );
59
+ assert.match(
60
+ app,
61
+ /new Set\(\[\.\.\.gitFooterPayloadStateByTab\.keys\(\), \.\.\.gitFooterPayloadSettlementTimersByTab\.keys\(\), \.\.\.gitFooterPayloadRefreshInFlightByTab\]\)\) clearGitFooterPayloadState\(tabId\)/,
62
+ "feature toggles should clear footer state, timers, and in-flight markers",
63
+ );
64
+
65
+ assert.match(
66
+ server,
67
+ /async function updateTabCwd\(id, cwd\)[\s\S]*?cwdChangeInProgress[\s\S]*?makeHttpError\(409,[\s\S]*?performTabCwdUpdate/,
68
+ "overlapping cwd changes should be rejected per tab",
69
+ );
70
+ assert.match(
71
+ server,
72
+ /function scheduleSupervisorMetadataUpdate\(tab\)[\s\S]*?if \(tab\.cwdChangeInProgress\) return;[\s\S]*?updateMetadata\(supervisedTabMetadata\(tab\)\)/,
73
+ "stale full metadata writes should be deferred during cwd replacement",
74
+ );
75
+ assert.match(
76
+ server,
77
+ /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/,
78
+ "the server should reject stale detached supervisors and publish tab cwd only after replacement succeeds",
79
+ );
80
+ assert.match(
81
+ server,
82
+ /webui_cwd_change_failed[\s\S]*?makeHttpError\(502, `Could not restart/,
83
+ "replacement failures should produce an actionable SSE event and HTTP error",
84
+ );
85
+
86
+ assert.match(
87
+ supervisor,
88
+ /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/,
89
+ "commands should release their FIFO admission barrier before the full Pi response while writes remain serialized",
90
+ );
91
+ assert.doesNotMatch(
92
+ supervisor,
93
+ /async afterTabMutation\(/,
94
+ "commands must not chase a continuously moving mutation tail",
95
+ );
96
+ assert.match(
97
+ supervisor,
98
+ /async spawnChildCandidate\(child\)[\s\S]*?return \{ processChild, cwd, startedAt[\s\S]*?commitChild\(tab/,
99
+ "replacement children should be spawned privately before atomic publication",
100
+ );
101
+ assert.match(
102
+ supervisor,
103
+ /if \(tab\.child === processChild\) this\.handlePiLine[\s\S]*?text && tab\.child === processChild/,
104
+ "retired child stdout and stderr should be generation-fenced",
105
+ );
106
+ assert.match(
107
+ supervisor,
108
+ /const stopFailures = stopResults\.filter[\s\S]*?shutdown blocked by live child[\s\S]*?return false/,
109
+ "shutdown should retain ownership and state when a child cannot be stopped",
110
+ );
111
+
112
+ console.log("cwd-footer-reliability-static.test.mjs passed");