@firstpick/pi-package-webui 0.7.6 → 0.7.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 (39) hide show
  1. package/README.md +37 -4
  2. package/bin/pi-webui-rpc-supervisor.mjs +518 -0
  3. package/bin/pi-webui.mjs +1003 -82
  4. package/lib/WEBUI_TUI_NATIVE_PARITY.json +13 -0
  5. package/lib/rpc-supervisor-client.mjs +301 -0
  6. package/lib/rpc-supervisor-protocol.mjs +236 -0
  7. package/lib/rpc-supervisor-state.mjs +165 -0
  8. package/lib/trust-boundaries.mjs +1 -0
  9. package/package.json +2 -2
  10. package/public/app.js +1237 -82
  11. package/public/index.html +334 -25
  12. package/public/service-worker.js +6 -1
  13. package/public/styles.css +366 -52
  14. package/public/subagent-gate-visibility.mjs +36 -0
  15. package/public/workflow-status-stack.mjs +69 -0
  16. package/tests/app-runner-process-tree-harness.test.mjs +37 -3
  17. package/tests/boot-failure-diagnostics.test.mjs +180 -0
  18. package/tests/durable-rpc-supervisor-harness.test.mjs +252 -0
  19. package/tests/fast-mode-client-static.test.mjs +2 -2
  20. package/tests/fixtures/compacting-pi.mjs +0 -0
  21. package/tests/fixtures/fake-pi.mjs +81 -2
  22. package/tests/git-panel-file-preview-static.test.mjs +221 -0
  23. package/tests/http-endpoints-harness.test.mjs +458 -33
  24. package/tests/mobile-static.test.mjs +74 -12
  25. package/tests/native-parity-harness.test.mjs +2 -1
  26. package/tests/native-parity.test.mjs +11 -0
  27. package/tests/numpad-decimal-input-static.test.mjs +128 -0
  28. package/tests/prompt-routing-input-clear-static.test.mjs +34 -0
  29. package/tests/prompt-routing-tab-status.test.mjs +103 -0
  30. package/tests/rpc-supervisor-host.test.mjs +275 -0
  31. package/tests/rpc-supervisor-protocol.test.mjs +67 -0
  32. package/tests/rpc-supervisor-state.test.mjs +62 -0
  33. package/tests/run-all.mjs +4 -1
  34. package/tests/streaming-ui-coupling.test.mjs +15 -0
  35. package/tests/subagent-gate-visibility.test.mjs +66 -0
  36. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  37. package/tests/subagents-helper.test.mjs +136 -0
  38. package/tests/workflow-status-stack.test.mjs +87 -0
  39. package/webui-rpc-helper.mjs +160 -2
@@ -20,7 +20,9 @@ import { randomUUID } from "node:crypto";
20
20
  import { appendFileSync } from "node:fs";
21
21
 
22
22
  const sessionIndex = process.argv.indexOf("--session");
23
- const sessionFile = sessionIndex !== -1 ? process.argv[sessionIndex + 1] : undefined;
23
+ const sessionFile = sessionIndex !== -1
24
+ ? process.argv[sessionIndex + 1]
25
+ : process.env.FAKE_PI_CONTINUITY_MODE === "1" ? process.env.FAKE_PI_CONTINUITY_SESSION_FILE || undefined : undefined;
24
26
 
25
27
  let activeBash = 0;
26
28
  let peakBash = 0;
@@ -38,7 +40,13 @@ let enabledToolNames = new Set(fakeTools.map((tool) => tool.name));
38
40
  let enabledSkillNames = new Set(fakeSkills.map((skill) => skill.name));
39
41
 
40
42
  const voiceScriptsEnabled = process.env.FAKE_PI_VOICE_SCRIPTS === "1";
43
+ // The continuity harness opts into this behavior explicitly so existing fixture
44
+ // consumers retain their current timing and log shapes.
45
+ const continuityModeEnabled = process.env.FAKE_PI_CONTINUITY_MODE === "1";
46
+ const largePayloadsEnabled = process.env.FAKE_PI_LARGE_PAYLOADS === "1";
41
47
  const commandLogFile = process.env.FAKE_PI_LOG_FILE || "";
48
+ const largeRpcText = "large-rpc-payload:" + "λ".repeat(70_000);
49
+ const largeTokenSamples = Array.from({ length: 300 }, (_, index) => ({ index, input: index + 1, output: index + 2 }));
42
50
  const staticEntries = [
43
51
  { type: "message", id: "u0000001", parentId: null, timestamp: new Date(1000).toISOString(), message: { role: "user", content: "fake prompt", timestamp: 1000 } },
44
52
  { type: "message", id: "a0000001", parentId: "u0000001", timestamp: new Date(2000).toISOString(), message: { role: "assistant", content: [{ type: "text", text: "fake answer" }], timestamp: 2000 } },
@@ -48,6 +56,8 @@ const dynamicEntries = [];
48
56
  const dynamicMessages = [];
49
57
  let dynamicLeafId = "u0000002";
50
58
  let scriptedStreaming = false;
59
+ let continuityRun = 0;
60
+ let largeTranscriptEnabled = false;
51
61
 
52
62
  function allSessionEntries() {
53
63
  return [...staticEntries, ...dynamicEntries];
@@ -93,8 +103,25 @@ logJsonLine({
93
103
  direction: "startup",
94
104
  recoveryUrl: String(process.env.PI_WEBUI_RECOVERY_URL || ""),
95
105
  recoveryTokenConfigured: Boolean(process.env.PI_WEBUI_RECOVERY_TOKEN),
106
+ ...(continuityModeEnabled ? { pid: process.pid, continuityMode: true } : {}),
96
107
  });
97
108
 
109
+ function continuityExitMarker(signal) {
110
+ if (continuityModeEnabled) logJsonLine({ direction: "exit", signal, pid: process.pid });
111
+ }
112
+
113
+ if (continuityModeEnabled) {
114
+ process.on("SIGTERM", () => {
115
+ continuityExitMarker("SIGTERM");
116
+ process.exit(143);
117
+ });
118
+ process.on("SIGINT", () => {
119
+ continuityExitMarker("SIGINT");
120
+ process.exit(130);
121
+ });
122
+ }
123
+
124
+
98
125
  function respond(payload) {
99
126
  process.stdout.write(`${JSON.stringify(payload)}\n`);
100
127
  }
@@ -160,6 +187,45 @@ function runVoiceScriptFlow({ text, chunks, chunkSpacingMs = 60, toolPhase = fal
160
187
  runScriptedSteps(steps);
161
188
  }
162
189
 
190
+ function runContinuityDelayedStream() {
191
+ scriptedStreaming = true;
192
+ const text = "continuity stream complete";
193
+ const run = ++continuityRun;
194
+ const tagged = (payload) => ({ ...payload, continuityRun: run });
195
+ const steps = [
196
+ { afterMs: 80, run: () => emitScriptedEvent(tagged({ type: "agent_start", continuityStep: "start" })) },
197
+ { afterMs: 80, run: () => emitScriptedEvent(tagged({ type: "message_start", continuityStep: "message-start", message: { role: "assistant" } })) },
198
+ { afterMs: 300, run: () => emitScriptedEvent(tagged({ type: "message_update", continuityStep: "delta-1", assistantMessageEvent: { type: "text_delta", delta: "continuity " } })) },
199
+ { afterMs: 300, run: () => emitScriptedEvent(tagged({ type: "message_update", continuityStep: "delta-2", assistantMessageEvent: { type: "text_delta", delta: "stream " } })) },
200
+ { afterMs: 300, run: () => emitScriptedEvent(tagged({ type: "message_update", continuityStep: "delta-3", assistantMessageEvent: { type: "text_delta", delta: "complete" } })) },
201
+ { afterMs: 100, run: () => {
202
+ const message = { role: "assistant", content: [{ type: "text", text }], timestamp: Date.now() };
203
+ appendDynamicMessage(message);
204
+ emitScriptedEvent(tagged({ type: "message_end", continuityStep: "message-end", message }));
205
+ } },
206
+ { afterMs: 80, run: () => {
207
+ scriptedStreaming = false;
208
+ emitScriptedEvent(tagged({ type: "agent_end", continuityStep: "end" }));
209
+ } },
210
+ ];
211
+ runScriptedSteps(steps);
212
+ }
213
+
214
+ function handleContinuityPrompt(command, base) {
215
+ if (!continuityModeEnabled || String(command.message || "").trim() !== "fixture continuity delayed stream") return false;
216
+ appendDynamicMessage({ role: "user", content: String(command.message), timestamp: Date.now() });
217
+ respond({ ...base, data: { output: "fake continuity stream accepted", pid: process.pid } });
218
+ runContinuityDelayedStream();
219
+ return true;
220
+ }
221
+
222
+ function handleLargePayloadPrompt(command, base) {
223
+ if (!largePayloadsEnabled || String(command.message || "").trim() !== "fixture large rpc payload") return false;
224
+ largeTranscriptEnabled = true;
225
+ respond({ ...base, data: { output: largeRpcText, tokens: { input: 123456, output: 654321 }, samples: largeTokenSamples } });
226
+ return true;
227
+ }
228
+
163
229
  function handleVoiceScriptPrompt(command, base) {
164
230
  if (!voiceScriptsEnabled) return false;
165
231
  const message = String(command.message || "");
@@ -499,6 +565,7 @@ rl.on("line", (line) => {
499
565
  ...(Array.isArray(command.images) ? { images: command.images } : {}),
500
566
  ...(command.provider !== undefined ? { provider: String(command.provider) } : {}),
501
567
  ...(command.modelId !== undefined ? { modelId: String(command.modelId) } : {}),
568
+ ...(type === "extension_ui_response" ? { id: String(command.id), value: command.value, cancelled: command.cancelled === true } : {}),
502
569
  });
503
570
  const base = { type: "response", id, command: type, success: true };
504
571
 
@@ -531,6 +598,7 @@ rl.on("line", (line) => {
531
598
  { role: "assistant", content: [{ type: "text", text: "fake answer" }], timestamp: 2000 },
532
599
  { role: "user", content: "fake follow-up", timestamp: 3000 },
533
600
  ...dynamicMessages,
601
+ ...(largeTranscriptEnabled ? [{ role: "assistant", content: [{ type: "text", text: largeRpcText }], timestamp: 4000 }] : []),
534
602
  ],
535
603
  },
536
604
  });
@@ -573,6 +641,8 @@ rl.on("line", (line) => {
573
641
  if (handleDocumentArtifactFixturePrompt(command, base)) return;
574
642
  if (handleWorkflowFixturePrompt(command, base)) return;
575
643
  if (handleTalkPrompt(command, base)) return;
644
+ if (handleContinuityPrompt(command, base)) return;
645
+ if (handleLargePayloadPrompt(command, base)) return;
576
646
  if (handleVoiceScriptPrompt(command, base)) return;
577
647
  respond({ ...base, data: { output: "fake prompt accepted" } });
578
648
  return;
@@ -591,11 +661,20 @@ rl.on("line", (line) => {
591
661
  respond({ ...base, data: { models: [{ provider: "fake", id: "fake-model", name: "Fake Model" }] } });
592
662
  return;
593
663
  case "get_session_stats":
594
- respond({ ...base, data: { tokens: 0 } });
664
+ respond({
665
+ ...base,
666
+ data: largePayloadsEnabled
667
+ ? { tokens: { input: 123456, output: 654321, total: 777777 }, samples: largeTokenSamples }
668
+ : { tokens: 0 },
669
+ });
595
670
  return;
596
671
  case "get_last_assistant_text":
597
672
  respond({ ...base, data: { text: "fake last text" } });
598
673
  return;
674
+ case "extension_ui_response":
675
+ // Pi's extension UI response is a one-way RPC write. Deliberately emit
676
+ // no response so supervised HTTP coverage catches accidental waits.
677
+ return;
599
678
  case "bash": {
600
679
  activeBash += 1;
601
680
  peakBash = Math.max(peakBash, activeBash);
@@ -0,0 +1,221 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import vm from "node:vm";
6
+
7
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
8
+ const [app, css, html] = await Promise.all([
9
+ readFile(join(root, "public", "app.js"), "utf8"),
10
+ readFile(join(root, "public", "styles.css"), "utf8"),
11
+ readFile(join(root, "public", "index.html"), "utf8"),
12
+ ]);
13
+
14
+ function sourceBetween(startMarker, endMarker, label) {
15
+ const start = app.indexOf(startMarker);
16
+ const end = app.indexOf(endMarker, start);
17
+ assert.ok(start >= 0 && end > start, `${label} should remain a standalone frontend helper`);
18
+ return app.slice(start, end);
19
+ }
20
+
21
+ const normalizePathSource = sourceBetween("function normalizeFileTreePath(", "\nfunction fileApiPath(", "normalizeFileTreePath");
22
+ const targetSource = sourceBetween("function gitFileViewerTarget(", "\nasync function openGitFileInViewer(", "gitFileViewerTarget");
23
+ const openSource = sourceBetween("async function openGitFileInViewer(", "\nasync function openGitFileFromChanges(", "openGitFileInViewer");
24
+ const renderSource = sourceBetween("function renderGitPanelFile(", "\nfunction renderGitPanelTreeSection(", "renderGitPanelFile");
25
+ const categorySource = sourceBetween("const GIT_FILE_DIFF_CATEGORY_BY_PANEL = Object.freeze({", "\nasync function loadGitFileChangesSnapshot(", "gitFileDiffCategory");
26
+ const modeSource = sourceBetween("function resolveFileViewerMode(", "\nfunction setFileViewerMode(", "resolveFileViewerMode");
27
+ const setModeSource = sourceBetween("function setFileViewerMode(", "\nfunction setFileViewerDirty(", "setFileViewerMode");
28
+ const viewerUiSource = sourceBetween("function updateFileViewerUi(", "\nfunction fileViewerChangesNotice(", "updateFileViewerUi");
29
+ const changesRenderSource = sourceBetween("function fileViewerChangesNotice(", "\nfunction clearFileViewerSelection(", "file viewer changes rendering");
30
+ const combinedSyntaxSource = sourceBetween("function gitFileDiffUsesCombinedSyntax(", "\nfunction renderFileViewerUntrackedChanges(", "gitFileDiffUsesCombinedSyntax");
31
+ const snapshotSource = sourceBetween("async function loadGitFileChangesSnapshot(", "\nfunction gitFileChangesPlaceholder(", "loadGitFileChangesSnapshot");
32
+ const applySnapshotSource = sourceBetween("function gitFileChangesPlaceholder(", "\nasync function openFileInViewer(", "gitFileChangesPlaceholder");
33
+ const openFileSource = sourceBetween("async function openFileInViewer(", "\nasync function openAurReviewReportInViewer(", "openFileInViewer");
34
+ const closeSource = sourceBetween("function closeFileViewer(", "\n// Side-panel Git categories are UI labels", "closeFileViewer");
35
+ const moveSource = sourceBetween("function updateActiveFileViewerAfterMove(", "\nfunction closeActiveFileViewerIfDeleted(", "updateActiveFileViewerAfterMove");
36
+
37
+ const targets = JSON.parse(vm.runInNewContext(`${normalizePathSource}\n${targetSource}\nJSON.stringify([
38
+ gitFileViewerTarget("sub/active.js", "/repo", [{ tabId: "repo-tab", cwd: "/repo" }]),
39
+ gitFileViewerTarget("other/fallback.js", "/repo", [{ tabId: "repo-tab", cwd: "/repo" }]),
40
+ gitFileViewerTarget("src/windows.js", "C:\\\\Repo", [{ tabId: "windows-tab", cwd: "c:\\\\repo" }]),
41
+ gitFileViewerTarget("root.js", "/", [{ tabId: "root-tab", cwd: "/" }]),
42
+ gitFileViewerTarget("outside.js", "/repo", [{ tabId: "nested-tab", cwd: "/repo/sub" }]),
43
+ ])`, {
44
+ activeTab: () => ({ id: "active-tab", cwd: "/repo/sub" }),
45
+ }));
46
+
47
+ assert.deepEqual(targets[0], { tabId: "active-tab", path: "active.js" }, "Git files inside the active cwd should stay on the active tab");
48
+ assert.deepEqual(targets[1], { tabId: "repo-tab", path: "other/fallback.js" }, "Git files outside the active cwd should use a repository tab that contains them");
49
+ assert.deepEqual(targets[2], { tabId: "windows-tab", path: "src/windows.js" }, "Git preview path translation should normalize Windows separators and compare drive paths case-insensitively");
50
+ assert.deepEqual(targets[3], { tabId: "root-tab", path: "root.js" }, "filesystem-root workspaces should retain a usable relative viewer path");
51
+ assert.equal(targets[4], null, "Git files outside every available tab cwd should fail closed");
52
+
53
+ assert.match(openSource, /gitFileViewerTarget\(repoRelPath, root, candidates\)/, "Git file opening should use the shared repo-to-workspace path resolver");
54
+ assert.match(openSource, /target\.tabId !== activeTabId[\s\S]*await switchTab\(target\.tabId\)[\s\S]*openFileInViewer\(target\.path/, "Git file opening should activate the owning tab before using the standard WebUI viewer");
55
+ assert.match(openSource, /its terminal tab is no longer available/, "a stale Git-card tab should produce visible failure feedback");
56
+ assert.match(renderSource, /row\.setAttribute\("role", "button"\)/, "Git file rows should expose button semantics");
57
+ assert.match(renderSource, /row\.addEventListener\("click", open\)/, "clicking a Git file row should open its preview");
58
+ assert.match(renderSource, /event\.repeat \|\| \(event\.key !== "Enter" && event\.key !== " "\)/, "Git file rows should support keyboard activation without key-repeat request bursts");
59
+ assert.match(renderSource, /openGitFileInViewer\(entry\.path, \{ root: card\.root, candidates: card\.candidates, category \}\)/, "Git file rows should pass repository and category context to the shared preview flow");
60
+ assert.match(css, /\.git-side-panel-file \{[^}]*cursor: pointer;[^}]*\}/, "Git file rows should visually indicate their primary open action");
61
+
62
+ // --- Changes mode DOM wiring ---
63
+
64
+ assert.match(
65
+ html,
66
+ /<div class="file-viewer-mode-toggle" role="group" aria-label="File view mode">\s*<button id="fileViewerChangesModeButton" type="button" aria-pressed="false" hidden>Changes<\/button>\s*<button id="fileViewerSourceModeButton"/,
67
+ "the file viewer mode toggle should expose a Changes control that is hidden until a Git-originated open supplies one",
68
+ );
69
+ assert.match(
70
+ html,
71
+ /<div class="file-viewer-content">[\s\S]*<div id="fileViewerChanges" class="file-viewer-changes"[^>]*hidden><\/div>\s*<\/div>/,
72
+ "the file viewer content area should own a dedicated, initially hidden Git changes surface",
73
+ );
74
+ assert.match(html, /id="fileViewerChanges"[^>]*aria-label="Git changes for this file"/, "the changes surface should be labelled for assistive technology");
75
+ assert.match(html, /id="fileViewerHelp"[^>]*>Files opened from Git start in Changes mode\./, "the viewer help should explain the Git-specific default mode");
76
+ assert.match(app, /fileViewerChangesModeButton: \$\("#fileViewerChangesModeButton"\)/, "the Changes mode button should be registered in the element map");
77
+ assert.match(app, /fileViewerChanges: \$\("#fileViewerChanges"\)/, "the changes surface should be registered in the element map");
78
+ assert.match(
79
+ app,
80
+ /elements\.fileViewerChangesModeButton\?\.addEventListener\("click", \(\) => setFileViewerMode\("changes"\)\);\nelements\.fileViewerSourceModeButton\?\.addEventListener\("click", \(\) => setFileViewerMode\("source"\)\);\nelements\.fileViewerPreviewModeButton\?\.addEventListener\("click", \(\) => setFileViewerMode\("preview"\)\);/,
81
+ "Changes mode should be selectable alongside the untouched Source and Preview controls",
82
+ );
83
+
84
+ // --- Mode resolution: default selection, availability, and isolation ---
85
+
86
+ const modes = JSON.parse(vm.runInNewContext(`${modeSource}\nJSON.stringify([
87
+ resolveFileViewerMode({ mode: "changes", gitChanges: { category: "unstaged" }, language: "text" }),
88
+ resolveFileViewerMode({ mode: "changes", gitChanges: null, language: "text" }),
89
+ resolveFileViewerMode({ mode: "source", gitChanges: { category: "unstaged" }, language: "text" }),
90
+ resolveFileViewerMode({ mode: "preview", gitChanges: { category: "unstaged" }, language: "markdown" }),
91
+ resolveFileViewerMode({ mode: "preview", language: "markdown" }),
92
+ resolveFileViewerMode({ mode: "preview", language: "text" }),
93
+ resolveFileViewerMode({ mode: "source", language: "markdown" }),
94
+ resolveFileViewerMode({ mode: "source", sourceAvailable: false, gitChanges: { category: "staged" }, language: "text" }),
95
+ resolveFileViewerMode({ mode: "source", sourceAvailable: false, language: "text" }),
96
+ resolveFileViewerMode(null),
97
+ ])`, {}));
98
+
99
+ assert.equal(modes[0], "changes", "a Git-originated viewer should stay in Changes mode when requested");
100
+ assert.equal(modes[1], "source", "Changes mode should fall back to Source when the viewer has no Git snapshot");
101
+ assert.equal(modes[2], "source", "a Git-originated viewer should still allow the live Source view");
102
+ assert.equal(modes[3], "preview", "Markdown Preview should remain reachable for Git-originated Markdown files");
103
+ assert.equal(modes[4], "preview", "normal Markdown opens should keep their Preview default");
104
+ assert.equal(modes[5], "source", "Preview should degrade to Source for non-Markdown files");
105
+ assert.equal(modes[6], "source", "Source stays Source for Markdown when explicitly selected");
106
+ assert.equal(modes[7], "changes", "a deleted tracked file without live source should resolve to Changes");
107
+ assert.equal(modes[8], "source", "a missing source without any Git snapshot should not invent a Changes view");
108
+ assert.equal(modes[9], "source", "mode resolution should fail closed without a viewer");
109
+
110
+ assert.match(setModeSource, /activeFileViewer\.mode = resolveFileViewerMode\(\{ \.\.\.activeFileViewer, mode \}\);/, "mode switching should route every request through the shared resolver");
111
+ assert.match(setModeSource, /if \(activeFileViewer\.mode === "changes" && previousMode !== "changes"\) clearFileViewerSelection\(\);/, "entering Changes mode should clear a stale Source or Preview selection bar");
112
+ assert.match(viewerUiSource, /const hasChanges = !!viewer\.gitChanges;/, "the viewer UI should derive Changes availability from the open-time snapshot");
113
+ assert.match(viewerUiSource, /elements\.fileViewerChangesModeButton\.hidden = !hasChanges;\s*elements\.fileViewerChangesModeButton\.disabled = !hasChanges;/, "the Changes control should stay hidden and disabled for non-Git opens");
114
+ assert.match(viewerUiSource, /elements\.fileViewerSourceModeButton\.disabled = !sourceAvailable;/, "Source should be disabled when the live file content is unavailable");
115
+ assert.match(viewerUiSource, /elements\.fileViewerPreviewModeButton\.hidden = !isMarkdown;\s*elements\.fileViewerPreviewModeButton\.disabled = !isMarkdown \|\| !sourceAvailable;/, "Markdown Preview should stay hidden for non-Markdown and disabled when live source is unavailable");
116
+ assert.match(viewerUiSource, /elements\.fileViewerEditor\.hidden = mode !== "source";/, "Source editing should remain bound to Source mode");
117
+ assert.match(
118
+ viewerUiSource,
119
+ /elements\.fileViewerChanges\.hidden = mode !== "changes";\s*if \(mode === "changes"\) renderFileViewerChanges\(viewer\.gitChanges\);\s*else elements\.fileViewerChanges\.replaceChildren\(\);/,
120
+ "the changes surface should render only in Changes mode and clear itself otherwise",
121
+ );
122
+ assert.match(viewerUiSource, /elements\.fileViewerSaveButton\.disabled = viewer\.readOnly === true \|\| !viewer\.dirty;/, "save semantics should stay tied to read-only and dirty state");
123
+ assert.match(viewerUiSource, /\["source unavailable"\]/, "a viewer without live content should say so in its metadata line");
124
+
125
+ // --- Category mapping ---
126
+
127
+ const categories = JSON.parse(vm.runInNewContext(`${categorySource}\nJSON.stringify([
128
+ gitFileDiffCategory("staged"),
129
+ gitFileDiffCategory("changes"),
130
+ gitFileDiffCategory("conflicted"),
131
+ gitFileDiffCategory("untracked"),
132
+ gitFileDiffCategory("history"),
133
+ gitFileDiffCategory(""),
134
+ gitFileDiffCategory(),
135
+ ])`, {}));
136
+
137
+ assert.deepEqual(
138
+ categories,
139
+ ["staged", "unstaged", "conflicted", "untracked", "", "", ""],
140
+ "side-panel categories should map onto the allowlisted API categories and fail closed for anything else",
141
+ );
142
+
143
+ // --- Backend request contract ---
144
+
145
+ assert.match(snapshotSource, /new URLSearchParams\(\{ path: repoRelPath, category \}\)/, "the changes request should send the repo-relative path and the mapped category");
146
+ assert.match(snapshotSource, /api\(`\/api\/git-file-diff\?\$\{params\.toString\(\)\}`, \{ tabId \}\)/, "the changes request should call the read-only Git file diff endpoint on the owning tab");
147
+ assert.match(snapshotSource, /if \(!response\.ok\) throw new Error\(response\.error \|\| "Failed to load Git changes for this file"\)/, "an ok:false response should surface a readable error");
148
+ assert.match(snapshotSource, /truncated: data\.truncated === true/, "truncation should be carried into the viewer snapshot");
149
+ assert.match(snapshotSource, /contentError: data\.error \? String\(data\.error\) : ""/, "an untracked read error should stay distinct from a request failure");
150
+ assert.match(snapshotSource, /return \{ \.\.\.snapshot, error: error\.message \|\| String\(error\) \};/, "a failed changes request should resolve to an error snapshot instead of rejecting the open");
151
+ assert.match(app, /let fileViewerGitChangesRequestSerial = 0;/, "Git changes opens should have a request identity counter");
152
+ assert.match(applySnapshotSource, /loading: true, requestSerial/, "the viewer should show an identified loading snapshot until the bounded diff arrives");
153
+ assert.match(
154
+ applySnapshotSource,
155
+ /if \(!isCurrentTabContext\(tabContext\)\) return;\s*if \(!activeFileViewer\?\.gitChanges\?\.loading \|\| activeFileViewer\.path !== viewerPath \|\| activeFileViewer\.gitChanges\.requestSerial !== requestSerial\) return;/,
156
+ "a late diff response should be discarded when the tab, viewer, or same-path request identity changed",
157
+ );
158
+
159
+ // --- Open flow: Git default, normal-open isolation, deleted files ---
160
+
161
+ assert.match(openSource, /category = "" \} = \{\}/, "Git opens should accept an optional side-panel category");
162
+ assert.match(openSource, /openFileInViewer\(target\.path, \{ gitCategory: category, gitPath: normalizeFileTreePath\(repoRelPath\) \}\)/, "Git opens should hand the category and repo path to the standard viewer");
163
+ assert.match(openFileSource, /async function openFileInViewer\(path = "", \{ gitCategory = "", gitPath = "" \} = \{\}\)/, "the standard viewer should accept optional Git context without changing its default signature");
164
+ assert.match(app, /let fileViewerOpenRequestSerial = 0;/, "file viewer opens should have a shared request identity counter");
165
+ assert.match(openFileSource, /const openRequestSerial = \+\+fileViewerOpenRequestSerial;/, "every viewer open should capture a unique request identity");
166
+ assert.match(openFileSource, /const category = gitFileDiffCategory\(gitCategory\);/, "the viewer should map the side-panel category through the shared allowlist");
167
+ assert.match(openFileSource, /const changesRequestSerial = category \? \+\+fileViewerGitChangesRequestSerial : 0;/, "each Git-originated open should receive a unique changes request identity");
168
+ assert.match(openFileSource, /const changesRequest = category \? loadGitFileChangesSnapshot\(changesPath, category, tabContext\.tabId\) : null;/, "only category-carrying opens should request a diff");
169
+ assert.match(openFileSource, /const gitChanges = changesRequest \? gitFileChangesPlaceholder\(category, changesPath, changesRequestSerial\) : null;/, "normal File-section opens should carry no Git snapshot at all");
170
+ assert.match(openFileSource, /applyGitFileChangesSnapshot\(changesRequest, tabContext, activeFileViewer\.path, changesRequestSerial\)/, "same-path Git requests should apply only through their captured request identity");
171
+ assert.match(openFileSource, /mode: gitChanges \? "changes" : data\.language === "markdown" \? "preview" : "source",/, "Git opens should default to Changes while normal opens keep the Markdown/Source default");
172
+ assert.match(openFileSource, /if \(!isCurrentTabContext\(tabContext\) \|\| openRequestSerial !== fileViewerOpenRequestSerial\) return;/, "the source-success path should reject stale same-tab viewer opens");
173
+ assert.match(openFileSource, /const gitChanges = changesRequest \? await changesRequest : null;\s*if \(!isCurrentTabContext\(tabContext\) \|\| openRequestSerial !== fileViewerOpenRequestSerial\) return;/, "the deleted-file fallback should reject stale same-tab viewer opens after awaiting the diff");
174
+ assert.match(openFileSource, /readOnly: false,\s*sourceAvailable: true,/, "a live Git-originated file should stay editable");
175
+ assert.match(
176
+ openFileSource,
177
+ /const gitChanges = changesRequest \? await changesRequest : null;\s*if \(!isCurrentTabContext\(tabContext\) \|\| openRequestSerial !== fileViewerOpenRequestSerial\) return;\s*if \(gitChanges && !gitChanges\.error\) \{/,
178
+ "a current failed source load should fall back to the diff only when that diff actually loaded",
179
+ );
180
+ assert.match(openFileSource, /mode: "changes",\s*dirty: false,\s*readOnly: true,\s*sourceAvailable: false,/, "a deleted tracked file should open read-only in Changes mode");
181
+ assert.match(openFileSource, /setFileViewerStatus\("File content unavailable; showing Git changes \(read-only\)\.", "warn"\)/, "the deleted-file fallback should explain itself in the viewer status");
182
+ assert.match(openFileSource, /setFileViewerStatus\(message, "error"\);\s*addEvent\(`file open failed: \$\{message\}`, "error"\);/, "a total failure should still report the original open error");
183
+ assert.match(closeSource, /fileViewerOpenRequestSerial \+= 1;\s*activeFileViewer = null;/, "closing the viewer should invalidate pending source and deleted-file opens");
184
+ assert.match(closeSource, /elements\.fileViewerChanges\.hidden = true;\s*elements\.fileViewerChanges\.replaceChildren\(\);/, "closing the viewer should clear the changes surface");
185
+ assert.match(moveSource, /gitChanges: null,/, "renaming the open file should drop its stale open-time diff snapshot");
186
+
187
+ // --- Changes rendering contracts ---
188
+
189
+ const combined = JSON.parse(vm.runInNewContext(`${combinedSyntaxSource}\nJSON.stringify([
190
+ gitFileDiffUsesCombinedSyntax("@@@ -1,4 -1,4 +1,6 @@@\\n context"),
191
+ gitFileDiffUsesCombinedSyntax("diff --git a/x b/x\\n@@ -1,2 +1,3 @@\\n context"),
192
+ gitFileDiffUsesCombinedSyntax(""),
193
+ ])`, {}));
194
+
195
+ assert.deepEqual(combined, [true, false, false], "combined conflict hunks should be detected while ordinary unified hunks stay on the split renderer");
196
+
197
+ assert.match(changesRenderSource, /make\("section", `git-diff-section file-viewer-changes-section \$\{snapshot\.category \|\| ""\}`\.trim\(\)\)/, "the changes surface should reuse the shared Git diff section shell");
198
+ assert.match(changesRenderSource, /if \(snapshot\.loading\) wrapper\.append\(fileViewerChangesNotice\("Loading Git changes…"\)\);/, "a pending diff should render an explicit loading state");
199
+ assert.match(changesRenderSource, /else if \(snapshot\.error\) wrapper\.append\(fileViewerChangesNotice\(snapshot\.error, "error"\)\);/, "a failed diff should render an in-viewer error state");
200
+ assert.match(
201
+ changesRenderSource,
202
+ /wrapper\.append\(snapshot\.category === "untracked" \? renderFileViewerUntrackedChanges\(snapshot\) : renderFileViewerTrackedChanges\(snapshot\)\);/,
203
+ "untracked files should use whole-file rendering while tracked categories use the diff renderer",
204
+ );
205
+ assert.match(changesRenderSource, /if \(snapshot\.truncated\) wrapper\.append\(renderFileViewerChangesTruncation\(snapshot\)\);/, "a truncated snapshot should be flagged in the viewer");
206
+ assert.match(changesRenderSource, /make\("div", "git-diff-truncated-notice"\)[\s\S]*formatBytes\(snapshot\.capBytes \|\| 0\)[\s\S]*make\("code", "git-tools-command", snapshot\.command \|\| "git diff"\)/, "the truncation notice should name the cap and the exact command");
207
+ assert.match(changesRenderSource, /if \(!diff\.trim\(\)\) return fileViewerChangesNotice\(`No \$\{String\(snapshot\.label \|\| "Git"\)\.toLowerCase\(\)\} changes for this file\.`\)/, "an empty diff should render an explicit empty state");
208
+ assert.match(changesRenderSource, /if \(gitFileDiffUsesCombinedSyntax\(diff\)\) return make\("pre", "git-diff-raw", diff\);/, "combined conflict syntax should fall back to readable raw diff text");
209
+ assert.match(changesRenderSource, /const files = parseGitUnifiedDiff\(diff\);[\s\S]*for \(const file of files\) fragment\.append\(renderGitDiffFile\(file\)\);/, "parsed diffs should render through the existing split Git grid");
210
+ assert.match(changesRenderSource, /if \(!files\.length\) return make\("pre", "git-diff-raw", diff\);/, "an unparsable diff should still show its raw text");
211
+ assert.match(changesRenderSource, /if \(entry\.error \|\| entry\.binary\) return renderGitUntrackedRawFile\(entry\);/, "binary or unreadable untracked files should show the shared notice instead of fake diff lines");
212
+ assert.match(changesRenderSource, /return renderGitDiffFile\(gitUntrackedEntryToDiffFile\(entry\)\);/, "verified untracked text should render as all-added lines");
213
+ assert.match(changesRenderSource, /if \(entry\.contentMissing\) return fileViewerChangesNotice\("Untracked file content is unavailable\.", "error"\);/, "an untracked response without content should not pretend the file is empty");
214
+ assert.doesNotMatch(changesRenderSource, /runGitFileAction|gitChangesFileActionsFor|gitFileActionButtons/, "the read-only changes surface must not expose staging or discard actions");
215
+
216
+ assert.match(css, /\.file-viewer-editor,\n\.file-viewer-preview,\n\.file-viewer-changes \{/, "the changes surface should share the file viewer content frame");
217
+ assert.match(css, /\.file-viewer-changes \{\n\s*padding: 0\.72rem;\n\}/, "the changes surface should have its own padding inside the shared frame");
218
+ assert.match(css, /\.file-viewer-changes \.git-diff-grid \{[\s\S]*grid-template-columns:[\s\S]*min-width: 30rem;[\s\S]*\}/, "the split diff grid should be narrowed for the file viewer pane");
219
+ assert.match(css, /\.file-viewer-changes-notice \{[\s\S]*font-size: var\(--text-xs\);[\s\S]*\}\n\.file-viewer-changes-notice\.error \{ color: var\(--ctp-red\); \}/, "changes notices should be readable and mark errors distinctly");
220
+
221
+ console.log("git panel file preview static tests passed");