@firstpick/pi-package-webui 0.9.6 → 0.9.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.
Files changed (70) hide show
  1. package/README.md +13 -5
  2. package/bin/pi-webui.mjs +480 -96
  3. package/index.ts +2 -1
  4. package/lib/git-workflow-preferences.mjs +21 -1
  5. package/lib/optional-feature-catalog.mjs +1 -1
  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 +1348 -131
  11. package/public/guided-git-command-state.mjs +175 -1
  12. package/public/index.html +48 -9
  13. package/public/service-worker.js +1 -1
  14. package/public/styles.css +387 -34
  15. package/public/transcript-renderer.mjs +62 -0
  16. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  17. package/tests/browser/control-visibility.spec.mjs +141 -2
  18. package/tests/browser/events-tree-context-menu.spec.mjs +240 -0
  19. package/tests/browser/footer-model-advanced-layout.spec.mjs +512 -0
  20. package/tests/browser/guided-git-extension-command.spec.mjs +180 -0
  21. package/tests/browser/guided-git-fallback.spec.mjs +218 -0
  22. package/tests/browser/interaction-continuity.spec.mjs +33 -0
  23. package/tests/codex-fast-mode-static.test.mjs +2 -2
  24. package/tests/compact-sections-static.test.mjs +4 -0
  25. package/tests/compaction-static.test.mjs +1 -1
  26. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  27. package/tests/control-visibility-static.test.mjs +66 -3
  28. package/tests/controls-layout-static.test.mjs +3 -3
  29. package/tests/events-tree-context-menu-static.test.mjs +131 -0
  30. package/tests/fast-mode-client-static.test.mjs +5 -2
  31. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  32. package/tests/file-viewer-image-static.test.mjs +3 -3
  33. package/tests/fixtures/fake-pi.mjs +34 -3
  34. package/tests/git-footer-context-menu-static.test.mjs +103 -1
  35. package/tests/git-workflow-preferences.test.mjs +30 -1
  36. package/tests/guided-git-activation-http.test.mjs +194 -0
  37. package/tests/guided-git-activation-static.test.mjs +80 -0
  38. package/tests/guided-git-activation.test.mjs +244 -0
  39. package/tests/guided-git-fallback-runtime.test.mjs +419 -0
  40. package/tests/guided-git-fallback-ui-static.test.mjs +60 -0
  41. package/tests/guided-git-message-reliability-static.test.mjs +9 -7
  42. package/tests/guided-git-optional-feature.test.mjs +31 -0
  43. package/tests/http-endpoints-harness.test.mjs +3 -0
  44. package/tests/interaction-state-stability-static.test.mjs +1 -1
  45. package/tests/intercom-conversation-viewer-static.test.mjs +3 -3
  46. package/tests/main-output-loading-static.test.mjs +11 -9
  47. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  48. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  49. package/tests/mobile-foundation-static.test.mjs +3 -3
  50. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  51. package/tests/mobile-static.test.mjs +92 -9
  52. package/tests/open-issue-wizard-static.test.mjs +1 -1
  53. package/tests/persistent-ui-layout-static.test.mjs +3 -3
  54. package/tests/prompt-input-vertical-scroll-static.test.mjs +6 -6
  55. package/tests/prompt-routing-input-clear-static.test.mjs +1 -1
  56. package/tests/questionnaire-dialog.test.mjs +3 -3
  57. package/tests/remote-auth-settings-harness.test.mjs +23 -0
  58. package/tests/resource-defaults-helper.test.mjs +12 -0
  59. package/tests/session-sampling-helper.test.mjs +1 -0
  60. package/tests/session-sampling-ui-static.test.mjs +3 -3
  61. package/tests/session-tree-event-targets.test.mjs +106 -0
  62. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  63. package/tests/subagent-launch-policy.test.mjs +532 -0
  64. package/tests/subagent-observability-static.test.mjs +2 -2
  65. package/tests/subagents-helper.test.mjs +211 -1
  66. package/tests/syntax-highlighting-static.test.mjs +3 -3
  67. package/tests/tab-close-continuity-static.test.mjs +25 -0
  68. package/tests/theme-customizer-static.test.mjs +1 -1
  69. package/tests/thinking-block-grouping.test.mjs +79 -0
  70. package/webui-rpc-helper.mjs +220 -3
@@ -0,0 +1,419 @@
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
+ assert.equal(intermediate.body.data.running, true, "the browser must be told that the correlated fallback generation is still active");
377
+ await waitFor(async () => (await readLog()).some((entry) => entry.type === "set_model" && entry.modelId === "original"), "fallback artifact generation should settle");
378
+ const final = await request(`/api/git-workflow/message?generationId=${encodeURIComponent(generationId)}`);
379
+ assert.equal(final.body.data.ready, true);
380
+ assert.equal(final.body.data.short, "fallback short");
381
+ assert.equal(final.body.data.long, "fallback long");
382
+ });
383
+
384
+ await runScenario("immediate-double-failure", async ({ request, baseURL }) => {
385
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "pr" } });
386
+ assert.equal(result.status, 500);
387
+ assert.equal(result.body.error, "Guided Git generation failed after the configured model attempts.");
388
+ assert.match(result.body.gitWorkflowGeneration.generationId, /^[0-9a-f-]{36}$/i);
389
+ const replayed = await readReplayedLifecycle(baseURL);
390
+ assert.deepEqual(replayed.map((event) => event.type), [
391
+ "webui_git_workflow_generation_fallback_started",
392
+ "webui_git_workflow_generation_fallback_failed",
393
+ ]);
394
+ for (const event of replayed) {
395
+ assert.equal(event.replayed, true);
396
+ assert.equal(event.generationId, result.body.gitWorkflowGeneration.generationId);
397
+ assert.doesNotMatch(JSON.stringify(event), /SECRET|private\/provider|file\.mjs/i, "lifecycle messages must be bounded and redacted");
398
+ }
399
+ });
400
+
401
+ await runScenario("process-loss", async ({ request, readLog }) => {
402
+ const result = await request("/api/git-workflow/generate", { method: "POST", body: { kind: "commit" } });
403
+ assert.equal(result.status, 200);
404
+ await waitFor(async () => (await readLog()).some((entry) => entry.type === "agent_start"), "process-loss run should start");
405
+ await delay(250);
406
+ const log = await readLog();
407
+ assert.equal(log.filter((entry) => entry.type === "set_model" && entry.modelId === "fallback").length, 0, "process loss must not start fallback");
408
+ const artifact = await request(`/api/git-workflow/message?generationId=${encodeURIComponent(result.body.data.generationId)}`);
409
+ assert.equal(artifact.body.data.ready, false);
410
+ assert.equal(artifact.body.data.expired, true);
411
+ });
412
+
413
+ const serverSource = await readFile(serverScript, "utf8");
414
+ assert.match(serverSource, /tab\.gitWorkflowGeneration = record;[\s\S]*await assertExpectedStagedContentHash/, "tab ownership must be reserved before preflight awaits");
415
+ assert.match(serverSource, /modelResponse = await[\s\S]*assertGitWorkflowGenerationOwnership[\s\S]*thinkingResponse = await[\s\S]*assertGitWorkflowGenerationOwnership/, "profile awaits must recheck exact ownership");
416
+ assert.match(serverSource, /replayGitWorkflowFallbackLifecycle\(tab, client\)/, "EventSource connections must replay bounded fallback lifecycle state");
417
+
418
+ await rm(temporaryRoot, { recursive: true, force: true });
419
+ 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=172"/, "the changed browser app should use the next query revision");
58
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v139";/, "the PWA cache identity should advance with browser behavior");
59
+
60
+ console.log("guided-git-fallback-ui-static.test.mjs passed");
@@ -11,21 +11,23 @@ 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]*running: true[\s\S]*!generation\.successful/, "message readiness must reject wrong identity and terminal failure while identifying an active attempt");
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, /message\.running === true\) deadline = Date\.now\(\) \+ GIT_WORKFLOW_MESSAGE_POLL_TIMEOUT_MS/, "an active fallback generation must renew the artifact-settle deadline instead of forcing manual preview");
29
+ assert.match(app, /\?generationId=\$\{encodeURIComponent\(expectedGenerationId\)\}/, "fresh commit reads must send the correlation ID to the backend");
30
+ assert.match(app, /branch-name\$\{query\}[\s\S]*pr-description\$\{query\}/, "fresh branch and PR reads must also send exact generation IDs");
29
31
  assert.match(app, /message\.ready === false[\s\S]*message\.expired[\s\S]*Regenerate/, "pending and expired generation states must remain actionable");
30
32
  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
33
  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");
@@ -0,0 +1,31 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { readFile } from "node:fs/promises";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { OPTIONAL_FEATURE_BY_ID, OPTIONAL_FEATURE_CATALOG } from "../lib/optional-feature-catalog.mjs";
7
+
8
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
9
+ const app = await readFile(join(root, "public", "app.js"), "utf8");
10
+ const extensionManifest = JSON.parse(await readFile(join(root, "..", "pi-extension-git-guided-workflow", "package.json"), "utf8"));
11
+
12
+ test("Optional Features installs the Guided Git extension that bundles its prompt companion", () => {
13
+ assert.deepEqual(OPTIONAL_FEATURE_BY_ID.get("gitWorkflow"), {
14
+ featureId: "gitWorkflow",
15
+ packageName: "@firstpick/pi-extension-git-guided-workflow",
16
+ expectedSpec: "^0.1.0",
17
+ });
18
+ assert.equal(OPTIONAL_FEATURE_BY_ID.has("gitGuidedWorkflow"), false, "one package install should own the complete Guided Git feature");
19
+ assert.equal(new Set(OPTIONAL_FEATURE_CATALOG.map(({ featureId }) => featureId)).size, OPTIONAL_FEATURE_CATALOG.length);
20
+ assert.equal(new Set(OPTIONAL_FEATURE_CATALOG.map(({ packageName }) => packageName)).size, OPTIONAL_FEATURE_CATALOG.length);
21
+
22
+ assert.equal(extensionManifest.dependencies?.["@firstpick/pi-prompts-git-pr"], "^0.1.6");
23
+ assert.deepEqual(extensionManifest.bundledDependencies, ["@firstpick/pi-prompts-git-pr"]);
24
+ assert.deepEqual(extensionManifest.pi?.prompts, ["./node_modules/@firstpick/pi-prompts-git-pr/prompts"]);
25
+
26
+ assert.match(app, /id: "gitWorkflow"[\s\S]*packageName: "@firstpick\/pi-extension-git-guided-workflow"[\s\S]*capabilityLabel: "\/git-guided-workflow"/u);
27
+ assert.match(app, /\["git-guided-workflow", "gitWorkflow"\][\s\S]*\["git-staged-msg", "gitWorkflow"\]/u);
28
+ assert.match(app, /optionalFeatureAvailability\.gitWorkflow = hasAvailableCommand\("git-guided-workflow"\) \|\| hasAvailableCommand\("git-staged-msg"\);/u);
29
+ assert.match(app, /case "git-workflow": return true;/u, "the browser-owned setup must not depend on a removed prompt command");
30
+ assert.match(app, /case "git-workflow": return openNativeGitWorkflowSetupDialog\(\);/u, "Setup must open the Guided Git workflow dialog");
31
+ });
@@ -1316,6 +1316,9 @@ try {
1316
1316
  const optionalFeatures = await request("127.0.0.1", "/api/optional-features");
1317
1317
  assert.equal(optionalFeatures.status, 200, "optional feature status should load");
1318
1318
  assert.equal(optionalFeatures.body?.data?.features?.length, 20, "the explicit server catalog should expose every allowlisted feature");
1319
+ const guidedGitFeature = optionalFeatures.body?.data?.features?.find((feature) => feature.featureId === "gitWorkflow");
1320
+ assert.equal(guidedGitFeature?.packageName, "@firstpick/pi-extension-git-guided-workflow", "Optional Features must install the extension that bundles the prompt companion");
1321
+ assert.equal(guidedGitFeature?.expectedSpec, "^0.1.0");
1319
1322
  const aurReviewFeature = optionalFeatures.body?.data?.features?.find((feature) => feature.featureId === "aurReview");
1320
1323
  assert.equal(aurReviewFeature?.expectedSpec, "^0.1.1", "status should expose the catalog-owned compatibility spec");
1321
1324
  assert.equal(aurReviewFeature?.installed, true, "workspace discovery should find the local pi-extension-aur-review sibling without an npm dependency");
@@ -186,7 +186,7 @@ const coordinatedTextPoint = functionBody("textPoint", renderer);
186
186
  const logMutation = functionBody("logMutation", renderer);
187
187
 
188
188
  // Coordinator import and initialization.
189
- assert.match(app, /import \{ createTranscriptRenderer \} from "\.\/transcript-renderer\.mjs";/, "app must import the transcript mutation coordinator module");
189
+ assert.match(app, /import \{ createTranscriptRenderer, groupConsecutiveThinkingItems, groupConsecutiveThinkingMessages \} from "\.\/transcript-renderer\.mjs";/, "app must import the transcript mutation coordinator and thinking-group helpers");
190
190
  assert.match(app, /const transcriptRenderer = createTranscriptRenderer\(\{[\s\S]*?chat: elements\.chat[\s\S]*?contextKey: \(\) => chatTextSelectionContextKey\(\)[\s\S]*?\}\);/, "the coordinator must be initialized once against #chat with the transcript context key");
191
191
  assert.doesNotMatch(renderer, /^\s*import\s/m, "the transcript renderer must stay dependency-free");
192
192
  assert.match(renderer, /export function createTranscriptRenderer\(/, "the coordinator must be the module's exported factory");
@@ -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=132/, "the stylesheet URL should advance for the bounded conversation tags");
99
- assert.match(html, /data-app-src="\/app\.js\?v=157"/, "the guarded app URL should advance for current browser wiring");
100
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v123"/, "the PWA cache identity should advance with browser assets");
98
+ assert.match(html, /\/styles\.css\?v=142/, "the stylesheet URL should advance for the bounded conversation tags");
99
+ assert.match(html, /data-app-src="\/app\.js\?v=172"/, "the guarded app URL should advance for current browser wiring");
100
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v139"/, "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");