@firstpick/pi-package-webui 0.7.8 → 0.7.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@
3
3
  // timers, and delivery callbacks all arrive through options so Node tests can
4
4
  // drive the full listen -> prompt -> speak -> listen loop without a browser.
5
5
  //
6
- // Turn-taking contract (see docs/webui/natural-conversation/NATURAL_CONVERSATION_MODE_PLAN.md):
6
+ // Turn-taking contract (see docs/planned/webui/natural-conversation/NATURAL_CONVERSATION_MODE_PLAN.md):
7
7
  // - Final transcripts while Pi is idle are sent as normal prompts.
8
8
  // - Transcripts while the assistant streams final text are interruptions.
9
9
  // - Transcripts during a tool call/execution are queued until the tool phase
@@ -0,0 +1,166 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import vm from "node:vm";
6
+
7
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
8
+ const server = await readFile(join(root, "bin", "pi-webui.mjs"), "utf8");
9
+
10
+ function sourceForFunction(name) {
11
+ const start = server.indexOf(`function ${name}(`);
12
+ assert.notEqual(start, -1, `${name} should remain a server helper`);
13
+ const openingBrace = server.indexOf(") {", start) + 2;
14
+ assert.ok(openingBrace > start, `${name} should have a function body`);
15
+ let depth = 0;
16
+ let quote = "";
17
+ for (let index = openingBrace; index < server.length; index += 1) {
18
+ const character = server[index];
19
+ if (quote) {
20
+ if (character === "\\") {
21
+ index += 1;
22
+ } else if (character === quote) {
23
+ quote = "";
24
+ }
25
+ continue;
26
+ }
27
+ if (character === '"' || character === "'" || character === "`") {
28
+ quote = character;
29
+ continue;
30
+ }
31
+ if (character === "{") depth += 1;
32
+ if (character === "}" && --depth === 0) return server.slice(start, index + 1);
33
+ }
34
+ assert.fail(`${name} should have a balanced function body`);
35
+ }
36
+
37
+ function plain(value) {
38
+ return JSON.parse(JSON.stringify(value));
39
+ }
40
+
41
+ const events = [];
42
+ const context = {
43
+ broadcastTabEvent(tab, event) {
44
+ events.push({ tab, event });
45
+ },
46
+ tabActivitySnapshot(tab) {
47
+ return { tabId: tab.id };
48
+ },
49
+ };
50
+ vm.createContext(context);
51
+ const functions = [
52
+ "compactionQueueForTab",
53
+ "compactionQueueRevision",
54
+ "advanceCompactionQueueRevision",
55
+ "compactionQueueSnapshot",
56
+ "compactionQueueEvent",
57
+ "sameQueueSnapshot",
58
+ "compactionFollowUpSlots",
59
+ "mutateCompactionFollowUpQueue",
60
+ ].map(sourceForFunction).join("\n\n");
61
+ vm.runInContext(`${functions}\nglobalThis.mutate = mutateCompactionFollowUpQueue;`, context);
62
+
63
+ const firstImage = { type: "image", mimeType: "image/png", data: "first-image" };
64
+ const secondImage = { type: "image", mimeType: "image/png", data: "second-image" };
65
+ const editedCommand = {
66
+ type: "follow_up",
67
+ mode: "followUp",
68
+ message: "first follow-up",
69
+ images: [firstImage],
70
+ metadata: { origin: "fixture", sequence: 1 },
71
+ };
72
+ const movedCommand = {
73
+ type: "prompt",
74
+ mode: "followUp",
75
+ message: "second follow-up",
76
+ images: [secondImage],
77
+ metadata: { origin: "fixture", sequence: 2 },
78
+ };
79
+ const tab = {
80
+ id: "compaction-contract-tab",
81
+ title: "Compaction contract",
82
+ compactionQueue: [
83
+ { id: "steer", command: { type: "steer", mode: "steer", message: "fixed steering", metadata: { origin: "fixture" } } },
84
+ { id: "edit", command: editedCommand },
85
+ { id: "move", command: movedCommand },
86
+ ],
87
+ };
88
+
89
+ const edit = context.mutate(tab, {
90
+ source: "webui-compaction",
91
+ kind: "followUp",
92
+ revision: 0,
93
+ expected: { steering: ["fixed steering"], followUp: ["first follow-up", "second follow-up"] },
94
+ operation: { type: "edit", index: 0, expectedText: "first follow-up", text: "edited follow-up" },
95
+ });
96
+ assert.deepEqual(plain(edit), {
97
+ mutated: true,
98
+ source: "webui-compaction",
99
+ queue: {
100
+ source: "webui-compaction",
101
+ revision: 1,
102
+ steering: ["fixed steering"],
103
+ followUp: ["edited follow-up", "second follow-up"],
104
+ draining: false,
105
+ },
106
+ }, "a successful edit returns the authoritative advanced snapshot");
107
+ assert.strictEqual(tab.compactionQueue[1].command, editedCommand, "edit must retain the original queued command object");
108
+ assert.strictEqual(editedCommand.images[0], firstImage, "edit must retain the original image object");
109
+ assert.deepEqual(editedCommand.metadata, { origin: "fixture", sequence: 1 }, "edit must retain command metadata");
110
+ assert.equal(editedCommand.type, "follow_up", "edit must retain the command type");
111
+ assert.equal(editedCommand.mode, "followUp", "edit must retain the command mode");
112
+ assert.equal(events.length, 1, "a successful compaction edit emits exactly one queue update");
113
+ assert.deepEqual(plain(events[0].event), {
114
+ type: "webui_compaction_queue_update",
115
+ tabId: "compaction-contract-tab",
116
+ tabTitle: "Compaction contract",
117
+ queueLength: 3,
118
+ pendingMessageCount: 3,
119
+ source: "webui-compaction",
120
+ revision: 1,
121
+ steering: ["fixed steering"],
122
+ followUp: ["edited follow-up", "second follow-up"],
123
+ draining: false,
124
+ tabActivity: { tabId: "compaction-contract-tab" },
125
+ }, "the successful edit emits its one authoritative snapshot");
126
+
127
+ const stale = context.mutate(tab, {
128
+ source: "webui-compaction",
129
+ kind: "followUp",
130
+ revision: 0,
131
+ expected: { steering: ["fixed steering"], followUp: ["first follow-up", "second follow-up"] },
132
+ operation: { type: "move", from: 1, to: 0, expectedText: "second follow-up" },
133
+ });
134
+ assert.equal(stale.mutated, false, "a stale compaction request is rejected");
135
+ assert.equal(stale.reason, "queue-changed");
136
+ assert.equal(events.length, 1, "a rejected stale mutation emits no queue update");
137
+ assert.strictEqual(tab.compactionQueue[1].command, editedCommand, "a rejected stale mutation leaves command identity intact");
138
+
139
+ const move = context.mutate(tab, {
140
+ source: "webui-compaction",
141
+ kind: "followUp",
142
+ revision: 1,
143
+ expected: { steering: ["fixed steering"], followUp: ["edited follow-up", "second follow-up"] },
144
+ operation: { type: "move", from: 1, to: 0, expectedText: "second follow-up" },
145
+ });
146
+ assert.equal(move.mutated, true, "a current move is accepted");
147
+ assert.deepEqual([...move.queue.followUp], ["second follow-up", "edited follow-up"], "move uses the final follow-up index while steering remains fixed");
148
+ assert.strictEqual(tab.compactionQueue[1].command, movedCommand, "move keeps the full command object paired with its queue slot");
149
+ assert.strictEqual(movedCommand.images[0], secondImage, "move retains the moved command image object");
150
+ assert.deepEqual(movedCommand.metadata, { origin: "fixture", sequence: 2 }, "move retains moved command metadata");
151
+ assert.equal(events.length, 2, "a successful compaction move emits exactly one additional queue update");
152
+
153
+ tab.compactionQueueDraining = true;
154
+ const draining = context.mutate(tab, {
155
+ source: "webui-compaction",
156
+ kind: "followUp",
157
+ revision: 2,
158
+ expected: { steering: ["fixed steering"], followUp: ["second follow-up", "edited follow-up"] },
159
+ operation: { type: "edit", index: 0, expectedText: "second follow-up", text: "must not apply" },
160
+ });
161
+ assert.equal(draining.mutated, false, "a draining compaction queue rejects mutation");
162
+ assert.equal(draining.reason, "queue-draining");
163
+ assert.equal(events.length, 2, "a rejected draining mutation emits no queue update");
164
+ assert.strictEqual(tab.compactionQueue[1].command, movedCommand, "a rejected draining mutation leaves the moved command untouched");
165
+
166
+ console.log("compaction-mutation-contract.test.mjs passed");
@@ -35,6 +35,36 @@ async function request(pathname, { method = "GET", body, timeoutMs = 5_000 } = {
35
35
  return { status: response.status, body: payload };
36
36
  }
37
37
 
38
+ async function waitForSseEvent(tabId, predicate) {
39
+ const controller = new AbortController();
40
+ const timeout = setTimeout(() => controller.abort(new Error("timed out waiting for SSE event")), 8_000);
41
+ try {
42
+ const response = await fetch(`http://127.0.0.1:${port}/api/events?tab=${encodeURIComponent(tabId)}`, { signal: controller.signal });
43
+ assert.equal(response.status, 200, "SSE connection should open");
44
+ const reader = response.body.getReader();
45
+ const decoder = new TextDecoder();
46
+ let buffer = "";
47
+ while (true) {
48
+ const { done, value } = await reader.read();
49
+ if (done) break;
50
+ buffer += decoder.decode(value, { stream: true });
51
+ let boundary;
52
+ while ((boundary = buffer.indexOf("\n\n")) >= 0) {
53
+ const block = buffer.slice(0, boundary);
54
+ buffer = buffer.slice(boundary + 2);
55
+ const data = block.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trim()).join("\n");
56
+ if (!data) continue;
57
+ const event = JSON.parse(data);
58
+ if (predicate(event)) return { event };
59
+ }
60
+ }
61
+ throw new Error("SSE stream ended before the expected event");
62
+ } finally {
63
+ clearTimeout(timeout);
64
+ controller.abort();
65
+ }
66
+ }
67
+
38
68
  async function waitFor(description, probe, { attempts = 60, intervalMs = 100 } = {}) {
39
69
  let last;
40
70
  for (let attempt = 0; attempt < attempts; attempt += 1) {
@@ -53,6 +83,7 @@ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "12
53
83
  stdio: ["ignore", "pipe", "pipe"],
54
84
  env: { ...process.env, PI_WEBUI_SETTINGS_FILE: settingsFile },
55
85
  });
86
+ const childClosed = new Promise((resolve) => child.once("close", resolve));
56
87
  let serverOutput = "";
57
88
  child.stdout.on("data", (chunk) => { serverOutput += String(chunk); });
58
89
  child.stderr.on("data", (chunk) => { serverOutput += String(chunk); });
@@ -113,6 +144,85 @@ try {
113
144
  assert.equal(queuedSlashPrompt.status, 202, "slash prompt sent during compaction should remain a prompt in the resume queue");
114
145
  assert.equal(queuedSlashPrompt.body?.data?.queueLength, 4);
115
146
 
147
+ const compactionQueueBeforeMutation = {
148
+ source: "webui-compaction",
149
+ revision: 4,
150
+ steering: [RESUME_PROMPT, STEER_PROMPT],
151
+ followUp: [FOLLOW_UP_PROMPT, QUEUED_SLASH_PROMPT],
152
+ };
153
+ const editedFollowUp = `${FOLLOW_UP_PROMPT} edited`;
154
+ const compactionEdit = await request("/api/queue/mutate", {
155
+ method: "POST",
156
+ body: {
157
+ tab: tabId,
158
+ source: "webui-compaction",
159
+ kind: "followUp",
160
+ revision: compactionQueueBeforeMutation.revision,
161
+ expected: { steering: compactionQueueBeforeMutation.steering, followUp: compactionQueueBeforeMutation.followUp },
162
+ operation: { type: "edit", index: 0, expectedText: FOLLOW_UP_PROMPT, text: ` ${editedFollowUp} ` },
163
+ },
164
+ });
165
+ assert.equal(compactionEdit.status, 200, `compaction follow-up edits should succeed before draining: ${compactionEdit.body?.error || ""}`);
166
+ assert.deepEqual(compactionEdit.body?.data, {
167
+ mutated: true,
168
+ source: "webui-compaction",
169
+ queue: {
170
+ source: "webui-compaction",
171
+ revision: 5,
172
+ steering: [RESUME_PROMPT, STEER_PROMPT],
173
+ followUp: [editedFollowUp, QUEUED_SLASH_PROMPT],
174
+ draining: false,
175
+ },
176
+ }, "compaction edits return an authoritative source-tagged revisioned snapshot");
177
+
178
+ const staleCompactionMove = await request("/api/queue/mutate", {
179
+ method: "POST",
180
+ body: {
181
+ tab: tabId,
182
+ source: "webui-compaction",
183
+ kind: "followUp",
184
+ revision: compactionQueueBeforeMutation.revision,
185
+ expected: { steering: compactionQueueBeforeMutation.steering, followUp: compactionQueueBeforeMutation.followUp },
186
+ operation: { type: "move", from: 1, to: 0, expectedText: QUEUED_SLASH_PROMPT },
187
+ },
188
+ });
189
+ assert.equal(staleCompactionMove.status, 409, "compaction mutations reject stale revisions and snapshots");
190
+ assert.equal(staleCompactionMove.body?.data?.reason, "queue-changed");
191
+
192
+ const compactionMove = await request("/api/queue/mutate", {
193
+ method: "POST",
194
+ body: {
195
+ tab: tabId,
196
+ source: "webui-compaction",
197
+ kind: "followUp",
198
+ revision: 5,
199
+ expected: { steering: [RESUME_PROMPT, STEER_PROMPT], followUp: [editedFollowUp, QUEUED_SLASH_PROMPT] },
200
+ operation: { type: "move", from: 1, to: 0, expectedText: QUEUED_SLASH_PROMPT },
201
+ },
202
+ });
203
+ assert.equal(compactionMove.status, 200, "compaction follow-up moves should reorder among the fixed follow-up slots");
204
+ assert.deepEqual(compactionMove.body?.data?.queue?.followUp, [QUEUED_SLASH_PROMPT, editedFollowUp]);
205
+ assert.deepEqual(compactionMove.body?.data?.queue?.steering, [RESUME_PROMPT, STEER_PROMPT], "compaction reordering must leave steering slots fixed");
206
+
207
+ const drainingCompactionQueue = await waitForSseEvent(
208
+ tabId,
209
+ (event) => event.type === "webui_compaction_queue_update" && event.source === "webui-compaction" && event.draining === true,
210
+ );
211
+ const drainingMutation = await request("/api/queue/mutate", {
212
+ method: "POST",
213
+ body: {
214
+ tab: tabId,
215
+ source: "webui-compaction",
216
+ kind: "followUp",
217
+ revision: 6,
218
+ expected: { steering: [RESUME_PROMPT, STEER_PROMPT], followUp: [QUEUED_SLASH_PROMPT, editedFollowUp] },
219
+ operation: { type: "edit", index: 0, expectedText: QUEUED_SLASH_PROMPT, text: "must not apply while draining" },
220
+ },
221
+ });
222
+ assert.equal(drainingCompactionQueue.event.revision, 7, "draining queue transition advances the monotonic queue revision");
223
+ assert.equal(drainingMutation.status, 409, "compaction mutations are rejected while draining");
224
+ assert.equal(drainingMutation.body?.data?.reason, "queue-draining");
225
+
116
226
  const messagesBeforeEnd = await request(`/api/messages?tab=${encodeURIComponent(tabId)}`);
117
227
  assert.equal(messagesBeforeEnd.status, 200);
118
228
  const queuedMessages = [RESUME_PROMPT, STEER_PROMPT, FOLLOW_UP_PROMPT, QUEUED_SLASH_PROMPT];
@@ -128,7 +238,7 @@ try {
128
238
  const resumedMessages = await waitFor("queued prompts to resume after compaction", async () => {
129
239
  const messages = await request(`/api/messages?tab=${encodeURIComponent(tabId)}`);
130
240
  const entries = messages.body?.data?.messages || [];
131
- const expected = [`prompt:${RESUME_PROMPT}`, `steer:${STEER_PROMPT}`, `follow_up:${FOLLOW_UP_PROMPT}`, `prompt:${QUEUED_SLASH_PROMPT}`];
241
+ const expected = [`prompt:${RESUME_PROMPT}`, `steer:${STEER_PROMPT}`, `prompt:${QUEUED_SLASH_PROMPT}`, `follow_up:${editedFollowUp}`];
132
242
  return expected.every((content, index) => String(entries[index]?.content || "") === content) ? messages : false;
133
243
  }, { attempts: 80, intervalMs: 100 });
134
244
  assert.equal(resumedMessages.status, 200);
@@ -160,7 +270,8 @@ try {
160
270
  assert.notEqual(child.exitCode, null, "server should exit after /api/shutdown");
161
271
  } finally {
162
272
  if (child.exitCode === null) child.kill("SIGKILL");
163
- await rm(cwd, { recursive: true, force: true });
273
+ await childClosed;
274
+ await rm(cwd, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
164
275
  }
165
276
 
166
277
  console.log("compaction-resume-harness.test.mjs passed");
@@ -17,6 +17,11 @@ assert.match(server, /async function flushCompactionQueue\(tab, event = \{\}\)[\
17
17
  assert.match(server, /async function flushCompactionQueue\(tab, event = \{\}\)[\s\S]*queuedPromptCommand\(item\)/, "compaction queue flush should start a new prompt when no run resumes automatically");
18
18
  assert.match(server, /function queuedRetryCommand\(item\)[\s\S]*queuedStreamingCommand\(item\)/, "post-compaction continuation should send later queued items as steering or follow-up messages");
19
19
  assert.match(server, /function stateWithPendingThinking\(tab, state\)[\s\S]*compactionQueueForTab\(tab\)\.length[\s\S]*pendingMessageCount/, "state responses should include Web UI compaction queue length while prompts wait to resume");
20
+ assert.match(server, /function eventForTabClients\(tab, event\)[\s\S]*event\?\.type === "queue_update"[\s\S]*source: "pi-runtime"/, "Pi runtime queue events should be decorated with their source at the server boundary");
21
+ assert.match(server, /function compactionQueueSnapshot\(tab\)[\s\S]*source: "webui-compaction"[\s\S]*revision: compactionQueueRevision\(tab\)[\s\S]*draining:/, "compaction queue snapshots should include source, monotonic revision, and draining state");
22
+ assert.match(server, /function mutateCompactionFollowUpQueue\(tab, request\)[\s\S]*if \(current\.draining\) return failed\("queue-draining"\)[\s\S]*request\.revision !== current\.revision[\s\S]*slots\.forEach\(\(slot, index\) => \{ queue\[slot\] = followUps\[index\]; \}\)/, "compaction mutations should reject draining/stale requests and only permute follow-up slots");
23
+ assert.match(server, /function mutateCompactionFollowUpQueue\(tab, request\)[\s\S]*queue\[slots\[operation\.index\]\]\.command\.message = operation\.text[\s\S]*advanceCompactionQueueRevision\(tab\)[\s\S]*broadcastTabEvent\(tab, compactionQueueEvent\(tab\)\)/, "compaction edits should preserve command metadata and emit one authoritative update after revision advancement");
24
+ assert.match(server, /url\.pathname === "\/api\/queue\/mutate" && req\.method === "POST"[\s\S]*request\.source === "webui-compaction"[\s\S]*mutateCompactionFollowUpQueue[\s\S]*status = data\?\.mutated === true \? 200 : conflict \? 409 : 400/, "queue mutation HTTP handling should keep compaction mutations source-specific and map conflicts to 409");
20
25
 
21
26
  assert.match(app, /function isRunActive\(\) \{\n\s+return !!currentState\?\.isStreaming \|\| !!currentState\?\.isCompacting/, "frontend should treat compaction as an active run for composer controls");
22
27
  assert.match(app, /const targetWasCompacting = !!currentState\?\.isCompacting;[\s\S]*const targetWasBusy = targetWasStreaming \|\| targetWasCompacting[\s\S]*if \(targetWasBusy\) body\.streamingBehavior = streamingBehavior \|\| busyBehavior/, "prompt send should use busy behavior while streaming or compacting");
@@ -25,6 +25,11 @@ assert.match(
25
25
  /const changedTabId = response\.data\?\.tab\?\.id \|\| tab\.id;[\s\S]*?resetGitWorkflowForTab\(changedTabId\);[\s\S]*?clearGitFooterPayloadState\(changedTabId\);[\s\S]*?if \(!isCurrentTabContext\(tabContext\)\)/,
26
26
  "a cwd change that finishes after a tab switch should invalidate that tab's old footer state",
27
27
  );
28
+ assert.match(
29
+ app,
30
+ /if \(response\.data\?\.changed !== false\) closeFileViewer\(\);\s*const nextContext = setActiveTabId\(response\.data\?\.tab\?\.id \|\| activeTabId\);\s*resetActiveTabUi\(\);/,
31
+ "a successful cwd change should discard the old workspace viewer instead of restoring its path in the replacement workspace",
32
+ );
28
33
 
29
34
  assert.match(
30
35
  app,
@@ -0,0 +1,21 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const css = await readFile(join(root, "public", "styles.css"), "utf8");
8
+
9
+ const selectionBarRule = css.match(/\.file-selection-bar \{[^}]*\}/)?.[0] || "";
10
+ assert.match(
11
+ selectionBarRule,
12
+ /position:\s*absolute;[^}]*right:\s*0\.72rem;[^}]*bottom:\s*1\.68rem;[^}]*left:\s*0\.72rem;[^}]*z-index:\s*7;/,
13
+ "the file selection comment bar should overlay the viewer instead of shifting selected text",
14
+ );
15
+ assert.doesNotMatch(
16
+ selectionBarRule,
17
+ /flex:\s*0\s+0\s+auto;/,
18
+ "the file selection comment bar must stay out of the viewer's flex layout",
19
+ );
20
+
21
+ console.log("file selection overlay static tests passed");
@@ -0,0 +1,65 @@
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
+ assert.match(
15
+ html,
16
+ /id="fileViewerSearchBar"[\s\S]*role="search"[\s\S]*id="fileViewerSearchInput"[\s\S]*id="fileViewerSearchCount"[\s\S]*id="fileViewerSearchPrevButton"[\s\S]*id="fileViewerSearchNextButton"[\s\S]*id="fileViewerSearchCloseButton"/,
17
+ "the file viewer should expose an accessible in-file search bar with match navigation",
18
+ );
19
+ assert.match(html, /id="fileViewerSearchInput"[^>]*aria-controls="fileViewerEditor"/, "the in-file search input should identify the source editor it searches");
20
+ assert.match(app, /fileViewerSearchInput: \$\("#fileViewerSearchInput"\)/, "file search controls should be registered in the element map");
21
+ assert.match(app, /const FILE_VIEWER_SEARCH_MATCH_LIMIT = 10_000;/, "in-file search should bound match collection for large files");
22
+ assert.match(app, /function collectFileViewerSearchMatches\([\s\S]*fileViewerSearchText\(\)\.toLowerCase\(\)[\s\S]*haystack\.indexOf\(needle, offset\)/, "in-file search should collect case-insensitive matches from the active viewer surface");
23
+
24
+ const helperStart = app.indexOf("const FILE_VIEWER_SEARCH_MATCH_LIMIT = 10_000;");
25
+ const helperEnd = app.indexOf("\nfunction updateFileViewerSearchCount()", helperStart);
26
+ assert.ok(helperStart >= 0 && helperEnd > helperStart, "file viewer search matching should remain independently testable");
27
+ const helperSource = app.slice(helperStart, helperEnd);
28
+ const sourceMatches = JSON.parse(vm.runInNewContext(`${helperSource}\nJSON.stringify(collectFileViewerSearchMatches("alpha"))`, {
29
+ activeFileViewer: { mode: "source", content: "stale" },
30
+ elements: { fileViewerEditor: { value: "Alpha beta ALPHA" }, fileViewerPreview: { textContent: "preview" }, fileViewerChanges: { textContent: "changes" } },
31
+ resolveFileViewerMode: (viewer) => viewer.mode,
32
+ }));
33
+ assert.deepEqual(sourceMatches, { matches: [{ start: 0, end: 5 }, { start: 11, end: 16 }], truncated: false }, "source search should use live edited text and match case-insensitively");
34
+ const previewMatches = JSON.parse(vm.runInNewContext(`${helperSource}\nJSON.stringify(collectFileViewerSearchMatches("rendered"))`, {
35
+ activeFileViewer: { mode: "preview" },
36
+ elements: { fileViewerEditor: { value: "source" }, fileViewerPreview: { textContent: "Rendered preview" }, fileViewerChanges: { textContent: "changes" } },
37
+ resolveFileViewerMode: (viewer) => viewer.mode,
38
+ }));
39
+ assert.deepEqual(previewMatches, { matches: [{ start: 0, end: 8 }], truncated: false }, "preview search should use the rendered file surface instead of hidden source text");
40
+ const truncatedMatches = JSON.parse(vm.runInNewContext(`${helperSource}\nJSON.stringify(collectFileViewerSearchMatches("a"))`, {
41
+ activeFileViewer: { mode: "source" },
42
+ elements: { fileViewerEditor: { value: "a".repeat(10_001) }, fileViewerPreview: { textContent: "" }, fileViewerChanges: { textContent: "" } },
43
+ resolveFileViewerMode: (viewer) => viewer.mode,
44
+ }));
45
+ assert.equal(truncatedMatches.matches.length, 10_000, "large-file match collection should stop at the declared bound");
46
+ assert.equal(truncatedMatches.truncated, true, "large-file match collection should disclose additional matches beyond the bound");
47
+ assert.match(app, /function fileViewerSearchSurface\(\)[\s\S]*mode === "preview"[\s\S]*mode === "changes"[\s\S]*fileViewerEditor/, "search should stay scoped to the current Source, Preview, or Changes surface");
48
+ assert.match(app, /function focusFileViewerSearchMatch\([\s\S]*setSelectionRange\(match\.start, match\.end\)[\s\S]*textOffsetPosition\(surface, match\.start\)[\s\S]*CSS\?\.highlights[\s\S]*scrollIntoView/, "match navigation should select source matches and highlight rendered matches without mutating the document selection");
49
+ assert.doesNotMatch(app.slice(app.indexOf("function focusFileViewerSearchMatch("), app.indexOf("\nfunction runFileViewerSearch(", app.indexOf("function focusFileViewerSearchMatch("))), /getSelection|addRange|removeAllRanges/, "rendered file search must not overwrite selections used by the Send to Pi workflow");
50
+ assert.match(app, /function runFileViewerSearch\([\s\S]*setAttribute\("aria-controls", surface\.id\)/, "the search input should identify the active Source, Preview, or Changes surface");
51
+ assert.match(app, /function setFileViewerMode\([\s\S]*updateFileViewerUi\(\);[\s\S]*runFileViewerSearch\(\{ navigate: true \}\)/, "an explicit mode switch should reveal the first match on the new surface");
52
+ assert.match(app, /function updateFileViewerUi\([\s\S]*runFileViewerSearch\(\{ navigate: false \}\)/, "background viewer refreshes should reindex without stealing focus or scrolling to a match");
53
+ assert.match(app, /fileViewerSearchInput\?\.addEventListener\("input"[\s\S]*setTimeout\([\s\S]*runFileViewerSearch\(\{ navigate: true \}\)[\s\S]*150/, "typing should debounce search work for large files");
54
+ assert.match(app, /fileViewerSearchInput\?\.addEventListener\("keydown"[\s\S]*event\.key === "Enter"[\s\S]*stepFileViewerSearch\(event\.shiftKey \? -1 : 1\)[\s\S]*event\.key === "Escape"[\s\S]*closeFileViewerSearch\(\)/, "Enter, Shift+Enter, and Escape should navigate or close in-file search");
55
+ assert.match(
56
+ app,
57
+ /if \(activeFileViewer && elements\.fileViewerPane\?\.contains\(event\.target\)\) openFileViewerSearch\(\);\s*else openChatSearch\(\);/,
58
+ "Ctrl/Cmd+F should route to in-file search only when the event target is inside the open file viewer",
59
+ );
60
+ assert.match(app, /function openChatSearch\(\)[\s\S]*closeFileViewerSearch\(\{ restoreFocus: false \}\)/, "opening transcript search should close any stale in-file search bar");
61
+ assert.match(css, /\.chat-search-bar,\s*\.file-viewer-search-bar \{/, "file search should reuse the transcript search layout conventions");
62
+ assert.match(css, /\.file-viewer-search-bar\[hidden\] \{ display: none; \}/, "the hidden file search bar should not consume viewer space");
63
+ assert.match(css, /::highlight\(file-viewer-search-current\)[\s\S]*\.file-viewer-search-current-fallback/, "rendered matches should have an exact CSS Highlight and a non-destructive fallback affordance");
64
+
65
+ console.log("file viewer focused search static tests passed");