@firstpick/pi-package-webui 0.8.9 → 0.9.1

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.
package/public/index.html CHANGED
@@ -678,6 +678,7 @@
678
678
  </div>
679
679
  </div>
680
680
  <div class="file-viewer-content">
681
+ <pre id="fileViewerSearchOverlay" class="file-viewer-search-overlay" aria-hidden="true" hidden></pre>
681
682
  <textarea id="fileViewerEditor" class="file-viewer-editor" wrap="soft" spellcheck="false" aria-label="File contents"></textarea>
682
683
  <div id="fileViewerPreview" class="file-viewer-preview markdown-body" tabindex="0" hidden></div>
683
684
  <div id="fileViewerChanges" class="file-viewer-changes" tabindex="0" aria-label="Git changes for this file" hidden></div>
package/public/styles.css CHANGED
@@ -940,6 +940,7 @@ body.side-panel-resizing * {
940
940
  .file-viewer-editor,
941
941
  .file-viewer-preview,
942
942
  .file-viewer-changes {
943
+ grid-area: 1 / 1;
943
944
  width: 100%;
944
945
  height: 100%;
945
946
  min-width: 0;
@@ -950,6 +951,8 @@ body.side-panel-resizing * {
950
951
  background: rgba(var(--ctp-crust-rgb), 0.64);
951
952
  }
952
953
  .file-viewer-editor {
954
+ position: relative;
955
+ z-index: 1;
953
956
  resize: none;
954
957
  padding: 0.72rem;
955
958
  overflow-x: hidden;
@@ -960,6 +963,37 @@ body.side-panel-resizing * {
960
963
  line-height: 1.45;
961
964
  white-space: pre-wrap;
962
965
  }
966
+ .file-viewer-search-overlay {
967
+ grid-area: 1 / 1;
968
+ z-index: 0;
969
+ box-sizing: border-box;
970
+ width: 100%;
971
+ height: 100%;
972
+ min-width: 0;
973
+ min-height: 0;
974
+ margin: 0;
975
+ padding: 0.72rem;
976
+ overflow: auto;
977
+ border: 1px solid rgba(180, 190, 254, 0.16);
978
+ border-radius: 0.86rem;
979
+ background: rgba(var(--ctp-crust-rgb), 0.64);
980
+ color: transparent;
981
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
982
+ font-size: 0.82rem;
983
+ line-height: 1.45;
984
+ overflow-wrap: anywhere;
985
+ pointer-events: none;
986
+ scrollbar-width: none;
987
+ white-space: pre-wrap;
988
+ }
989
+ .file-viewer-search-overlay::-webkit-scrollbar { display: none; }
990
+ .file-viewer-content.search-highlights-source .file-viewer-editor { background: transparent; }
991
+ .file-viewer-search-match {
992
+ border-radius: 0.12rem;
993
+ background: rgba(249, 226, 175, 0.48);
994
+ color: transparent;
995
+ }
996
+ .file-viewer-search-match.current { background: rgba(250, 179, 135, 0.78); }
963
997
  .file-viewer-preview {
964
998
  padding: 0.85rem;
965
999
  line-height: 1.55;
@@ -11825,7 +11859,6 @@ body:not(.mobile-keyboard-open) .composer-input-row:has(.composer-workflow-mode-
11825
11859
  }
11826
11860
  body.subagent-terminal-active .workspace-dashboard,
11827
11861
  body.subagent-terminal-active .widget-area,
11828
- body.subagent-terminal-active .chat-search-bar,
11829
11862
  body.subagent-terminal-active .chat,
11830
11863
  body.subagent-terminal-active .feedback-tray,
11831
11864
  body.subagent-terminal-active .jump-to-latest-button,
@@ -15167,16 +15200,24 @@ button.git-workflow-step { min-height: 1.9rem; }
15167
15200
  }
15168
15201
  .chat-search-button:hover,
15169
15202
  .file-viewer-search-button:hover { background: var(--panel); }
15170
- ::highlight(file-viewer-search-current) {
15203
+ ::highlight(file-viewer-search-match),
15204
+ ::highlight(chat-search-match) {
15205
+ color: inherit;
15206
+ background: rgba(249, 226, 175, 0.48);
15207
+ }
15208
+ ::highlight(file-viewer-search-current),
15209
+ ::highlight(chat-search-current) {
15171
15210
  color: var(--button-primary-text);
15172
- background: var(--ctp-yellow);
15211
+ background: var(--ctp-peach);
15173
15212
  }
15174
- .file-viewer-search-current-fallback {
15175
- outline: 2px solid var(--ctp-yellow);
15176
- outline-offset: 2px;
15213
+ .file-viewer-search-match-fallback,
15214
+ .message.search-match {
15215
+ outline: 1px solid rgba(249, 226, 175, 0.72);
15216
+ outline-offset: 1px;
15177
15217
  }
15218
+ .file-viewer-search-current-fallback,
15178
15219
  .message.search-current {
15179
- outline: 2px solid var(--accent-2);
15220
+ outline: 2px solid var(--ctp-peach);
15180
15221
  outline-offset: 2px;
15181
15222
  }
15182
15223
 
@@ -0,0 +1,28 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const [app, server] = await Promise.all([
8
+ readFile(join(root, "public", "app.js"), "utf8"),
9
+ readFile(join(root, "bin", "pi-webui.mjs"), "utf8"),
10
+ ]);
11
+
12
+ assert.match(
13
+ app,
14
+ /function renderAppRunnerWidget\(\)[\s\S]*appendReleaseNpmTerminalLine\(terminal, line\)/,
15
+ "frontend should render app runner output through the shared terminal-line renderer",
16
+ );
17
+ assert.match(
18
+ app,
19
+ /function appendReleaseNpmTerminalLine\(parent, line\)[\s\S]*renderAnsiText\(row, line\)/,
20
+ "app-runner terminal lines should apply supported ANSI styling and hide unsupported ANSI controls",
21
+ );
22
+ assert.match(
23
+ server,
24
+ /consumeAppRunnerTerminalChunk\([\s\S]*carriageReturnPending/,
25
+ "server should preserve terminal-style carriage-return state across app-runner chunks",
26
+ );
27
+
28
+ console.log("app runner terminal static contracts passed");
@@ -0,0 +1,65 @@
1
+ import assert from "node:assert/strict";
2
+ import { consumeAppRunnerTerminalChunk } from "../lib/app-runner-terminal.mjs";
3
+
4
+ function consume(chunks) {
5
+ let state = { line: "", carriageReturnPending: false };
6
+ const lines = [];
7
+ for (const chunk of chunks) {
8
+ const result = consumeAppRunnerTerminalChunk(state, chunk);
9
+ lines.push(...result.lines);
10
+ state = result;
11
+ }
12
+ return { lines, line: state.line, carriageReturnPending: state.carriageReturnPending };
13
+ }
14
+
15
+ assert.deepEqual(
16
+ consume(["Discovering packages\nChecking package statuses: 1/77\rChecking package statuses: 2/77\rChecking package statuses: 3/77"]),
17
+ {
18
+ lines: ["Discovering packages"],
19
+ line: "Checking package statuses: 3/77",
20
+ carriageReturnPending: false,
21
+ },
22
+ "bare carriage returns should replace one live progress line instead of adding scrollback",
23
+ );
24
+
25
+ assert.deepEqual(
26
+ consume(["first\r", "\nsecond\r\nthird\n"]),
27
+ {
28
+ lines: ["first", "second", "third"],
29
+ line: "",
30
+ carriageReturnPending: false,
31
+ },
32
+ "CRLF should commit one line even when the pair is split across chunks",
33
+ );
34
+
35
+ assert.deepEqual(
36
+ consume(["50% complete\r", "51% complete"]),
37
+ {
38
+ lines: [],
39
+ line: "51% complete",
40
+ carriageReturnPending: false,
41
+ },
42
+ "a trailing carriage return should replace the live line when the next chunk arrives",
43
+ );
44
+
45
+ assert.deepEqual(
46
+ consume(["progress 1\r\u001b[2Kprogress \u001b[32m2\u001b[0m\n"]),
47
+ {
48
+ lines: ["\u001b[2Kprogress \u001b[32m2\u001b[0m"],
49
+ line: "",
50
+ carriageReturnPending: false,
51
+ },
52
+ "ANSI control and SGR sequences should remain intact for the browser renderer",
53
+ );
54
+
55
+ assert.deepEqual(
56
+ consume(["abc\bD"]),
57
+ {
58
+ lines: [],
59
+ line: "abD",
60
+ carriageReturnPending: false,
61
+ },
62
+ "backspace should update the current line without exposing a control glyph",
63
+ );
64
+
65
+ console.log("app runner terminal reducer tests passed");
@@ -45,6 +45,11 @@ async function activeTabId(page) {
45
45
  return page.locator("#tabBar [role=\"tab\"][aria-selected=\"true\"]").evaluate((node) => node.closest("[data-tab-id]")?.dataset.tabId || "");
46
46
  }
47
47
 
48
+ async function tabClientCount(page, tabId) {
49
+ const payload = await api(page, "/api/tabs");
50
+ return Number(payload.data?.tabs?.find((tab) => tab.id === tabId)?.clientCount || 0);
51
+ }
52
+
48
53
  async function startContinuityRunner(page) {
49
54
  const tabId = await activeTabId(page) || (await tabIds(page))[0];
50
55
  const configured = await api(page, "/api/app-runner-config", {
@@ -205,6 +210,63 @@ test.afterAll(async () => {
205
210
  await rm(tempRoot, { recursive: true, force: true });
206
211
  });
207
212
 
213
+ test("only hidden pages disconnect live events and resume from one authoritative snapshot", async ({ page }) => {
214
+ await page.setViewportSize({ width: 1280, height: 800 });
215
+ await page.goto(baseURL);
216
+ const tabId = await activeTabId(page) || (await tabIds(page))[0];
217
+ assert.ok(tabId, "the background catch-up fixture requires an active tab");
218
+ await expect.poll(() => tabClientCount(page, tabId)).toBe(1);
219
+
220
+ await page.evaluate(() => {
221
+ window.__backgroundStreamProof = { closeCalls: 0, constructions: 0 };
222
+ const NativeEventSource = window.EventSource;
223
+ const nativeClose = NativeEventSource.prototype.close;
224
+ NativeEventSource.prototype.close = function (...args) {
225
+ window.__backgroundStreamProof.closeCalls += 1;
226
+ return nativeClose.apply(this, args);
227
+ };
228
+ window.EventSource = new Proxy(NativeEventSource, {
229
+ construct(target, args, receiver) {
230
+ window.__backgroundStreamProof.constructions += 1;
231
+ return Reflect.construct(target, args, receiver);
232
+ },
233
+ });
234
+ window.dispatchEvent(new Event("blur"));
235
+ });
236
+ await expect.poll(() => tabClientCount(page, tabId)).toBe(1);
237
+ await expect.poll(() => page.evaluate(() => window.__backgroundStreamProof.closeCalls)).toBe(0);
238
+
239
+ await page.evaluate(() => {
240
+ window.__backgroundVisibilityState = "hidden";
241
+ Object.defineProperty(document, "visibilityState", {
242
+ configurable: true,
243
+ get: () => window.__backgroundVisibilityState,
244
+ });
245
+ document.dispatchEvent(new Event("visibilitychange"));
246
+ });
247
+ await expect.poll(() => tabClientCount(page, tabId)).toBe(0);
248
+ await expect.poll(() => page.evaluate(() => window.__backgroundStreamProof.closeCalls)).toBe(1);
249
+
250
+ const completedBefore = await page.locator("#chat .message.assistant", { hasText: "continuity stream complete" }).count();
251
+ await api(page, `/api/prompt?tab=${encodeURIComponent(tabId)}`, {
252
+ method: "POST",
253
+ data: { message: "fixture continuity delayed stream", requestId: `background-catch-up-${Date.now()}` },
254
+ });
255
+ await waitForFixtureSettlement(page, tabId);
256
+ await expect(page.locator("#chat .message.assistant", { hasText: "continuity stream complete" })).toHaveCount(completedBefore);
257
+
258
+ const resumedAt = Date.now();
259
+ await page.evaluate(() => {
260
+ window.__backgroundVisibilityState = "visible";
261
+ document.dispatchEvent(new Event("visibilitychange"));
262
+ });
263
+ await expect.poll(() => tabClientCount(page, tabId)).toBe(1);
264
+ await expect(page.locator("#chat .message.assistant", { hasText: "continuity stream complete" })).toHaveCount(completedBefore + 1);
265
+ const proof = await page.evaluate(() => window.__backgroundStreamProof);
266
+ assert.equal(proof.constructions, 1, "foreground catch-up should create exactly one replacement EventSource");
267
+ assert.ok(Date.now() - resumedAt < 4_000, "the bounded snapshot resume should complete without replaying the hidden stream duration");
268
+ });
269
+
208
270
  test("autosizing the main input does not move settled agent output", async ({ page }) => {
209
271
  await page.setViewportSize({ width: 1280, height: 800 });
210
272
  await page.goto(baseURL);
@@ -982,3 +1044,35 @@ test("submitting a new turn resumes bottom-follow and keeps the streamed tail an
982
1044
  await waitForFixtureSettlement(page);
983
1045
  await expect.poll(() => chat.evaluate((node) => Math.round(node.scrollHeight - node.clientHeight - node.scrollTop))).toBe(0);
984
1046
  });
1047
+
1048
+ test("Latest reaches the live edge during a paused transcript reconciliation", async ({ page }) => {
1049
+ await page.setViewportSize({ width: 900, height: 420 });
1050
+ await page.goto(baseURL);
1051
+ await expect.poll(() => page.locator("#chat .message").count()).toBeGreaterThanOrEqual(3);
1052
+ await page.addStyleTag({ content: "#chat > .message { min-height: 10rem; }" });
1053
+
1054
+ const chat = page.locator("#chat");
1055
+ const pausedRemaining = await chat.evaluate((node) => {
1056
+ node.style.scrollBehavior = "auto";
1057
+ node.scrollTop = node.scrollHeight;
1058
+ node.dispatchEvent(new WheelEvent("wheel", { deltaY: -180, bubbles: true }));
1059
+ node.scrollTop = Math.max(0, node.scrollHeight - node.clientHeight - 180);
1060
+ node.dispatchEvent(new Event("scroll", { bubbles: true }));
1061
+ node.style.removeProperty("scroll-behavior");
1062
+ return node.scrollHeight - node.clientHeight - node.scrollTop;
1063
+ });
1064
+ assert.ok(pausedRemaining > 96, `the fixture must pause above the bottom threshold, got ${pausedRemaining}px`);
1065
+ await expect(page.locator("#jumpToLatestButton")).toBeVisible();
1066
+
1067
+ await triggerDelayedStream(page);
1068
+ await expect(page.locator("#jumpToLatestButton")).toBeVisible();
1069
+ await page.locator("#jumpToLatestButton").click();
1070
+
1071
+ await expect.poll(() => chat.evaluate((node) => ({
1072
+ following: document.querySelector("#jumpToLatestButton")?.hidden === true,
1073
+ remaining: Math.round(node.scrollHeight - node.clientHeight - node.scrollTop),
1074
+ }))).toEqual({ following: true, remaining: 0 });
1075
+ await expect(page.locator(".message.assistant.streaming .streaming-markdown").last()).toContainText("continuity");
1076
+ await waitForFixtureSettlement(page);
1077
+ await expect.poll(() => chat.evaluate((node) => Math.round(node.scrollHeight - node.clientHeight - node.scrollTop))).toBe(0);
1078
+ });
@@ -0,0 +1,104 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { createServer } from "node:net";
4
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { dirname, join } from "node:path";
7
+ import { setTimeout as delay } from "node:timers/promises";
8
+ import { fileURLToPath } from "node:url";
9
+ import { expect, test } from "@playwright/test";
10
+
11
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
12
+ const serverScript = join(root, "bin", "pi-webui.mjs");
13
+ const fakePi = join(root, "tests", "fixtures", "fake-pi.mjs");
14
+
15
+ async function freePort() {
16
+ const server = createServer();
17
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
18
+ const { port } = server.address();
19
+ await new Promise((resolve) => server.close(resolve));
20
+ return port;
21
+ }
22
+
23
+ let child;
24
+ let baseURL;
25
+ let tempRoot;
26
+ let output = "";
27
+
28
+ test.beforeAll(async () => {
29
+ const port = await freePort();
30
+ tempRoot = await mkdtemp(join(tmpdir(), "pi-webui-search-highlights-"));
31
+ await writeFile(join(tempRoot, "search-sample.txt"), "Alpha beta alpha\nplain text\nALPHA final\n");
32
+ baseURL = `http://127.0.0.1:${port}`;
33
+ child = spawn(process.execPath, [serverScript, "--cwd", tempRoot, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
34
+ stdio: ["ignore", "pipe", "pipe"],
35
+ env: {
36
+ ...process.env,
37
+ PI_WEBUI_RPC_SUPERVISOR: "0",
38
+ PI_CODING_AGENT_DIR: join(tempRoot, "agent"),
39
+ PI_WEBUI_SETTINGS_FILE: join(tempRoot, "settings.json"),
40
+ },
41
+ });
42
+ child.stdout.on("data", (chunk) => { output += String(chunk); });
43
+ child.stderr.on("data", (chunk) => { output += String(chunk); });
44
+ for (let attempt = 0; attempt < 80; attempt += 1) {
45
+ if (child.exitCode !== null) break;
46
+ try {
47
+ const response = await fetch(`${baseURL}/api/health`, { signal: AbortSignal.timeout(500) });
48
+ if (response.ok) return;
49
+ } catch {
50
+ // Poll only until the package server and fake Pi fixture are ready.
51
+ }
52
+ await delay(100);
53
+ }
54
+ throw new Error(`Pi Web UI did not start:\n${output}`);
55
+ });
56
+
57
+ test.afterAll(async () => {
58
+ if (child?.exitCode === null) {
59
+ await fetch(`${baseURL}/api/shutdown`, { method: "POST", signal: AbortSignal.timeout(1_000) }).catch(() => undefined);
60
+ await new Promise((resolve) => child.once("exit", resolve));
61
+ }
62
+ await rm(tempRoot, { recursive: true, force: true });
63
+ });
64
+
65
+ test("highlights every transcript and source-file match while retaining current-match navigation", async ({ page }) => {
66
+ await page.setViewportSize({ width: 1440, height: 900 });
67
+ await page.goto(baseURL);
68
+ await expect(page.locator("#chat .message")).toHaveCount(3);
69
+
70
+ await page.keyboard.press("Control+F");
71
+ await page.locator("#chatSearchInput").fill("fake");
72
+ await expect(page.locator("#chatSearchCount")).toHaveText("3/3");
73
+ const transcriptHighlightSizes = await page.evaluate(() => ({
74
+ all: CSS.highlights.get("chat-search-match")?.size || 0,
75
+ current: CSS.highlights.get("chat-search-current")?.size || 0,
76
+ }));
77
+ assert.deepEqual(transcriptHighlightSizes, { all: 3, current: 1 });
78
+
79
+ await page.keyboard.press("Escape");
80
+ await page.locator("#sidePanelSectionToggleFiles").click();
81
+ await page.locator("#fileTreeSearchInput").fill("search-sample.txt");
82
+ const fileResult = page.locator(".file-tree-search-item", { hasText: "search-sample.txt" });
83
+ await expect(fileResult).toBeVisible();
84
+ await fileResult.click();
85
+ await expect(page.locator("#fileViewerPane")).toBeVisible();
86
+
87
+ const editor = page.locator("#fileViewerEditor");
88
+ await editor.focus();
89
+ await page.keyboard.press("Control+F");
90
+ await page.locator("#fileViewerSearchInput").fill("alpha");
91
+ await expect(page.locator("#fileViewerSearchCount")).toHaveText("1/3");
92
+ await expect(page.locator("#fileViewerSearchOverlay .file-viewer-search-match")).toHaveCount(3);
93
+ await expect(page.locator("#fileViewerSearchOverlay .file-viewer-search-match.current")).toHaveCount(1);
94
+
95
+ const synchronizedScroll = await editor.evaluate((node) => {
96
+ node.scrollTop = 12;
97
+ node.dispatchEvent(new Event("scroll"));
98
+ return {
99
+ editor: node.scrollTop,
100
+ overlay: document.querySelector("#fileViewerSearchOverlay")?.scrollTop || 0,
101
+ };
102
+ });
103
+ assert.equal(synchronizedScroll.overlay, synchronizedScroll.editor);
104
+ });
@@ -57,7 +57,7 @@ assert.doesNotMatch(updateLatest, /isChatNearBottom/, "Latest must not remain hi
57
57
  assert.match(applyFollow, /if \(!autoFollowChat\)[\s\S]*return;/, "already queued streaming frames must honor the immediate follow pause");
58
58
  assert.match(app, /if \(!autoFollowChat\) chatPausedScrollRestoreUntil = performance\.now\(\) \+ CHAT_PROGRAMMATIC_SCROLL_GRACE_MS;/, "paused transcript reconciliation should guard against scroll events from temporary DOM height changes");
59
59
  assert.match(app, /lastChatProgrammaticScrollAt = performance\.now\(\);\s*setChatScrollTopInstant\(Math\.min\(previousScrollTop, elements\.chat\.scrollHeight\)\);/, "transcript reconciliation should mark its instant reader-position restoration as programmatic");
60
- assert.match(resumeFollow, /chatUserScrollAwayIntentUntil = 0;[\s\S]*autoFollowChat = true;/, "explicit resume should clear stale upward intent before following again");
60
+ assert.match(resumeFollow, /chatUserScrollAwayIntentUntil = 0;\s*chatPausedScrollRestoreUntil = 0;\s*autoFollowChat = true;/, "explicit resume should clear stale upward intent and any reconciliation guard before following again");
61
61
  assert.match(forceFollow, /if \(force\) resumeChatAutoFollow\(\)/, "Latest and other forced-bottom actions should use the explicit resume path");
62
62
  assert.match(app, /addEventListener\("touchstart", noteChatTouchStart[\s\S]*addEventListener\("touchend", clearChatTouchIntent[\s\S]*addEventListener\("touchcancel", clearChatTouchIntent/, "touch direction tracking should be initialized and cleared for each gesture");
63
63
 
@@ -17,7 +17,9 @@ assert.match(
17
17
  "the file viewer should expose an accessible in-file search bar with match navigation",
18
18
  );
19
19
  assert.match(html, /id="fileViewerSearchInput"[^>]*aria-controls="fileViewerEditor"/, "the in-file search input should identify the source editor it searches");
20
+ assert.match(html, /id="fileViewerSearchOverlay"[^>]*aria-hidden="true"[^>]*hidden/, "source search should provide a non-interactive highlight overlay");
20
21
  assert.match(app, /fileViewerSearchInput: \$\("#fileViewerSearchInput"\)/, "file search controls should be registered in the element map");
22
+ assert.match(app, /fileViewerSearchOverlay: \$\("#fileViewerSearchOverlay"\)/, "the source highlight overlay should be registered in the element map");
21
23
  assert.match(app, /const FILE_VIEWER_SEARCH_MATCH_LIMIT = 10_000;/, "in-file search should bound match collection for large files");
22
24
  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
25
 
@@ -45,7 +47,9 @@ const truncatedMatches = JSON.parse(vm.runInNewContext(`${helperSource}\nJSON.st
45
47
  assert.equal(truncatedMatches.matches.length, 10_000, "large-file match collection should stop at the declared bound");
46
48
  assert.equal(truncatedMatches.truncated, true, "large-file match collection should disclose additional matches beyond the bound");
47
49
  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");
50
+ assert.match(app, /function renderFileViewerSourceSearchHighlights\(\)[\s\S]*fileViewerSearchMatches\.forEach[\s\S]*make\("mark", `file-viewer-search-match/, "source search should render every collected match into the synchronized overlay");
51
+ assert.match(app, /function renderFileViewerSearchHighlights\(\)[\s\S]*new HighlightConstructor\(\.\.\.ranges\)[\s\S]*file-viewer-search-match[\s\S]*file-viewer-search-current/, "rendered file surfaces should highlight all exact ranges and distinguish the current range");
52
+ assert.match(app, /function focusFileViewerSearchMatch\(\)[\s\S]*setSelectionRange\(match\.start, match\.end\)[\s\S]*syncFileViewerSearchOverlayScroll\(\)[\s\S]*textOffsetPosition\(surface, match\.start\)[\s\S]*scrollIntoView/, "match navigation should select and center source or rendered matches without mutating document selection");
49
53
  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
54
  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
55
  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");
@@ -60,6 +64,7 @@ assert.match(
60
64
  assert.match(app, /function openChatSearch\(\)[\s\S]*closeFileViewerSearch\(\{ restoreFocus: false \}\)/, "opening transcript search should close any stale in-file search bar");
61
65
  assert.match(css, /\.chat-search-bar,\s*\.file-viewer-search-bar \{/, "file search should reuse the transcript search layout conventions");
62
66
  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");
67
+ assert.match(css, /\.file-viewer-search-overlay[\s\S]*\.file-viewer-content\.search-highlights-source[\s\S]*\.file-viewer-search-match\.current/, "source matches should use a scroll-synchronized visual overlay with a distinct current match");
68
+ assert.match(css, /::highlight\(file-viewer-search-match\)[\s\S]*::highlight\(file-viewer-search-current\)[\s\S]*\.file-viewer-search-match-fallback/, "rendered matches should highlight all exact ranges with a non-destructive fallback affordance");
64
69
 
65
70
  console.log("file viewer focused search static tests passed");
@@ -26,21 +26,23 @@ assert.match(parser, /x-codex-primary-window-minutes/, "Codex parser should read
26
26
  assert.match(parser, /x-codex-secondary-window-minutes/, "Codex parser should read the secondary window duration");
27
27
  assert.match(parser, /windowMinutes === 10_080\) return "weekly"/, "Codex weekly windows should have a truthful compact label");
28
28
  assert.match(parser, /return fallback;/, "missing Codex durations should use neutral labels rather than guessed 5h\/7d labels");
29
- assert.match(parser, /usage\.primary\.label[\s\S]*usage\.secondary\.label/, "formatted text should use snapshot labels");
29
+ assert.match(parser, /providerUsageWindows\(usage\)[\s\S]*\.map\(\(window\)/, "formatted text should use every available snapshot window");
30
30
 
31
- assert.match(producer, /usageWindows\?:\s*\{\s*primaryPercent:\s*number;\s*secondaryPercent:\s*number;/s, "producer should type the optional usageWindows contract");
32
- assert.match(producer, /usageWindows:\s*\{\s*primaryPercent:\s*providerUsage\.primary\.usedPercent,\s*secondaryPercent:\s*providerUsage\.secondary\.usedPercent,/s, "Usage chip should publish both normalized window percentages");
33
- assert.match(app, /usage:\s*"Provider subscription usage\.[^"]*provider-reported primary and secondary rate windows\./, "Usage tooltip should explain both provider-reported windows rather than using generic fallback copy");
31
+ assert.match(producer, /usageWindows\?:\s*\{\s*primaryPercent\?:\s*number;\s*secondaryPercent\?:\s*number;/s, "producer should type each usage window as independently optional");
32
+ assert.match(producer, /providerUsage\.primary \? \{ primaryPercent: providerUsage\.primary\.usedPercent \}/, "Usage chip should publish an available primary percentage");
33
+ assert.match(producer, /providerUsage\.secondary \? \{ secondaryPercent: providerUsage\.secondary\.usedPercent \}/, "Usage chip should publish an available secondary percentage");
34
+ assert.match(app, /usage:\s*"Provider subscription usage\.[^"]*every available provider-reported rate window\./, "Usage tooltip should explain that partial provider windows remain visible");
34
35
 
35
36
  assert.match(usageNormalization, /value\.usageWindows\.primaryPercent/, "consumer should read structured primary metadata");
36
37
  assert.match(usageNormalization, /value\.usageWindows\.secondaryPercent/, "consumer should read structured secondary metadata");
37
- assert.match(usageNormalization, /Number\.isFinite\(primaryPercent\)\s*&&\s*Number\.isFinite\(secondaryPercent\)/, "consumer should require both finite window values");
38
- assert.match(usageNormalization, /chip\.usageWindows\s*=\s*\{\s*primaryPercent,\s*secondaryPercent\s*\}/, "consumer should preserve the two structured values");
38
+ assert.match(usageNormalization, /Number\.isFinite\(primaryPercent\)\s*\|\|\s*Number\.isFinite\(secondaryPercent\)/, "consumer should accept either finite window value");
39
+ assert.match(usageNormalization, /Number\.isFinite\(primaryPercent\) \? \{ primaryPercent \}/, "consumer should preserve an available primary value");
40
+ assert.match(usageNormalization, /Number\.isFinite\(secondaryPercent\) \? \{ secondaryPercent \}/, "consumer should preserve an available secondary value");
39
41
  assert.doesNotMatch(usageNormalization, /chip\.value|value\.value|5h.*match|7d.*match/s, "usage-window normalization must not parse display text");
40
42
 
41
43
  assert.match(app, /if \(chip\.usageWindows\) applyFooterUsageWindows\(node, chip\.usageWindows\);/, "initial rendering should apply Usage visuals");
42
- assert.match(applyUsage, /Math\.min\(100, Math\.max\(0, primaryPercent\)\)/, "primary visual should clamp defensively");
43
- assert.match(applyUsage, /Math\.min\(100, Math\.max\(0, secondaryPercent\)\)/, "secondary visual should clamp defensively");
44
+ assert.match(applyUsage, /Number\.isFinite\(primaryPercent\) \? Math\.min\(100, Math\.max\(0, primaryPercent\)\) : 0/, "primary visual should clamp available data and leave a missing lane empty");
45
+ assert.match(applyUsage, /Number\.isFinite\(secondaryPercent\) \? Math\.min\(100, Math\.max\(0, secondaryPercent\)\) : 0/, "secondary visual should clamp available data and leave a missing lane empty");
44
46
  assert.match(applyUsage, /--usage-primary/, "primary should have an independent CSS width variable");
45
47
  assert.match(applyUsage, /--usage-secondary/, "secondary should have an independent CSS width variable");
46
48
  assert.doesNotMatch(applyUsage, /\.value|5h.*match|7d.*match/s, "visual application must not parse display text");
@@ -0,0 +1,91 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const app = await readFile(join(root, "public", "app.js"), "utf8");
8
+
9
+ function functionBody(source, name) {
10
+ const match = new RegExp(`function\\s+${name}\\s*\\(`).exec(source);
11
+ assert.ok(match, `${name} should be defined`);
12
+ let parens = 0;
13
+ let open = -1;
14
+ for (let index = match.index + match[0].length - 1; index < source.length; index += 1) {
15
+ if (source[index] === "(") parens += 1;
16
+ else if (source[index] === ")") parens -= 1;
17
+ else if (source[index] === "{" && parens === 0) {
18
+ open = index;
19
+ break;
20
+ }
21
+ }
22
+ assert.notEqual(open, -1, `${name} should open`);
23
+ let depth = 0;
24
+ for (let index = open; index < source.length; index += 1) {
25
+ if (source[index] === "{") depth += 1;
26
+ else if (source[index] === "}" && --depth === 0) return source.slice(open + 1, index);
27
+ }
28
+ assert.fail(`${name} should close`);
29
+ }
30
+
31
+ assert.match(app, /import \{ classifyTranscriptStreamEvent, createStreamOutputController \} from "\.\/stream-output-controller\.mjs";/);
32
+ assert.match(app, /let foregroundTranscriptCatchUpRequired = document\.visibilityState === "hidden";/);
33
+
34
+ const beginCatchUp = functionBody(app, "beginForegroundTranscriptCatchUp");
35
+ assert.match(beginCatchUp, /foregroundTranscriptCatchUpRequired = true/);
36
+ assert.match(beginCatchUp, /streamOutputController\.cancel\(\)/, "backgrounding should discard pending frame work rather than replaying it later");
37
+ assert.match(beginCatchUp, /eventStreamPausedForBackground = true[\s\S]*?eventSource = null[\s\S]*?source\.close\(\)/, "backgrounding should close the EventSource so Chromium cannot retain and replay an SSE backlog");
38
+
39
+ const dispatch = functionBody(app, "dispatchTranscriptStreamEvent");
40
+ assert.match(dispatch, /classifyTranscriptStreamEvent\(event\)/);
41
+ assert.match(dispatch, /document\.visibilityState === "hidden" \|\| foregroundTranscriptCatchUpRequired/);
42
+ assert.ok(
43
+ dispatch.indexOf("return true;") < dispatch.indexOf("streamOutputController.dispatch(event"),
44
+ "hidden transcript updates should be consumed without entering DOM render queues",
45
+ );
46
+
47
+ const reconcile = functionBody(app, "reconcileForegroundState");
48
+ const authoritativeRefresh = reconcile.indexOf("refreshMessages(tabContext, { authoritative: true })");
49
+ const resumeLiveRendering = reconcile.indexOf("foregroundTranscriptCatchUpRequired = false");
50
+ const resumeEventStream = reconcile.indexOf("ensureActiveEventStream(tabContext)");
51
+ const supplementalRefresh = reconcile.indexOf("scheduleForegroundSupplementalRefresh(tabContext)");
52
+ assert.ok(authoritativeRefresh >= 0, "foreground catch-up should fetch one authoritative transcript snapshot");
53
+ assert.ok(authoritativeRefresh < resumeLiveRendering, "live transcript rendering must resume only after the authoritative snapshot settles");
54
+ assert.ok(resumeLiveRendering < resumeEventStream, "the event stream must reconnect only after authoritative transcript rendering resumes");
55
+ assert.ok(resumeEventStream < supplementalRefresh, "nonessential refresh work should be staged after transcript catch-up");
56
+ assert.match(reconcile, /backgroundReconnectSnapshotFresh = !\[\.\.\.tabResult, \.\.\.criticalResults\]\.some/, "a failed snapshot must not suppress reconnect recovery");
57
+
58
+ const supplemental = functionBody(app, "scheduleForegroundSupplementalRefresh");
59
+ assert.match(supplemental, /requestIdleCallback\(run, \{ timeout: 1_200 \}\)/, "supplemental panels should refresh during idle time when supported");
60
+ assert.match(supplemental, /setTimeout\(run, 250\)/, "browsers without idle callbacks should still yield before supplemental refreshes");
61
+
62
+ assert.doesNotMatch(app, /window\.addEventListener\("blur", beginForegroundTranscriptCatchUp\)/, "a visible but unfocused window must keep live streaming");
63
+ assert.match(
64
+ app,
65
+ /document\.addEventListener\("visibilitychange"[\s\S]*?beginForegroundTranscriptCatchUp\(\)[\s\S]*?mobileConnectionState = "away"/,
66
+ "the hidden transition should enter catch-up mode before background state rendering",
67
+ );
68
+ assert.match(app, /case "webui_connected":[\s\S]*?resumedWithFreshSnapshot[\s\S]*?if \(!resumedWithFreshSnapshot\) scheduleForegroundReconcile/, "the deliberate reconnect must not immediately trigger a second full refresh");
69
+ assert.match(app, /case "webui_supervisor_reconnected":[\s\S]*?foregroundReconnectSnapshotFreshUntil/, "initial supervisor replay must reuse the fresh foreground snapshot");
70
+
71
+ const executeBeginCatchUp = new Function("eventSource", "streamOutputController", `
72
+ let foregroundTranscriptCatchUpRequired = false;
73
+ let backgroundReconnectSnapshotFresh = true;
74
+ let eventStreamPausedForBackground = false;
75
+ ${beginCatchUp}
76
+ return { foregroundTranscriptCatchUpRequired, backgroundReconnectSnapshotFresh, eventStreamPausedForBackground, eventSource };
77
+ `);
78
+ let closeCount = 0;
79
+ let cancelCount = 0;
80
+ const pausedState = executeBeginCatchUp(
81
+ { close() { closeCount += 1; } },
82
+ { cancel() { cancelCount += 1; } },
83
+ );
84
+ assert.equal(cancelCount, 1, "backgrounding should cancel pending transcript work exactly once");
85
+ assert.equal(closeCount, 1, "backgrounding should close the active EventSource exactly once");
86
+ assert.equal(pausedState.eventSource, null, "the closed EventSource must be detached so no queued message handler remains current");
87
+ assert.equal(pausedState.eventStreamPausedForBackground, true);
88
+ assert.equal(pausedState.backgroundReconnectSnapshotFresh, false);
89
+ assert.equal(pausedState.foregroundTranscriptCatchUpRequired, true);
90
+
91
+ console.log("foreground-transcript-catch-up-static.test.mjs passed");
@@ -2679,6 +2679,35 @@ try {
2679
2679
  assert.equal(stashDrop.body?.ok, true, "confirmed stash drop should succeed");
2680
2680
  assert.equal(stashDrop.body?.data?.stashes?.length, 0, "dropping the only stash should empty the list");
2681
2681
 
2682
+ // Both footer Sync and Guided Git use this push endpoint. Even when a
2683
+ // feature branch mistakenly tracks origin/main, push its current HEAD to
2684
+ // the same-named remote branch without changing remote main.
2685
+ const mismatchedPushBranch = "feature/current-branch-push";
2686
+ const remoteMainBeforeCurrentBranchPush = runGitFixture(["rev-parse", "refs/heads/main"], remoteBare, "current-branch push fixture should record remote main");
2687
+ runGitFixture(["switch", "-c", mismatchedPushBranch], localRepo, "current-branch push fixture should create its feature branch");
2688
+ runGitFixture(["config", `branch.${mismatchedPushBranch}.remote`, "origin"], localRepo, "current-branch push fixture should configure the upstream remote");
2689
+ runGitFixture(["config", `branch.${mismatchedPushBranch}.merge`, "refs/heads/main"], localRepo, "current-branch push fixture should reproduce the mismatched upstream branch");
2690
+ await writeFile(path.join(localRepo, "current-branch-push.txt"), "feature branch only\n");
2691
+ runGitFixture(["add", "current-branch-push.txt"], localRepo, "current-branch push fixture should stage its marker");
2692
+ runGitFixture(["commit", "-m", "current branch push fixture"], localRepo, "current-branch push fixture should commit its marker");
2693
+ const currentBranchHead = runGitFixture(["rev-parse", "HEAD"], localRepo, "current-branch push fixture should record feature HEAD");
2694
+
2695
+ const pushCurrentBranch = await request("127.0.0.1", "/api/git-workflow/push", { method: "POST", body: { tab: remoteTabId }, timeoutMs: 30_000 });
2696
+ assert.equal(pushCurrentBranch.body?.ok, true, `push should target the checked-out branch despite a mismatched upstream: ${pushCurrentBranch.body?.error || ""}`);
2697
+ assert.equal(pushCurrentBranch.body?.data?.branch, mismatchedPushBranch);
2698
+ assert.equal(pushCurrentBranch.body?.data?.remote, "origin");
2699
+ assert.equal(runGitFixture(["rev-parse", `refs/heads/${mismatchedPushBranch}`], remoteBare, "current-branch push fixture should create the same-named remote branch"), currentBranchHead);
2700
+ assert.equal(runGitFixture(["rev-parse", "refs/heads/main"], remoteBare, "current-branch push fixture should leave remote main unchanged"), remoteMainBeforeCurrentBranchPush);
2701
+ assert.equal(
2702
+ runGitFixture(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], localRepo, "current-branch push fixture should read the repaired upstream"),
2703
+ `origin/${mismatchedPushBranch}`,
2704
+ "push should replace origin/main tracking with the same-named remote feature branch",
2705
+ );
2706
+ const currentBranchStatus = runGitFixture(["status", "--porcelain=v2", "--branch"], localRepo, "current-branch push fixture should read synchronized status");
2707
+ assert.match(currentBranchStatus, new RegExp(`^# branch\\.upstream origin/${mismatchedPushBranch}$`, "m"));
2708
+ assert.match(currentBranchStatus, /^# branch\.ab \+0 -0$/m, "the repaired upstream should leave no phantom outgoing Sync count");
2709
+ runGitFixture(["switch", "main"], localRepo, "current-branch push fixture should restore main");
2710
+
2682
2711
  // Fetch, divergence classification, integrate, push classification
2683
2712
  await writeFile(path.join(remoteWork, "incoming.txt"), "base\nremote one\nremote two\nremote three\n");
2684
2713
  runGitFixture(["commit", "-am", "remote three"], remoteWork, "remote worktree should commit third incoming change");