@firstpick/pi-package-webui 0.9.5 → 0.9.7

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 (82) hide show
  1. package/README.md +11 -5
  2. package/bin/pi-webui.mjs +457 -77
  3. package/lib/git-workflow-preferences.mjs +21 -1
  4. package/lib/optional-feature-catalog.mjs +1 -1
  5. package/lib/session-actions.mjs +20 -2
  6. package/lib/session-tree-event-targets.mjs +70 -0
  7. package/lib/subagent-launch-policy.mjs +375 -0
  8. package/lib/subagent-launch-slots.mjs +2 -1
  9. package/package.json +1 -1
  10. package/public/app.js +2539 -292
  11. package/public/index.html +87 -31
  12. package/public/service-worker.js +4 -1
  13. package/public/stream-derived-output.mjs +799 -0
  14. package/public/stream-markdown-tail.mjs +204 -0
  15. package/public/stream-output-controller.mjs +193 -51
  16. package/public/stream-render-scheduler.mjs +85 -0
  17. package/public/styles.css +501 -19
  18. package/public/transcript-renderer.mjs +73 -24
  19. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  20. package/tests/browser/composer-action-grid-reorder.spec.mjs +114 -31
  21. package/tests/browser/control-visibility.spec.mjs +141 -2
  22. package/tests/browser/events-tree-context-menu.spec.mjs +240 -0
  23. package/tests/browser/guided-git-fallback.spec.mjs +153 -0
  24. package/tests/browser/mobile-foundation.spec.mjs +28 -0
  25. package/tests/browser/stream-output-isolation.spec.mjs +308 -3
  26. package/tests/browser/user-noticeable-fixes.spec.mjs +204 -0
  27. package/tests/codex-fast-mode-static.test.mjs +2 -2
  28. package/tests/compact-sections-static.test.mjs +4 -0
  29. package/tests/composer-action-grid-reorder-static.test.mjs +8 -7
  30. package/tests/control-visibility-static.test.mjs +66 -3
  31. package/tests/controls-layout-static.test.mjs +3 -3
  32. package/tests/cwd-footer-reliability-static.test.mjs +1 -1
  33. package/tests/events-tree-context-menu-static.test.mjs +131 -0
  34. package/tests/fast-mode-client-static.test.mjs +5 -2
  35. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  36. package/tests/file-viewer-image-static.test.mjs +3 -3
  37. package/tests/fixtures/fake-pi.mjs +57 -10
  38. package/tests/fixtures/streaming-workloads.mjs +36 -0
  39. package/tests/footer-provider-usage-visual-static.test.mjs +15 -0
  40. package/tests/foreground-transcript-catch-up-static.test.mjs +7 -1
  41. package/tests/git-workflow-preferences.test.mjs +30 -1
  42. package/tests/guided-git-fallback-runtime.test.mjs +418 -0
  43. package/tests/guided-git-fallback-ui-static.test.mjs +60 -0
  44. package/tests/guided-git-message-reliability-static.test.mjs +8 -7
  45. package/tests/interaction-state-stability-static.test.mjs +3 -1
  46. package/tests/intercom-conversation-viewer-static.test.mjs +3 -3
  47. package/tests/intercom-conversations-http.test.mjs +16 -0
  48. package/tests/main-output-loading-static.test.mjs +3 -3
  49. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  50. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  51. package/tests/mobile-foundation-static.test.mjs +3 -3
  52. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  53. package/tests/mobile-static.test.mjs +80 -67
  54. package/tests/open-issue-wizard-static.test.mjs +1 -1
  55. package/tests/persistent-ui-layout-static.test.mjs +4 -4
  56. package/tests/prompt-input-vertical-scroll-static.test.mjs +26 -0
  57. package/tests/questionnaire-dialog.test.mjs +3 -3
  58. package/tests/remote-auth-settings-harness.test.mjs +23 -0
  59. package/tests/resource-defaults-helper.test.mjs +12 -0
  60. package/tests/runtime-error-visibility.test.mjs +3 -3
  61. package/tests/session-auth-harness.test.mjs +26 -1
  62. package/tests/session-sampling-helper.test.mjs +1 -0
  63. package/tests/session-sampling-ui-static.test.mjs +3 -3
  64. package/tests/session-tree-event-targets.test.mjs +106 -0
  65. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  66. package/tests/stream-derived-output.test.mjs +121 -0
  67. package/tests/stream-markdown-tail.test.mjs +218 -0
  68. package/tests/stream-output-controller.test.mjs +119 -4
  69. package/tests/stream-output-isolation-static.test.mjs +27 -6
  70. package/tests/stream-output-workloads.test.mjs +40 -3
  71. package/tests/stream-render-scheduler.test.mjs +115 -0
  72. package/tests/streaming-ui-coupling.test.mjs +1 -1
  73. package/tests/subagent-launch-policy.test.mjs +532 -0
  74. package/tests/subagent-observability-static.test.mjs +2 -2
  75. package/tests/subagents-helper.test.mjs +211 -1
  76. package/tests/syntax-highlighting-static.test.mjs +3 -3
  77. package/tests/tab-close-continuity-static.test.mjs +23 -0
  78. package/tests/theme-customizer-static.test.mjs +1 -1
  79. package/tests/thinking-format-parser.test.mjs +15 -0
  80. package/tests/todo-filter-static.test.mjs +148 -0
  81. package/tests/transcript-markdown-tail.test.mjs +137 -0
  82. package/webui-rpc-helper.mjs +220 -3
@@ -69,6 +69,12 @@ try {
69
69
  assert.equal(migrated.gitWorkflow.stagingPolicy, "review");
70
70
  assert.equal(migrated.gitWorkflow.reviewProcessEnabled, true, "legacy settings should preserve the existing review-process behavior");
71
71
  assert.equal(migrated.gitWorkflow.generation.thinkingLevel, "low");
72
+ assert.deepEqual(migrated.gitWorkflow.generation.fallback, {
73
+ provider: "",
74
+ modelId: "",
75
+ thinkingLevel: "low",
76
+ }, "legacy settings should keep fallback explicitly disabled");
77
+ assert.equal(isGitWorkflowSetupComplete({ ...migrated.gitWorkflow, generation: { provider: "fake", modelId: "fake-model", thinkingLevel: "off" } }), true, "fallback must remain optional for setup completeness");
72
78
  assert.equal(migrated.uiLayout.version, 3);
73
79
  assert.equal(migrated.uiLayout.sidePanel.placement, "right");
74
80
  assert.deepEqual(migrated.uiLayout.sidePanel.sectionLayout, { order: ["files", "controls", "git"], leftSectionIds: [] });
@@ -97,7 +103,13 @@ try {
97
103
  assert.equal((await readWebuiSettings(settingsFile)).outputModeDefault, "normal", "invalid persisted output modes must fail closed to normal");
98
104
 
99
105
  const saved = await writeGitWorkflowPreferences({
100
- generation: { provider: "fake", modelId: "fake-model", thinkingLevel: "off", unavailablePolicy: "ask" },
106
+ generation: {
107
+ provider: "fake",
108
+ modelId: "fake-model",
109
+ thinkingLevel: "off",
110
+ unavailablePolicy: "ask",
111
+ fallback: { provider: "other", modelId: "other-model", thinkingLevel: "medium" },
112
+ },
101
113
  commit: { language: "de", defaultVariant: "long", scope: "required" },
102
114
  stagingPolicy: "preserve",
103
115
  reviewProcessEnabled: false,
@@ -122,6 +134,17 @@ try {
122
134
 
123
135
  const partiallyUpdated = await writeGitWorkflowPreferences({ deliveryMode: "current" }, settingsFile);
124
136
  assert.equal(partiallyUpdated.generation.modelId, "fake-model", "partial updates should preserve the selected model");
137
+ assert.deepEqual(partiallyUpdated.generation.fallback, {
138
+ provider: "other",
139
+ modelId: "other-model",
140
+ thinkingLevel: "medium",
141
+ }, "unrelated partial updates should preserve the configured fallback");
142
+ const fallbackEffortOnly = await writeGitWorkflowPreferences({ generation: { fallback: { thinkingLevel: "high" } } }, settingsFile);
143
+ assert.deepEqual(fallbackEffortOnly.generation.fallback, {
144
+ provider: "other",
145
+ modelId: "other-model",
146
+ thinkingLevel: "high",
147
+ }, "nested fallback patches should preserve the selected fallback model");
125
148
  assert.equal(partiallyUpdated.commit.language, "de", "partial updates should preserve nested commit preferences");
126
149
  assert.equal(partiallyUpdated.deliveryMode, "current");
127
150
  assert.equal(partiallyUpdated.reviewProcessEnabled, false, "partial updates should preserve the review-process choice");
@@ -135,12 +158,18 @@ try {
135
158
  assert.equal(persisted.remoteAuthEnabled, true);
136
159
  assert.equal(persisted.outputModeDefault, "compact-v1", "output-mode default should persist beside existing Web UI settings");
137
160
  assert.equal(persisted.gitWorkflow.generation.provider, "fake");
161
+ assert.deepEqual(persisted.gitWorkflow.generation.fallback, {
162
+ provider: "other",
163
+ modelId: "other-model",
164
+ thinkingLevel: "high",
165
+ });
138
166
  assert.deepEqual(persisted.resourceDefaults.tools.enabledTools, ["read", "write"], "global tool defaults should be normalized and deduplicated");
139
167
  assert.deepEqual(persisted.resourceDefaults.skills.enabledSkills, ["repo-explorer", "code-security"], "global skill defaults should persist beside other Web UI settings");
140
168
  assert.equal(persisted.interfacePreferences.sidePanelWidth, 612, "the user-scoped Control Deck width should persist beside other Web UI settings");
141
169
  assert.equal((await readWebuiSettings(settingsFile)).interfacePreferences.sidePanelWidth, 612);
142
170
  const summary = gitWorkflowPreferencesSummary(await readGitWorkflowPreferences(settingsFile));
143
171
  assert.match(summary, /fake\/fake-model/);
172
+ assert.match(summary, /Fallback: other\/other-model · high/);
144
173
  assert.match(summary, /Review process: disabled/);
145
174
  if (process.platform !== "win32") assert.equal((await stat(settingsFile)).mode & 0o777, 0o600);
146
175
 
@@ -0,0 +1,418 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { createServer } from "node:net";
5
+ import { tmpdir } from "node:os";
6
+ import path from "node:path";
7
+ import { setTimeout as delay } from "node:timers/promises";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
11
+ const serverScript = path.join(packageRoot, "bin", "pi-webui.mjs");
12
+ const temporaryRoot = await mkdtemp(path.join(tmpdir(), "pi-webui-guided-git-fallback-"));
13
+ const fakePi = path.join(temporaryRoot, "fake-guided-git-pi.mjs");
14
+
15
+ await writeFile(fakePi, `#!/usr/bin/env node
16
+ import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ import { createInterface } from "node:readline";
19
+ const scenario = process.env.GUIDED_GIT_SCENARIO || "settled-success";
20
+ const logFile = process.env.GUIDED_GIT_LOG_FILE;
21
+ const artifactRoot = process.env.GUIDED_GIT_ARTIFACT_ROOT;
22
+ let activeModel = { provider: "fake", id: "original" };
23
+ let thinkingLevel = "high";
24
+ function log(value) { appendFileSync(logFile, JSON.stringify(value) + "\\n"); }
25
+ function send(value) { process.stdout.write(JSON.stringify(value) + "\\n"); }
26
+ function event(value) { log({ direction: "event", ...value }); send(value); }
27
+ function assistantFailure() { return { role: "assistant", stopReason: "error", content: [{ type: "text", text: "fixture failure" }] }; }
28
+ function writeCommitArtifacts(prefix) {
29
+ const directory = join(artifactRoot, "dev", "COMMIT");
30
+ mkdirSync(directory, { recursive: true });
31
+ writeFileSync(join(directory, "staged-commit-short.txt"), prefix + " short\\n");
32
+ writeFileSync(join(directory, "staged-commit-long.txt"), prefix + " long\\n");
33
+ }
34
+ function settle({ failed = false, wait = 20 } = {}) {
35
+ setTimeout(() => {
36
+ event({ type: "agent_start" });
37
+ if (failed) {
38
+ const message = assistantFailure();
39
+ event({ type: "message_end", message });
40
+ event({ type: "agent_end", willRetry: false, messages: [message] });
41
+ } else {
42
+ event({ type: "message_end", message: { role: "assistant", content: [{ type: "text", text: "fixture success" }] } });
43
+ event({ type: "agent_end" });
44
+ }
45
+ event({ type: "agent_settled" });
46
+ }, wait);
47
+ }
48
+ function settleAfterInternalRetry() {
49
+ setTimeout(() => {
50
+ const first = assistantFailure();
51
+ event({ type: "agent_start" });
52
+ event({ type: "message_end", message: first });
53
+ event({ type: "agent_end", willRetry: true, messages: [first] });
54
+ const final = assistantFailure();
55
+ event({ type: "agent_start" });
56
+ event({ type: "message_end", message: final });
57
+ event({ type: "agent_end", willRetry: false, messages: [final] });
58
+ event({ type: "agent_settled" });
59
+ }, 20);
60
+ }
61
+ const models = [
62
+ { provider: "fake", id: "original", name: "Original", reasoning: true },
63
+ { provider: "fake", id: "primary", name: "Primary", reasoning: true },
64
+ { provider: "fake", id: "fallback", name: "Fallback", reasoning: false },
65
+ ];
66
+ createInterface({ input: process.stdin }).on("line", (line) => {
67
+ let command;
68
+ try { command = JSON.parse(line); } catch { return; }
69
+ if (!command?.id || !command?.type) return;
70
+ log({ direction: "command", type: command.type, provider: command.provider, modelId: command.modelId, level: command.level, message: command.message, activeModel: activeModel.id, thinkingLevel });
71
+ const response = { type: "response", id: command.id, command: command.type, success: true };
72
+ switch (command.type) {
73
+ case "get_state":
74
+ send({ ...response, data: { model: activeModel, thinkingLevel, isStreaming: false, isCompacting: false, pendingMessageCount: 0, sessionId: "fixture", sessionName: "fixture" } });
75
+ break;
76
+ case "get_available_models":
77
+ send({ ...response, data: { models } });
78
+ break;
79
+ case "get_commands":
80
+ send({ ...response, data: { commands: [] } });
81
+ break;
82
+ case "get_messages":
83
+ send({ ...response, data: { messages: [] } });
84
+ break;
85
+ case "set_model": {
86
+ if ((scenario === "immediate-selection" || scenario === "immediate-double-failure") && command.modelId === "primary") {
87
+ send({ ...response, success: false, error: "SECRET primary selection failure at /private/provider/file.mjs:42" });
88
+ } else if ((scenario === "cancel-during-fallback-selection" && command.modelId === "fallback")
89
+ || (scenario === "cancel-during-primary-selection" && command.modelId === "primary")) {
90
+ setTimeout(() => {
91
+ activeModel = { provider: command.provider, id: command.modelId };
92
+ send({ ...response, data: activeModel });
93
+ }, 350);
94
+ } else {
95
+ activeModel = { provider: command.provider, id: command.modelId };
96
+ send({ ...response, data: activeModel });
97
+ }
98
+ break;
99
+ }
100
+ case "set_thinking_level":
101
+ if (scenario === "immediate-thinking" && activeModel.id === "primary" && command.level === "low") {
102
+ send({ ...response, success: false, error: "fixture primary effort failure" });
103
+ } else {
104
+ thinkingLevel = command.level;
105
+ send({ ...response, data: { level: thinkingLevel } });
106
+ }
107
+ break;
108
+ case "prompt": {
109
+ const model = activeModel.id;
110
+ if ((scenario === "fallback-prompt-failure" || scenario === "immediate-double-failure") && model === "fallback") {
111
+ send({ ...response, success: false, error: "SECRET fallback rejection at /private/provider/file.mjs:99" });
112
+ break;
113
+ }
114
+ if (scenario === "immediate-prompt" && model === "primary") {
115
+ send({ ...response, success: false, error: "fixture primary prompt failure" });
116
+ break;
117
+ }
118
+ if (scenario === "settlement-before-response" && model === "primary") {
119
+ const message = assistantFailure();
120
+ event({ type: "agent_start" });
121
+ event({ type: "message_end", message });
122
+ event({ type: "agent_end", willRetry: false, messages: [message] });
123
+ event({ type: "agent_settled" });
124
+ setTimeout(() => send({ ...response, data: { output: "late prompt acknowledgement" } }), 80);
125
+ break;
126
+ }
127
+ send({ ...response, data: { output: "fixture prompt accepted" } });
128
+ if (scenario === "process-loss" && model === "primary") {
129
+ event({ type: "agent_start" });
130
+ setTimeout(() => process.exit(7), 30);
131
+ break;
132
+ }
133
+ if (scenario === "will-retry-final-failure" && model === "primary") {
134
+ settleAfterInternalRetry();
135
+ break;
136
+ }
137
+ if (scenario === "artifact-primary-then-fallback" && model === "primary") {
138
+ writeCommitArtifacts("primary");
139
+ settle({ failed: true });
140
+ break;
141
+ }
142
+ if (scenario === "artifact-primary-then-fallback" && model === "fallback") {
143
+ setTimeout(() => writeCommitArtifacts("fallback"), 180);
144
+ settle({ failed: false, wait: 230 });
145
+ break;
146
+ }
147
+ const fallbackFailsAfterAcceptance = scenario === "fallback-settled-failure" && model === "fallback";
148
+ const primaryFails = model === "primary" && !["concurrent", "primary-success"].includes(scenario);
149
+ settle({ failed: fallbackFailsAfterAcceptance || primaryFails });
150
+ break;
151
+ }
152
+ default:
153
+ send({ ...response, data: {} });
154
+ }
155
+ });
156
+ `, "utf8");
157
+ await chmod(fakePi, 0o755);
158
+
159
+ function lines(text) {
160
+ return text.trim().split("\n").filter(Boolean).map((line) => JSON.parse(line));
161
+ }
162
+
163
+ async function waitFor(check, message, timeoutMs = 8_000) {
164
+ const deadline = Date.now() + timeoutMs;
165
+ while (Date.now() < deadline) {
166
+ if (await check()) return;
167
+ await delay(40);
168
+ }
169
+ assert.fail(message);
170
+ }
171
+
172
+ async function availablePort() {
173
+ const server = createServer();
174
+ await new Promise((resolve, reject) => {
175
+ server.once("error", reject);
176
+ server.listen(0, "127.0.0.1", resolve);
177
+ });
178
+ const address = server.address();
179
+ const port = typeof address === "object" && address ? address.port : 0;
180
+ await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
181
+ assert.ok(port > 0, "the OS should allocate a test server port");
182
+ return port;
183
+ }
184
+
185
+ async function readReplayedLifecycle(baseURL) {
186
+ const controller = new AbortController();
187
+ const response = await fetch(`${baseURL}/api/events`, { signal: controller.signal });
188
+ assert.equal(response.status, 200);
189
+ const reader = response.body.getReader();
190
+ const decoder = new TextDecoder();
191
+ let text = "";
192
+ const events = [];
193
+ const deadline = Date.now() + 3_000;
194
+ try {
195
+ while (Date.now() < deadline && events.length < 2) {
196
+ const result = await Promise.race([
197
+ reader.read(),
198
+ delay(500).then(() => ({ timeout: true })),
199
+ ]);
200
+ if (result.timeout) continue;
201
+ if (result.done) break;
202
+ text += decoder.decode(result.value, { stream: true });
203
+ const frames = text.split("\n\n");
204
+ text = frames.pop() || "";
205
+ for (const frame of frames) {
206
+ const data = frame.split("\n").find((line) => line.startsWith("data: "))?.slice(6);
207
+ if (!data) continue;
208
+ const event = JSON.parse(data);
209
+ if (String(event.type || "").startsWith("webui_git_workflow_generation_fallback_")) events.push(event);
210
+ }
211
+ }
212
+ } finally {
213
+ controller.abort();
214
+ }
215
+ return events;
216
+ }
217
+
218
+ async function runScenario(scenario, verify) {
219
+ const cwd = path.join(temporaryRoot, scenario);
220
+ const settingsFile = path.join(cwd, "settings.json");
221
+ const logFile = path.join(cwd, "rpc.jsonl");
222
+ await mkdir(cwd, { recursive: true });
223
+ const git = spawnSync("git", ["init", "--quiet"], { cwd, encoding: "utf8" });
224
+ assert.equal(git.status, 0, git.stderr);
225
+ await writeFile(settingsFile, `${JSON.stringify({
226
+ version: 8,
227
+ gitWorkflow: {
228
+ generation: {
229
+ provider: "fake",
230
+ modelId: "primary",
231
+ thinkingLevel: "low",
232
+ unavailablePolicy: "ask",
233
+ fallback: { provider: "fake", modelId: "fallback", thinkingLevel: "off" },
234
+ },
235
+ },
236
+ }, null, 2)}\n`, "utf8");
237
+ if (scenario === "artifact-primary-then-fallback") {
238
+ await mkdir(path.join(cwd, "dev", "COMMIT"), { recursive: true });
239
+ await writeFile(path.join(cwd, "dev", "COMMIT", "staged-commit-short.txt"), "baseline short\n");
240
+ await writeFile(path.join(cwd, "dev", "COMMIT", "staged-commit-long.txt"), "baseline long\n");
241
+ }
242
+ const port = await availablePort();
243
+ const baseURL = `http://127.0.0.1:${port}`;
244
+ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
245
+ stdio: ["ignore", "pipe", "pipe"],
246
+ env: {
247
+ ...process.env,
248
+ PI_WEBUI_RPC_SUPERVISOR: "0",
249
+ PI_WEBUI_SETTINGS_FILE: settingsFile,
250
+ GUIDED_GIT_SCENARIO: scenario,
251
+ GUIDED_GIT_LOG_FILE: logFile,
252
+ GUIDED_GIT_ARTIFACT_ROOT: cwd,
253
+ },
254
+ });
255
+ let output = "";
256
+ child.stdout.on("data", (chunk) => { output += String(chunk); });
257
+ child.stderr.on("data", (chunk) => { output += String(chunk); });
258
+ const request = async (pathname, { method = "GET", body, timeoutMs = 5_000 } = {}) => {
259
+ const response = await fetch(`${baseURL}${pathname}`, {
260
+ method,
261
+ headers: body === undefined ? undefined : { "Content-Type": "application/json" },
262
+ body: body === undefined ? undefined : JSON.stringify(body),
263
+ signal: AbortSignal.timeout(timeoutMs),
264
+ });
265
+ return { status: response.status, body: await response.json() };
266
+ };
267
+ try {
268
+ await waitFor(async () => {
269
+ try { return (await request("/api/health")).status === 200; } catch { return false; }
270
+ }, `server did not start for ${scenario}:\n${output}`, 20_000);
271
+ const readLog = async () => lines(await readFile(logFile, "utf8").catch(() => ""));
272
+ await verify({ request, readLog, baseURL, output: () => output });
273
+ } finally {
274
+ child.kill("SIGTERM");
275
+ await delay(120);
276
+ if (child.exitCode === null) child.kill("SIGKILL");
277
+ }
278
+ }
279
+
280
+ await runScenario("concurrent", async ({ request, readLog }) => {
281
+ const [left, right] = await Promise.all([
282
+ request("/api/git-workflow/generate", { method: "POST", body: { kind: "branch" } }),
283
+ request("/api/git-workflow/generate", { method: "POST", body: { kind: "branch" } }),
284
+ ]);
285
+ assert.deepEqual([left.status, right.status].sort((a, b) => a - b), [200, 409], "one concurrent request must own the tab and one must be rejected");
286
+ await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "original"), "the accepted generation should settle and restore");
287
+ assert.equal((await readLog()).filter((entry) => entry.type === "prompt").length, 1, "concurrent requests must dispatch exactly one prompt");
288
+ });
289
+
290
+ await runScenario("immediate-selection", async ({ request, readLog }) => {
291
+ const invalidKind = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "invalid" } });
292
+ assert.equal(invalidKind.status, 400);
293
+ assert.equal((await readLog()).filter((entry) => entry.type === "set_model").length, 0);
294
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
295
+ assert.equal(result.status, 200);
296
+ assert.equal(result.body.data.fallbackUsed, true);
297
+ assert.match(result.body.data.generationId, /^[0-9a-f-]{36}$/i);
298
+ await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "original"), "immediate fallback should restore");
299
+ const restoredLog = await readLog();
300
+ const restoredModelIndex = restoredLog.findIndex((entry) => entry.type === "set_model" && entry.modelId === "original");
301
+ const restoredEffortIndex = restoredLog.findIndex((entry, index) => index > restoredModelIndex && entry.type === "set_thinking_level" && entry.level === "high");
302
+ assert.ok(restoredModelIndex >= 0 && restoredEffortIndex > restoredModelIndex, "restoration should reapply the original reasoning effort after the original model");
303
+ assert.equal(restoredLog.filter((entry) => entry.type === "prompt").length, 1);
304
+ });
305
+
306
+ for (const scenario of ["immediate-thinking", "immediate-prompt"]) {
307
+ await runScenario(scenario, async ({ request, readLog }) => {
308
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "branch" } });
309
+ assert.equal(result.status, 200);
310
+ assert.equal(result.body.data.fallbackUsed, true);
311
+ assert.match(result.body.data.generationId, /^[0-9a-f-]{36}$/i, "every generation kind must receive a server ID");
312
+ await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "original"), `${scenario} should restore`);
313
+ const prompts = (await readLog()).filter((entry) => entry.type === "prompt");
314
+ assert.equal(prompts.filter((entry) => entry.activeModel === "fallback").length, 1);
315
+ if (scenario === "immediate-prompt") assert.equal(prompts[0].message, prompts[1].message);
316
+ });
317
+ }
318
+
319
+ await runScenario("will-retry-final-failure", async ({ request, readLog }) => {
320
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "pr" } });
321
+ assert.equal(result.status, 200);
322
+ assert.match(result.body.data.generationId, /^[0-9a-f-]{36}$/i);
323
+ await waitFor(async () => (await readLog()).filter((entry) => entry.type === "prompt").length === 2, "fallback should run after final settlement");
324
+ const log = await readLog();
325
+ const retryEnd = log.findIndex((entry) => entry.type === "agent_end" && entry.willRetry === true);
326
+ const fallbackPrompt = log.findIndex((entry) => entry.type === "prompt" && entry.activeModel === "fallback");
327
+ assert.ok(retryEnd >= 0 && fallbackPrompt > retryEnd, "Pi internal retry must occur before server fallback");
328
+ assert.equal(log.filter((entry) => entry.type === "prompt" && entry.activeModel === "fallback").length, 1);
329
+ });
330
+
331
+ await runScenario("settlement-before-response", async ({ request, readLog }) => {
332
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "branch" } });
333
+ assert.equal(result.status, 200);
334
+ await waitFor(async () => (await readLog()).filter((entry) => entry.type === "prompt").length === 2, "pending settlement must start one fallback");
335
+ assert.equal((await readLog()).filter((entry) => entry.type === "prompt" && entry.activeModel === "fallback").length, 1);
336
+ });
337
+
338
+ await runScenario("fallback-settled-failure", async ({ request, readLog }) => {
339
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
340
+ assert.equal(result.status, 200);
341
+ await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "original"), "accepted fallback failure should restore");
342
+ const status = await request("/api/webui-status?detailed=true&events=100");
343
+ assert.equal(status.body.data.events.filter((event) => event.type === "webui_git_workflow_generation_fallback_failed").length, 1);
344
+ assert.equal((await readLog()).filter((entry) => entry.type === "prompt" && entry.activeModel === "fallback").length, 1);
345
+ });
346
+
347
+ await runScenario("cancel-during-primary-selection", async ({ request, readLog }) => {
348
+ const pending = request("/api/git-workflow/generate", { method: "POST", body: { kind: "branch" } });
349
+ await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "primary"), "primary selection should be delayed");
350
+ const cancellation = await request("/api/git-workflow/cancel", { method: "POST", body: {} });
351
+ assert.equal(cancellation.body.data.cancelled, true);
352
+ const result = await pending;
353
+ assert.equal(result.status, 409);
354
+ assert.match(result.body.error, /cancelled/i, "primary cancellation should keep its ordinary error instead of masquerading as fallback failure");
355
+ await waitFor(async () => (await readLog()).filter((entry) => entry.type === "set_model" && entry.modelId === "original").length >= 1, "cancelled primary selection should restore");
356
+ assert.equal((await readLog()).filter((entry) => entry.type === "prompt").length, 0, "cancelled primary selection must never dispatch a prompt");
357
+ });
358
+
359
+ await runScenario("cancel-during-fallback-selection", async ({ request, readLog }) => {
360
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "branch" } });
361
+ assert.equal(result.status, 200);
362
+ await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "fallback"), "fallback selection should be delayed");
363
+ const cancellation = await request("/api/git-workflow/cancel", { method: "POST", body: {} });
364
+ assert.equal(cancellation.body.data.cancelled, true);
365
+ await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "original"), "cancellation should restore ownership profile");
366
+ assert.equal((await readLog()).filter((entry) => entry.type === "prompt" && entry.activeModel === "fallback").length, 0, "cancelled fallback selection must never dispatch a prompt");
367
+ });
368
+
369
+ await runScenario("artifact-primary-then-fallback", async ({ request, readLog }) => {
370
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
371
+ assert.equal(result.status, 200);
372
+ const generationId = result.body.data.generationId;
373
+ await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "fallback"), "fallback should begin after primary artifacts");
374
+ const intermediate = await request(`/api/git-workflow/message?generationId=${encodeURIComponent(generationId)}`);
375
+ assert.equal(intermediate.body.data.ready, false, "failed-primary artifacts must remain pending while fallback runs");
376
+ await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "original"), "fallback artifact generation should settle");
377
+ const final = await request(`/api/git-workflow/message?generationId=${encodeURIComponent(generationId)}`);
378
+ assert.equal(final.body.data.ready, true);
379
+ assert.equal(final.body.data.short, "fallback short");
380
+ assert.equal(final.body.data.long, "fallback long");
381
+ });
382
+
383
+ await runScenario("immediate-double-failure", async ({ request, baseURL }) => {
384
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "pr" } });
385
+ assert.equal(result.status, 500);
386
+ assert.equal(result.body.error, "Guided Git generation failed after the configured model attempts.");
387
+ assert.match(result.body.gitWorkflowGeneration.generationId, /^[0-9a-f-]{36}$/i);
388
+ const replayed = await readReplayedLifecycle(baseURL);
389
+ assert.deepEqual(replayed.map((event) => event.type), [
390
+ "webui_git_workflow_generation_fallback_started",
391
+ "webui_git_workflow_generation_fallback_failed",
392
+ ]);
393
+ for (const event of replayed) {
394
+ assert.equal(event.replayed, true);
395
+ assert.equal(event.generationId, result.body.gitWorkflowGeneration.generationId);
396
+ assert.doesNotMatch(JSON.stringify(event), /SECRET|private\/provider|file\.mjs/i, "lifecycle messages must be bounded and redacted");
397
+ }
398
+ });
399
+
400
+ await runScenario("process-loss", async ({ request, readLog }) => {
401
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
402
+ assert.equal(result.status, 200);
403
+ await waitFor(async () => (await readLog()).some((entry) => entry.type === "agent_start"), "process-loss run should start");
404
+ await delay(250);
405
+ const log = await readLog();
406
+ assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "fallback").length, 0, "process loss must not start fallback");
407
+ const artifact = await request(`/api/git-workflow/message?generationId=${encodeURIComponent(result.body.data.generationId)}`);
408
+ assert.equal(artifact.body.data.ready, false);
409
+ assert.equal(artifact.body.data.expired, true);
410
+ });
411
+
412
+ const serverSource = await readFile(serverScript, "utf8");
413
+ assert.match(serverSource, /tab\.gitWorkflowGeneration = record;[\s\S]*await assertExpectedStagedContentHash/, "tab ownership must be reserved before preflight awaits");
414
+ assert.match(serverSource, /modelResponse = await[\s\S]*assertGitWorkflowGenerationOwnership[\s\S]*thinkingResponse = await[\s\S]*assertGitWorkflowGenerationOwnership/, "profile awaits must recheck exact ownership");
415
+ assert.match(serverSource, /replayGitWorkflowFallbackLifecycle\(tab, client\)/, "EventSource connections must replay bounded fallback lifecycle state");
416
+
417
+ await rm(temporaryRoot, { recursive: true, force: true });
418
+ console.log("guided-git-fallback-runtime.test.mjs passed");
@@ -0,0 +1,60 @@
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, html, serviceWorker, readme, technical, development] = 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, "public", "index.html"), "utf8"),
12
+ readFile(path.join(packageDir, "public", "service-worker.js"), "utf8"),
13
+ readFile(path.join(packageDir, "README.md"), "utf8"),
14
+ readFile(path.join(packageDir, "TECHNICAL.md"), "utf8"),
15
+ readFile(path.join(packageDir, "DEVELOPMENT.md"), "utf8"),
16
+ ]);
17
+
18
+ function sourceBetween(source, start, end, label) {
19
+ const startIndex = source.indexOf(start);
20
+ const endIndex = source.indexOf(end, startIndex + start.length);
21
+ assert.ok(startIndex >= 0 && endIndex > startIndex, `${label} source should be extractable`);
22
+ return source.slice(startIndex, endIndex);
23
+ }
24
+
25
+ const setup = sourceBetween(app, "async function openNativeGitWorkflowSetupDialog", "function normalizedWorkflowPolicyList", "Guided Git setup");
26
+ assert.match(setup, /configuredFallbackKey[\s\S]*initialFallbackKey/, "setup should restore an available configured fallback");
27
+ assert.match(setup, /\{ value: "", label: "No fallback" \}/, "fallback choices should include an explicit disabled option");
28
+ assert.match(setup, /modelOptions\.filter\(\(option\) => option\.value !== primaryKey\)/, "the selected primary must be excluded from fallback choices");
29
+ assert.match(setup, /Fallback reasoning effort[\s\S]*syncFallbackThinkingLevels[\s\S]*thinkingLevelsForModel\(fallbackKey\)/, "fallback effort should follow the fallback model capabilities");
30
+ assert.match(setup, /controls\.fallbackThinking\.select\.disabled = !fallbackKey/, "fallback effort should be disabled when no fallback is selected");
31
+ assert.match(setup, /fallback:\s*\{[\s\S]*provider: selectedFallback\?\.provider \|\| ""[\s\S]*modelId: selectedFallback\?\.id \|\| ""[\s\S]*thinkingLevel:/, "saving should send the complete nested fallback contract with empty provider/model fields when disabled");
32
+ assert.match(setup, /Guided Git setup saved\. Primary:[\s\S]*Fallback:/, "save confirmation should identify primary and fallback state");
33
+
34
+ const acceptedText = sourceBetween(app, "function gitWorkflowGenerationAcceptedText", "function gitWorkflowFallbackEventMatches", "immediate fallback copy");
35
+ assert.match(acceptedText, /fallbackUsed === true[\s\S]*primaryGeneration[\s\S]*continued with the fallback/, "immediate fallback responses should explain that primary failed and fallback continued");
36
+ assert.match(app, /gitWorkflowConfiguredGenerationText\(preferences\)[\s\S]*active tab model and effort are restored/, "workflow startup should identify configured generation profiles and restoration");
37
+
38
+ const lifecycle = sourceBetween(app, "function gitWorkflowFallbackEventMatchesPendingRequest", "function formatGitCommandResult", "fallback lifecycle handler");
39
+ assert.match(lifecycle, /webui_git_workflow_generation_fallback_started/, "the browser should observe fallback start events");
40
+ assert.match(lifecycle, /webui_git_workflow_generation_fallback_failed/, "the browser should observe fallback failure events");
41
+ assert.match(lifecycle, /fallbackLifecycleKeys instanceof Set[\s\S]*keys\.has\(key\)[\s\S]*keys\.add\(key\)/, "lifecycle output should be deduplicated");
42
+ assert.match(lifecycle, /pendingFallbackLifecycleEvents[\s\S]*slice\(-4\)/, "pre-response lifecycle events should be buffered with a fixed bound");
43
+ assert.match(lifecycle, /flushPendingGitWorkflowFallbackLifecycleEvents[\s\S]*generationAccepted: true[\s\S]*flushPendingGitWorkflowFallbackLifecycleEvents\(tabId\)/, "buffered lifecycle events should flush only after response correlation");
44
+ assert.match(lifecycle, /generationId[\s\S]*workflow\.generationId/, "all lifecycle kinds should require the exact server generation ID");
45
+ assert.doesNotMatch(lifecycle, /\bapi\(|gitWorkflowRequest\(|fetch\(/, "browser lifecycle handling must never dispatch fallback or another request");
46
+ assert.match(server, /lifecycle\.events = [\s\S]*\.slice\(-2\)/, "the server should retain a bounded per-tab lifecycle replay snapshot");
47
+ assert.match(server, /replayGitWorkflowFallbackLifecycle\(tab, client\)/, "EventSource reconnect should replay Guided Git lifecycle state");
48
+ assert.match(server, /reason: boundedGitWorkflowGenerationError\("The primary Git-writing model ended with an error\."\)/, "lifecycle reason copy should be curated rather than exposing provider diagnostics");
49
+ assert.match(app, /handleGitWorkflowFallbackLifecycleEvent\(event\)\) return;[\s\S]*if \(!eventTargetsActiveTab\(event\)\)/, "tab-scoped fallback events should be handled before inactive-tab routing");
50
+ assert.match(app, /generationKind: "commit"[\s\S]*generationKind: "branch"[\s\S]*generationKind: "pr"/, "all three Guided Git generation kinds should register browser correlation state");
51
+ assert.match(app, /branch-name\$\{query\}[\s\S]*pr-description\$\{query\}/, "branch and PR artifact reads should send their exact generation IDs");
52
+
53
+ assert.match(readme, /fallback model and its own reasoning effort[\s\S]*tries the fallback once[\s\S]*stopped Pi process do not trigger fallback/i, "README should explain the optional fallback and essential limits");
54
+ assert.match(technical, /## Guided Git generation profiles[\s\S]*strict one-retry policy[\s\S]*model and reasoning effort are restored[\s\S]*dead Pi process cannot run the fallback/i, "technical reference should document configuration and operational limits");
55
+ assert.match(development, /### Fallback browser\/runtime contract[\s\S]*fallbackUsed: true[\s\S]*webui_git_workflow_generation_fallback_started[\s\S]*never sends a retry/, "development guide should preserve the response/event and browser ownership contract");
56
+
57
+ assert.match(html, /data-app-src="\/app\.js\?v=166"/, "the changed browser app should use the next query revision");
58
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v132";/, "the PWA cache identity should advance with browser behavior");
59
+
60
+ console.log("guided-git-fallback-ui-static.test.mjs passed");
@@ -11,21 +11,22 @@ const [app, server, artifacts] = await Promise.all([
11
11
  readFile(path.join(packageDir, "lib", "git-message-artifacts.mjs"), "utf8"),
12
12
  ]);
13
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");
14
+ assert.match(server, /async function createGitWorkflowMessageGeneration\(tab, generationId\)[\s\S]*id: generationId[\s\S]*baseline: await readStableGitMessageArtifactPair\(paths\)/, "commit generation must retain the shared server-owned ID and exact pre-primary baseline");
15
+ assert.match(server, /generationId: record\.generationId/, "generation dispatch must return one server-owned correlation ID across every kind and both attempts");
16
+ assert.match(server, /tab\.gitWorkflowArtifactGeneration = record\.artifactGeneration/, "the artifact generation record must be owned by the originating tab");
17
+ assert.match(server, /case "\/api\/git-workflow\/message"[\s\S]*generationId[\s\S]*tab\?\.gitWorkflowArtifactGeneration/, "fresh message reads must resolve the correlated generation from the requested tab");
18
+ assert.match(server, /readGitWorkflowMessages\(cwd, \{ generationId = "", generation = null \} = \{\}\)[\s\S]*generation\.cwd !== messageCwd[\s\S]*!generation\.terminal[\s\S]*!generation\.successful/, "message readiness must reject wrong identity, active attempts, and terminal failure");
19
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
20
  assert.doesNotMatch(app, /newestMtime \+ 10000 < currentWorkflow\.messageRequestedAt/, "freshness must not use the previous wall-clock/mtime tolerance");
21
21
 
22
22
  assert.match(app, /const gitWorkflowMessageLoadsByTab = new Map\(\)/, "browser message loading must have tab-scoped single-flight ownership");
23
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");
24
+ assert.match(app, /function acceptGitWorkflowGenerationCorrelation[\s\S]*generationId[\s\S]*messageGenerationId: generation\.kind === "commit" \? generationId[\s\S]*generationAccepted: true/, "the browser must bind the returned generation ID and accepted attempt before loading files");
25
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
26
  assert.match(app, /gitWorkflowMessageLoadIsCurrent\(tabId, expectedRunId, expectedGenerationId\)/, "poll results must be guarded by tab, run, and generation identity");
27
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");
28
+ assert.match(app, /\?generationId=\$\{encodeURIComponent\(expectedGenerationId\)\}/, "fresh commit reads must send the correlation ID to the backend");
29
+ assert.match(app, /branch-name\$\{query\}[\s\S]*pr-description\$\{query\}/, "fresh branch and PR reads must also send exact generation IDs");
29
30
  assert.match(app, /message\.ready === false[\s\S]*message\.expired[\s\S]*Regenerate/, "pending and expired generation states must remain actionable");
30
31
  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
32
  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");
@@ -227,7 +227,9 @@ assert.match(updateTextSurface, /_transcriptTextNode[\s\S]*node\.appendData\(val
227
227
  // Stable committed blocks and a bounded mutable tail.
228
228
  assert.match(reconcileMarkdownSurface, /if \(boundary > state\.stableText\.length\)/, "committed blocks must never be re-rendered for append-only input");
229
229
  assert.match(reconcileMarkdownSurface, /for \(const node of state\.tailNodes\) node\.remove\(\)/, "only the mutable tail may be detached during streaming");
230
- assert.match(reconcileMarkdownSurface, /const diverged = !!state && !value\.startsWith\(state\.stableText\);[\s\S]*invalidateSelection: diverged/, "authoritative divergence must explicitly invalidate selection rather than silently rebuilding");
230
+ assert.match(reconcileMarkdownSurface, /const diverged = !!state && !value\.startsWith\(state\.value\);[\s\S]*invalidateSelection: diverged/, "authoritative divergence must compare the whole previous value and explicitly invalidate selection");
231
+ assert.match(reconcileMarkdownSurface, /canReuseLiveTail[\s\S]*appendLiveTail\(state\.tailNodes, state\.tailText, tail, boundaryInfo\)/, "open fences and bounded plain tails must append into their mounted live nodes");
232
+ assert.match(reconcileMarkdownSurface, /promotesMountedTail[\s\S]*ownBlocks\(state\.tailNodes[\s\S]*state\.tailNodes = \[\]/, "a newly stable mounted tail must be promoted without detaching its DOM");
231
233
 
232
234
  // Live settlement adoption.
233
235
  assert.match(authoritativeAssistantTextForAdoption, /if \(finalParts\.length !== 1\) return null;/, "multi-part settlement must not be fuzzy-adopted onto a single live surface");
@@ -95,9 +95,9 @@ assert.match(css, /\.composer-intercom-tag:hover,[\s\S]*\.composer-intercom-tag:
95
95
  assert.match(css, /\.extension-dialog\.intercom-conversation-dialog \{[\s\S]*width: min\(76rem,[\s\S]*height: min\(54rem,/, "the viewer should use a large in-app modal");
96
96
  assert.match(css, /@media \(max-width: 720px\)[\s\S]*\.composer-intercom-tag \{ min-height: 44px;[\s\S]*\.extension-dialog\.intercom-conversation-dialog[\s\S]*width: calc\(100vw - 0\.7rem\)/, "tags and the dialog should remain reachable on narrow and coarse-pointer layouts");
97
97
 
98
- assert.match(html, /\/styles\.css\?v=129/, "the stylesheet URL should advance for the bounded conversation tags");
99
- assert.match(html, /data-app-src="\/app\.js\?v=150"/, "the guarded app URL should advance for current browser wiring");
100
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v115"/, "the PWA cache identity should advance with browser assets");
98
+ assert.match(html, /\/styles\.css\?v=137/, "the stylesheet URL should advance for the bounded conversation tags");
99
+ assert.match(html, /data-app-src="\/app\.js\?v=166"/, "the guarded app URL should advance for current browser wiring");
100
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v132"/, "the PWA cache identity should advance with browser assets");
101
101
 
102
102
  assert.match(readme, /one compact tag per conversation appears beneath the composer/i, "the README should explain the user-visible entry point");
103
103
  assert.match(technical, /## Agent conversation viewer[\s\S]*Attachments, tool calls and results, thinking, stdout\/stderr, filesystem paths, raw session records/i, "the advanced guide should document privacy exclusions");
@@ -244,6 +244,22 @@ try {
244
244
  const outsideResponse = await request(server.port, `/api/intercom/conversations?tab=${encodeURIComponent(outsideTabId)}`);
245
245
  assert.equal(outsideResponse.status, 403, "server-derived session files outside allowed Pi roots must be rejected");
246
246
  assert.equal(JSON.stringify(outsideResponse.body).includes(outsideSessionFile), false, "confinement errors must not expose the rejected path");
247
+ await stopServer(server.child);
248
+ server = undefined;
249
+
250
+ // Fresh/empty session: the file is only created on first persist, so the
251
+ // endpoint must answer with an empty projection instead of erroring out
252
+ // every poll for the tab (regression for "Persisted session is unavailable").
253
+ const pendingSessionFile = path.join(sessionDir, "not-created-yet.jsonl");
254
+ server = await startServer(pendingSessionFile);
255
+ const pendingTabId = await startupTabId(server);
256
+ const pendingBasePath = `/api/intercom/conversations?tab=${encodeURIComponent(pendingTabId)}`;
257
+ const pendingSummary = await request(server.port, pendingBasePath);
258
+ assert.equal(pendingSummary.status, 200, pendingSummary.body?.error);
259
+ assert.deepEqual(pendingSummary.body?.data?.conversations, [], "a not-yet-persisted session must project zero conversations");
260
+ const pendingMissingConversation = await request(server.port, `${pendingBasePath}&conversation=conv_${"b".repeat(24)}`);
261
+ assert.equal(pendingMissingConversation.status, 404, "an explicit unknown conversation on an unpersisted session must still 404");
262
+ assert.equal(JSON.stringify(pendingMissingConversation.body).includes(pendingSessionFile), false, "the 404 must not expose the pending session path");
247
263
 
248
264
  console.log("intercom-conversations-http: ok");
249
265
  } finally {