@firstpick/pi-package-webui 0.8.0 → 0.8.2

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 (63) hide show
  1. package/README.md +34 -5
  2. package/bin/pi-webui.mjs +606 -102
  3. package/lib/component-update-state.mjs +126 -0
  4. package/lib/npm-command.mjs +81 -0
  5. package/lib/queue-mutation.mjs +6 -0
  6. package/lib/trust-boundaries.mjs +1 -0
  7. package/lib/workspace-files-live-watcher.mjs +138 -0
  8. package/package.json +8 -3
  9. package/public/app.js +4231 -376
  10. package/public/index.html +265 -52
  11. package/public/mobile-shell-state.mjs +166 -0
  12. package/public/service-worker.js +60 -13
  13. package/public/styles.css +1790 -383
  14. package/public/subagent-gate-visibility.mjs +16 -0
  15. package/public/subagent-launch-slot-state.mjs +16 -0
  16. package/public/transcript-renderer.mjs +433 -0
  17. package/tests/boot-failure-diagnostics.test.mjs +63 -5
  18. package/tests/browser/control-deck-component-updates.spec.mjs +180 -0
  19. package/tests/browser/interaction-continuity.spec.mjs +897 -0
  20. package/tests/browser/mobile-foundation.spec.mjs +363 -0
  21. package/tests/browser/optimistic-prompt.spec.mjs +130 -0
  22. package/tests/browser/side-panel-section-reorder.spec.mjs +101 -0
  23. package/tests/browser/stats-overlay.spec.mjs +265 -0
  24. package/tests/chat-scroll-intent-static.test.mjs +6 -1
  25. package/tests/codex-fast-mode-static.test.mjs +8 -5
  26. package/tests/compact-sections-static.test.mjs +20 -2
  27. package/tests/compaction-mutation-contract.test.mjs +18 -4
  28. package/tests/compaction-static.test.mjs +1 -0
  29. package/tests/completion-signal-contract.test.mjs +13 -2
  30. package/tests/component-update-api-static.test.mjs +67 -0
  31. package/tests/component-update-state.test.mjs +80 -0
  32. package/tests/control-deck-component-updates-static.test.mjs +251 -0
  33. package/tests/fast-mode-client-static.test.mjs +7 -4
  34. package/tests/fixtures/fake-pi.mjs +305 -2
  35. package/tests/footer-provider-usage-visual-static.test.mjs +71 -0
  36. package/tests/git-panel-gitignore-static.test.mjs +104 -0
  37. package/tests/http-endpoints-harness.test.mjs +228 -2
  38. package/tests/interaction-state-stability-static.test.mjs +271 -0
  39. package/tests/mobile-continuity-tablet-static.test.mjs +55 -0
  40. package/tests/mobile-foundation-static.test.mjs +71 -0
  41. package/tests/mobile-phone-experience-static.test.mjs +65 -0
  42. package/tests/mobile-shell-state.test.mjs +69 -0
  43. package/tests/mobile-static.test.mjs +246 -39
  44. package/tests/mobile-transcript-cache-characterization.test.mjs +34 -0
  45. package/tests/native-parity-harness.test.mjs +2 -0
  46. package/tests/npm-command.test.mjs +64 -1
  47. package/tests/open-issue-wizard-static.test.mjs +2 -1
  48. package/tests/queue-edit-reorder-static.test.mjs +9 -1
  49. package/tests/queue-mutation-contract.test.mjs +22 -0
  50. package/tests/service-worker-lifecycle.test.mjs +120 -0
  51. package/tests/side-panel-section-reorder-static.test.mjs +68 -0
  52. package/tests/sse-backpressure-harness.test.mjs +137 -0
  53. package/tests/stats-dashboard-static.test.mjs +266 -0
  54. package/tests/streaming-ui-coupling.test.mjs +7 -1
  55. package/tests/subagent-gate-visibility.test.mjs +18 -2
  56. package/tests/subagent-launch-slot-state.test.mjs +32 -0
  57. package/tests/subagent-launch-slots-static.test.mjs +8 -2
  58. package/tests/subagents-helper.test.mjs +90 -0
  59. package/tests/terminal-tab-workspace-static.test.mjs +1 -1
  60. package/tests/update-commands.test.mjs +4 -0
  61. package/tests/workspace-files-live-updates-static.test.mjs +76 -0
  62. package/tests/workspace-files-live-watcher.test.mjs +95 -0
  63. package/webui-rpc-helper.mjs +175 -3
@@ -0,0 +1,897 @@
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
+ async function api(page, pathname, { method = "GET", data } = {}) {
29
+ const response = await page.request.fetch(`${baseURL}${pathname}`, {
30
+ method,
31
+ data,
32
+ headers: data === undefined ? undefined : { "content-type": "application/json" },
33
+ });
34
+ const payload = await response.json().catch(() => ({}));
35
+ assert.equal(response.ok(), true, `${method} ${pathname} should succeed: ${payload.error || output}`);
36
+ return payload;
37
+ }
38
+
39
+ async function tabIds(page) {
40
+ const payload = await api(page, "/api/tabs");
41
+ return payload.data?.tabs?.map((tab) => tab.id) || [];
42
+ }
43
+
44
+ async function activeTabId(page) {
45
+ return page.locator("#tabBar [role=\"tab\"][aria-selected=\"true\"]").evaluate((node) => node.closest("[data-tab-id]")?.dataset.tabId || "");
46
+ }
47
+
48
+ async function startContinuityRunner(page) {
49
+ const tabId = await activeTabId(page) || (await tabIds(page))[0];
50
+ const configured = await api(page, "/api/app-runner-config", {
51
+ method: "POST",
52
+ data: {
53
+ tab: tabId,
54
+ runner: { label: "Continuity runner", command: process.execPath, path: "continuity-runner.mjs" },
55
+ },
56
+ });
57
+ assert.ok(configured.data?.runners?.some((runner) => runner.label === "Continuity runner"), "continuity runner should be available through the public app-runner API");
58
+
59
+ await page.locator("#appRunnerMenuButton").click();
60
+ const runner = page.getByRole("menuitem", { name: /Continuity runner/ });
61
+ await expect(runner).toBeVisible();
62
+ await runner.click();
63
+ await expect(page.locator(".app-runner-stdin-input")).toBeVisible();
64
+ }
65
+
66
+ async function triggerDelayedStream(page, tabId = "") {
67
+ const targetTabId = tabId || await activeTabId(page);
68
+ assert.ok(targetTabId, "a visible active terminal tab is required for the delayed stream fixture");
69
+ const beforeLength = (await page.locator("#chat").textContent() || "").length;
70
+ await api(page, `/api/prompt?tab=${encodeURIComponent(targetTabId)}`, {
71
+ method: "POST",
72
+ data: { message: "fixture continuity delayed stream", requestId: `continuity-${Date.now()}-${Math.random().toString(36).slice(2)}` },
73
+ });
74
+ await expect.poll(async () => ((await page.locator("#chat").textContent() || "").length > beforeLength)).toBe(true);
75
+ }
76
+
77
+ async function triggerTranscriptContinuity(page, scenario, tabId = "") {
78
+ const targetTabId = tabId || await activeTabId(page);
79
+ assert.ok(targetTabId, `an active terminal tab is required for the ${scenario} fixture`);
80
+ await api(page, `/api/prompt?tab=${encodeURIComponent(targetTabId)}`, {
81
+ method: "POST",
82
+ data: { message: `fixture transcript continuity ${scenario}`, requestId: `transcript-${scenario}-${Date.now()}-${Math.random().toString(36).slice(2)}` },
83
+ });
84
+ }
85
+
86
+ async function waitForFixtureSettlement(page, tabId = "") {
87
+ const targetTabId = tabId || await activeTabId(page);
88
+ await expect.poll(async () => (await api(page, `/api/state?tab=${encodeURIComponent(targetTabId)}`)).data?.isStreaming === false).toBe(true);
89
+ }
90
+
91
+ async function selectRenderedText(locator, expected, { backward = false } = {}) {
92
+ return locator.evaluate((root, { text, backwardSelection }) => {
93
+ const fullText = root.textContent || "";
94
+ const start = fullText.indexOf(text);
95
+ if (start < 0) return { text: "", anchorOffset: -1, focusOffset: -1 };
96
+ const point = (targetOffset) => {
97
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
98
+ let consumed = 0;
99
+ let last = null;
100
+ while (walker.nextNode()) {
101
+ const node = walker.currentNode;
102
+ const next = consumed + node.data.length;
103
+ if (targetOffset < next) return { node, offset: targetOffset - consumed };
104
+ consumed = next;
105
+ last = node;
106
+ }
107
+ return last ? { node: last, offset: last.data.length } : { node: root, offset: root.childNodes.length };
108
+ };
109
+ const offsetFromRoot = (node, offset) => {
110
+ const range = document.createRange();
111
+ range.selectNodeContents(root);
112
+ range.setEnd(node, offset);
113
+ return range.toString().length;
114
+ };
115
+ const from = point(start);
116
+ const to = point(start + text.length);
117
+ const selection = window.getSelection();
118
+ selection.removeAllRanges();
119
+ if (backwardSelection && typeof selection.setBaseAndExtent === "function") {
120
+ selection.setBaseAndExtent(to.node, to.offset, from.node, from.offset);
121
+ } else {
122
+ const range = document.createRange();
123
+ range.setStart(from.node, from.offset);
124
+ range.setEnd(to.node, to.offset);
125
+ selection.addRange(range);
126
+ }
127
+ return {
128
+ text: selection.toString(),
129
+ anchorOffset: offsetFromRoot(selection.anchorNode, selection.anchorOffset),
130
+ focusOffset: offsetFromRoot(selection.focusNode, selection.focusOffset),
131
+ };
132
+ }, { text: expected, backwardSelection: backward });
133
+ }
134
+
135
+ async function textRangeBox(locator, expected) {
136
+ return locator.evaluate((root, text) => {
137
+ const fullText = root.textContent || "";
138
+ const start = fullText.indexOf(text);
139
+ if (start < 0) return null;
140
+ const point = (targetOffset) => {
141
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
142
+ let consumed = 0;
143
+ let last = null;
144
+ while (walker.nextNode()) {
145
+ const node = walker.currentNode;
146
+ const next = consumed + node.data.length;
147
+ if (targetOffset < next) return { node, offset: targetOffset - consumed };
148
+ consumed = next;
149
+ last = node;
150
+ }
151
+ return last ? { node: last, offset: last.data.length } : null;
152
+ };
153
+ const from = point(start);
154
+ const to = point(start + text.length);
155
+ if (!from || !to) return null;
156
+ const range = document.createRange();
157
+ range.setStart(from.node, from.offset);
158
+ range.setEnd(to.node, to.offset);
159
+ const box = range.getBoundingClientRect();
160
+ return box.width > 0 && box.height > 0 ? { left: box.left, right: box.right, top: box.top, bottom: box.bottom } : null;
161
+ }, expected);
162
+ }
163
+
164
+ test.beforeAll(async () => {
165
+ const port = await freePort();
166
+ tempRoot = await mkdtemp(join(tmpdir(), "pi-webui-interaction-continuity-"));
167
+ await writeFile(join(tempRoot, "continuity-runner.mjs"), [
168
+ "let line = 0;",
169
+ "for (let index = 0; index < 30; index += 1) console.log(`continuity output ${++line} ${'x'.repeat(120)}`);",
170
+ "setInterval(() => console.log(`continuity output ${++line} ${'x'.repeat(120)}`), 500);",
171
+ "process.stdin.on('data', () => {});",
172
+ "",
173
+ ].join("\n"));
174
+ baseURL = `http://127.0.0.1:${port}`;
175
+ child = spawn(process.execPath, [serverScript, "--cwd", tempRoot, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
176
+ stdio: ["ignore", "pipe", "pipe"],
177
+ env: {
178
+ ...process.env,
179
+ PI_WEBUI_RPC_SUPERVISOR: "0",
180
+ PI_CODING_AGENT_DIR: join(tempRoot, "agent"),
181
+ PI_WEBUI_SETTINGS_FILE: join(tempRoot, "settings.json"),
182
+ FAKE_PI_CONTINUITY_MODE: "1",
183
+ },
184
+ });
185
+ child.stdout.on("data", (chunk) => { output += String(chunk); });
186
+ child.stderr.on("data", (chunk) => { output += String(chunk); });
187
+ for (let attempt = 0; attempt < 80; attempt += 1) {
188
+ if (child.exitCode !== null) break;
189
+ try {
190
+ const response = await fetch(`${baseURL}/api/health`, { signal: AbortSignal.timeout(500) });
191
+ if (response.ok) return;
192
+ } catch {
193
+ // Poll only until the real server and fake Pi fixture are available.
194
+ }
195
+ await delay(100);
196
+ }
197
+ throw new Error(`Pi Web UI did not start:\n${output}`);
198
+ });
199
+
200
+ test.afterAll(async () => {
201
+ if (child?.exitCode === null) {
202
+ await fetch(`${baseURL}/api/shutdown`, { method: "POST", signal: AbortSignal.timeout(1_000) }).catch(() => undefined);
203
+ await new Promise((resolve) => child.once("exit", resolve));
204
+ }
205
+ await rm(tempRoot, { recursive: true, force: true });
206
+ });
207
+
208
+ test("same-context app-runner refresh preserves directional selection, control scroll, and reader scroll mode", async ({ page }) => {
209
+ await page.setViewportSize({ width: 1280, height: 800 });
210
+ await page.goto(baseURL);
211
+ await startContinuityRunner(page);
212
+
213
+ const input = page.locator(".app-runner-stdin-input");
214
+ const draft = Array.from({ length: 24 }, (_, index) => `draft line ${index} ${"q".repeat(90)}`).join("\n");
215
+ await input.fill(draft);
216
+ await input.focus();
217
+ await page.keyboard.press("Control+End");
218
+ for (let index = 0; index < 12; index += 1) await page.keyboard.press("Shift+ArrowLeft");
219
+ const before = await input.evaluate((node) => {
220
+ node.scrollTop = 32;
221
+ node.dispatchEvent(new Event("scroll"));
222
+ return {
223
+ value: node.value,
224
+ selectionStart: node.selectionStart,
225
+ selectionEnd: node.selectionEnd,
226
+ selectionDirection: node.selectionDirection,
227
+ scrollTop: node.scrollTop,
228
+ scrollHeight: node.scrollHeight,
229
+ clientHeight: node.clientHeight,
230
+ };
231
+ });
232
+ assert.ok(before.scrollTop > 0, `the text-control fixture needs a real nonzero scroll position before the live rerender: ${JSON.stringify(before)}`);
233
+
234
+ const terminal = page.locator(".app-runner-widget .release-npm-terminal");
235
+ const initialOutputLines = await terminal.locator(".release-npm-line").count();
236
+ await expect.poll(async () => terminal.locator(".release-npm-line").count()).toBeGreaterThan(initialOutputLines);
237
+ await expect(input).toBeFocused();
238
+ await expect.poll(() => input.evaluate((node) => ({
239
+ value: node.value,
240
+ selectionStart: node.selectionStart,
241
+ selectionEnd: node.selectionEnd,
242
+ selectionDirection: node.selectionDirection,
243
+ scrollTop: node.scrollTop,
244
+ }))).toEqual({
245
+ value: before.value,
246
+ selectionStart: before.selectionStart,
247
+ selectionEnd: before.selectionEnd,
248
+ selectionDirection: before.selectionDirection,
249
+ scrollTop: before.scrollTop,
250
+ });
251
+
252
+ let readerState = null;
253
+ await expect.poll(async () => {
254
+ const candidate = await terminal.evaluate((node) => {
255
+ const maxScrollTop = Math.max(0, node.scrollHeight - node.clientHeight);
256
+ if (maxScrollTop <= 120) return { scrollTop: 0, key: node.dataset.continuityScrollKey || "" };
257
+ node.dispatchEvent(new WheelEvent("wheel", { deltaY: -80 }));
258
+ node.scrollTop = Math.max(1, maxScrollTop - 80);
259
+ node.dispatchEvent(new Event("scroll"));
260
+ return { scrollTop: node.scrollTop, key: node.dataset.continuityScrollKey || "" };
261
+ });
262
+ if (candidate.scrollTop > 0) readerState = candidate;
263
+ return candidate.scrollTop;
264
+ }).toBeGreaterThan(0);
265
+ const readerScrollTop = readerState.scrollTop;
266
+ await input.fill("position update");
267
+ await page.getByRole("button", { name: "Send input", exact: true }).click();
268
+ await expect.poll(async () => (await terminal.textContent() || "").includes("# stdin sent (15 chars)")).toBe(true);
269
+ await expect.poll(() => terminal.evaluate((node, expected) => Math.abs(node.scrollTop - expected) <= 1, readerScrollTop)).toBe(true);
270
+
271
+ await terminal.evaluate((node) => {
272
+ node.dispatchEvent(new WheelEvent("wheel", { deltaY: 80 }));
273
+ node.scrollTop = node.scrollHeight;
274
+ node.dispatchEvent(new Event("scroll"));
275
+ });
276
+ await input.fill("follow update");
277
+ await page.getByRole("button", { name: "Send input", exact: true }).click();
278
+ await expect.poll(async () => (await terminal.textContent() || "").includes("# stdin sent (13 chars)")).toBe(true);
279
+ await expect.poll(() => terminal.evaluate((node) => Math.abs(node.scrollHeight - node.clientHeight - node.scrollTop) <= 1)).toBe(true);
280
+ const runnerTabId = await activeTabId(page);
281
+ await api(page, "/api/tabs", { method: "POST", data: {} });
282
+ await api(page, `/api/tabs/${encodeURIComponent(runnerTabId)}`, { method: "DELETE" });
283
+ await expect.poll(async () => (await tabIds(page)).length).toBe(1);
284
+ });
285
+
286
+ test("main output text selection survives streaming-tail and settlement rerenders", async ({ page }) => {
287
+ await page.setViewportSize({ width: 1280, height: 800 });
288
+ await page.goto(baseURL);
289
+ const tabId = await activeTabId(page) || (await tabIds(page))[0];
290
+ await api(page, `/api/prompt?tab=${encodeURIComponent(tabId)}`, {
291
+ method: "POST",
292
+ data: { message: "fixture continuity delayed stream", requestId: `selection-${Date.now()}` },
293
+ });
294
+
295
+ const streamingOutput = page.locator(".message.assistant.streaming .streaming-markdown").last();
296
+ await expect(streamingOutput).toContainText("continuity stream");
297
+ const selectedText = "continuity stream";
298
+ assert.equal((await selectRenderedText(streamingOutput, selectedText)).text, selectedText, "the fixture must create a real browser Range inside the streaming main output");
299
+ const originalSurface = await streamingOutput.elementHandle();
300
+ const originalBubble = await streamingOutput.evaluateHandle((node) => node.closest(".message"));
301
+ assert.ok(originalSurface && originalBubble, "the streaming selection needs inspectable source surface and bubble nodes");
302
+
303
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(selectedText);
304
+ await expect(page.locator(".message.assistant:not(.streaming)").last()).toContainText("continuity stream complete");
305
+ await expect.poll(() => originalSurface.evaluate((node) => node.isConnected), { timeout: 8_000 }).toBe(true);
306
+ await expect.poll(() => originalBubble.evaluate((node) => ({ connected: node.isConnected, streaming: node.classList.contains("streaming"), itemKey: node.dataset.itemKey, messageKey: node.dataset.transcriptMessageKey })), { timeout: 8_000 }).toEqual({ connected: true, streaming: false, itemKey: "m:4", messageKey: "m:4" });
307
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || ""), { timeout: 8_000 }).toBe(selectedText);
308
+ await waitForFixtureSettlement(page, tabId);
309
+ await delay(4_000);
310
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(selectedText);
311
+ });
312
+
313
+ test("backward normal-output selection keeps its direction through streaming and exact settlement", async ({ page }) => {
314
+ await page.setViewportSize({ width: 1280, height: 800 });
315
+ await page.goto(baseURL);
316
+ await triggerTranscriptContinuity(page, "reverse");
317
+
318
+ const output = page.locator(".message.assistant.streaming .streaming-markdown").last();
319
+ const selectedText = "backward selection literal";
320
+ await expect(output).toContainText(selectedText);
321
+ const selection = await selectRenderedText(output, selectedText, { backward: true });
322
+ assert.equal(selection.text, selectedText, "the browser should create a backward main-output Range");
323
+ assert.ok(selection.anchorOffset > selection.focusOffset, `the fixture requires a backward selection: ${JSON.stringify(selection)}`);
324
+ const originalSurface = await output.elementHandle();
325
+ assert.ok(originalSurface, "the backward Range needs an inspectable streaming surface");
326
+
327
+ await expect(output).toContainText("survives");
328
+ await expect.poll(() => originalSurface.evaluate((node) => node.isConnected)).toBe(true);
329
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(selectedText);
330
+ await waitForFixtureSettlement(page);
331
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(selectedText);
332
+ await expect.poll(() => page.evaluate(() => {
333
+ const selection = window.getSelection();
334
+ const root = document.querySelector(".message.assistant:not(.streaming) .streaming-markdown:last-child");
335
+ if (!selection || !root || !selection.anchorNode || !selection.focusNode) return false;
336
+ const offset = (node, value) => {
337
+ const range = document.createRange();
338
+ range.selectNodeContents(root);
339
+ range.setEnd(node, value);
340
+ return range.toString().length;
341
+ };
342
+ return offset(selection.anchorNode, selection.anchorOffset) > offset(selection.focusNode, selection.focusOffset);
343
+ })).toBe(true);
344
+ });
345
+
346
+ test("duplicate assistant text remains selected in its original keyed bubble during suffix reconciliation", async ({ page }) => {
347
+ await page.setViewportSize({ width: 1280, height: 800 });
348
+ await page.goto(baseURL);
349
+ const text = "duplicate keyed selection literal";
350
+ await triggerTranscriptContinuity(page, "duplicate");
351
+ const bubbles = page.locator(".message.assistant:not(.streaming)", { hasText: text });
352
+ await expect.poll(() => bubbles.count()).toBeGreaterThan(0);
353
+ await waitForFixtureSettlement(page);
354
+ const originalBubble = bubbles.last();
355
+ const originalSurface = originalBubble.locator(".streaming-markdown");
356
+ const beforeCount = await bubbles.count();
357
+ const key = await originalBubble.getAttribute("data-transcript-message-key");
358
+ assert.ok(key, "duplicate text needs a semantic message key before suffix reconciliation");
359
+ assert.equal((await selectRenderedText(originalSurface, text)).text, text);
360
+ const originalHandle = await originalBubble.elementHandle();
361
+ assert.ok(originalHandle, "the original duplicate-text bubble needs an inspectable DOM identity");
362
+
363
+ await triggerTranscriptContinuity(page, "duplicate");
364
+ await expect.poll(() => bubbles.count()).toBeGreaterThan(beforeCount);
365
+ await expect.poll(() => originalHandle.evaluate((node, expectedKey) => node.isConnected && node.dataset.transcriptMessageKey === expectedKey, key)).toBe(true);
366
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(text);
367
+ await waitForFixtureSettlement(page);
368
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(text);
369
+ });
370
+
371
+ test("real pointer drag keeps the selected tail nodes connected until the drag ends", async ({ page }) => {
372
+ await page.setViewportSize({ width: 1280, height: 800 });
373
+ await page.goto(baseURL);
374
+ const previousTabId = await activeTabId(page);
375
+ const created = await api(page, "/api/tabs", { method: "POST", data: {} });
376
+ const pointerTabId = created.data?.tab?.id;
377
+ assert.ok(pointerTabId, "pointer fixture requires an isolated replacement terminal tab");
378
+ await api(page, `/api/tabs/${encodeURIComponent(previousTabId)}`, { method: "DELETE" });
379
+ await expect.poll(async () => (await tabIds(page)).length).toBe(1);
380
+ await page.reload();
381
+ await expect.poll(() => activeTabId(page)).toBe(pointerTabId);
382
+ await triggerTranscriptContinuity(page, "pointer", pointerTabId);
383
+
384
+ const output = page.locator(".message.assistant.streaming .streaming-markdown").last();
385
+ const selectedText = "pointer drag selection literal";
386
+ await expect(output).toContainText(selectedText);
387
+ const outputHandle = await output.elementHandle();
388
+ assert.ok(outputHandle, "the pointer-drag fixture requires an inspectable streaming surface");
389
+ await output.scrollIntoViewIfNeeded();
390
+ const box = await textRangeBox(output, selectedText);
391
+ assert.ok(box, "the pointer-drag fixture needs visible text geometry");
392
+ await page.mouse.move(box.left + 2, (box.top + box.bottom) / 2);
393
+ await page.mouse.down();
394
+ try {
395
+ await page.mouse.move(box.right - 2, (box.top + box.bottom) / 2, { steps: 12 });
396
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toContain("pointer drag selection");
397
+ const anchor = await page.evaluateHandle(() => window.getSelection()?.anchorNode || null);
398
+ const focus = await page.evaluateHandle(() => window.getSelection()?.focusNode || null);
399
+ // The fixture sends its next destructive tail update while this native pointer gesture is held.
400
+ await delay(1_100);
401
+ await expect.poll(() => anchor.evaluate((node) => node?.isConnected === true)).toBe(true);
402
+ await expect.poll(() => focus.evaluate((node) => node?.isConnected === true)).toBe(true);
403
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toContain("pointer drag selection");
404
+ } finally {
405
+ // Release outside #chat to prove the window-level gesture cleanup flushes
406
+ // deferred transcript work instead of wedging the live renderer.
407
+ await page.mouse.move(12, 790);
408
+ await page.mouse.up();
409
+ }
410
+ await expect.poll(() => outputHandle.evaluate((node) => node.isConnected && node.textContent?.includes("remains after update") === true)).toBe(true);
411
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toContain("pointer drag selection");
412
+ await waitForFixtureSettlement(page, pointerTabId);
413
+ });
414
+
415
+ test("streaming thinking selection survives a later thinking delta", async ({ page }) => {
416
+ await page.setViewportSize({ width: 1280, height: 800 });
417
+ await page.goto(baseURL);
418
+ await triggerTranscriptContinuity(page, "thinking");
419
+
420
+ const thinking = page.locator(".message.thinking.streaming .thinking-text").last();
421
+ const selectedText = "thinking selection literal";
422
+ await expect(thinking).toContainText(selectedText);
423
+ assert.equal((await selectRenderedText(thinking, selectedText)).text, selectedText);
424
+ const originalSurface = await thinking.elementHandle();
425
+ assert.ok(originalSurface, "thinking continuity needs an inspectable streaming surface");
426
+ await expect(thinking).toContainText("survives");
427
+ await expect.poll(() => originalSurface.evaluate((node) => node.isConnected)).toBe(true);
428
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(selectedText);
429
+ await waitForFixtureSettlement(page);
430
+ await expect.poll(() => originalSurface.evaluate((node) => node.isConnected)).toBe(false);
431
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe("");
432
+ });
433
+
434
+ test("thinking visibility change explicitly invalidates a live thinking selection", async ({ page }) => {
435
+ await page.setViewportSize({ width: 1280, height: 800 });
436
+ await page.goto(baseURL);
437
+ await triggerTranscriptContinuity(page, "thinking");
438
+ const thinking = page.locator(".message.thinking.streaming .thinking-text").last();
439
+ const selectedText = "thinking selection literal";
440
+ await expect(thinking).toContainText(selectedText);
441
+ assert.equal((await selectRenderedText(thinking, selectedText)).text, selectedText);
442
+ const originalSurface = await thinking.elementHandle();
443
+ try {
444
+ await page.keyboard.press("Control+t");
445
+ await expect(page.locator("#thinkingVisibilityToggle")).not.toBeChecked();
446
+ await expect.poll(() => originalSurface.evaluate((node) => node.isConnected)).toBe(false);
447
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe("");
448
+ } finally {
449
+ if (!(await page.locator("#thinkingVisibilityToggle").isChecked())) await page.keyboard.press("Control+t");
450
+ await expect(page.locator("#thinkingVisibilityToggle")).toBeChecked();
451
+ await waitForFixtureSettlement(page);
452
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe("");
453
+ }
454
+ });
455
+
456
+ test("selectable live tool output restores an unchanged range across body reconciliation", async ({ page }) => {
457
+ await page.setViewportSize({ width: 1280, height: 800 });
458
+ await page.goto(baseURL);
459
+ await triggerTranscriptContinuity(page, "tool");
460
+
461
+ const toolBody = page.locator(".message.toolExecution .message-body").last();
462
+ const selectedText = "tool selection literal";
463
+ await expect(toolBody).toContainText("unselected revision one");
464
+ await toolBody.locator(".tool-output-details").evaluate((node) => { node.open = true; });
465
+ assert.equal((await selectRenderedText(toolBody, selectedText)).text, selectedText);
466
+ const bodyHandle = await toolBody.elementHandle();
467
+ assert.ok(bodyHandle, "tool selection continuity needs an inspectable semantic surface");
468
+ await expect(toolBody).toContainText("unselected revision two");
469
+ await expect.poll(() => bodyHandle.evaluate((node) => node.isConnected)).toBe(true);
470
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(selectedText);
471
+ await waitForFixtureSettlement(page);
472
+ });
473
+
474
+ test("expanded live tool output preserves reader scroll and summary focus across updates", async ({ page }) => {
475
+ await page.setViewportSize({ width: 1280, height: 800 });
476
+ await page.goto(baseURL);
477
+ await triggerTranscriptContinuity(page, "tool");
478
+
479
+ const toolBody = page.locator(".message.toolExecution .message-body").last();
480
+ const details = toolBody.locator(".tool-output-details");
481
+ const output = details.locator(".tool-output-code");
482
+ const summary = details.locator("summary");
483
+ await expect(toolBody).toContainText("unselected revision one");
484
+ await summary.click();
485
+ const scrollState = await output.evaluate((node) => {
486
+ node.scrollTop = Math.min(180, node.scrollHeight - node.clientHeight);
487
+ return { top: node.scrollTop };
488
+ });
489
+ assert.ok(scrollState.top > 0, "the tool fixture must create vertical reader scroll");
490
+ await summary.focus();
491
+ await expect(summary).toBeFocused();
492
+
493
+ await expect(toolBody).toContainText("unselected revision two");
494
+ await expect.poll(() => details.evaluate((node) => node.open)).toBe(true);
495
+ await expect.poll(() => output.evaluate((node) => node.scrollTop)).toBe(scrollState.top);
496
+ await expect(summary).toBeFocused();
497
+ await waitForFixtureSettlement(page);
498
+ });
499
+
500
+ test("authoritative divergence clears a stale live-output selection", async ({ page }) => {
501
+ await page.setViewportSize({ width: 1280, height: 800 });
502
+ await page.goto(baseURL);
503
+ await triggerTranscriptContinuity(page, "authoritative");
504
+
505
+ const output = page.locator(".message.assistant.streaming .streaming-markdown").last();
506
+ const selectedText = "authoritative selection literal";
507
+ await expect(output).toContainText(selectedText);
508
+ assert.equal((await selectRenderedText(output, selectedText)).text, selectedText);
509
+ await expect(page.locator(".message.assistant:not(.streaming)").last()).toContainText("authoritative replacement text");
510
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe("");
511
+ await waitForFixtureSettlement(page);
512
+ });
513
+
514
+ test("high-cadence output preserves the selected committed block through burst updates and settlement", async ({ page }) => {
515
+ await page.setViewportSize({ width: 1280, height: 800 });
516
+ await page.goto(baseURL);
517
+ await triggerTranscriptContinuity(page, "cadence");
518
+
519
+ const output = page.locator(".message.assistant.streaming .streaming-markdown").last();
520
+ const selectedText = "high cadence selection literal";
521
+ await expect(output).toContainText(selectedText);
522
+ const committedBlock = output.locator('[data-transcript-block="committed"]').first();
523
+ await expect(committedBlock).toBeVisible();
524
+ const committedHandle = await committedBlock.elementHandle();
525
+ assert.ok(committedHandle, "the cadence fixture requires a committed keyed block");
526
+ assert.equal((await selectRenderedText(output, selectedText)).text, selectedText);
527
+ await expect(output).toContainText("c95");
528
+ await expect.poll(() => committedHandle.evaluate((node) => node.isConnected && node.dataset.transcriptBlock === "committed")).toBe(true);
529
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(selectedText);
530
+ await waitForFixtureSettlement(page);
531
+ await expect.poll(() => committedHandle.evaluate((node) => node.isConnected)).toBe(true);
532
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(selectedText);
533
+ });
534
+
535
+ test("30-second polling and sustained cadence preserve one committed selection", async ({ page }) => {
536
+ test.setTimeout(50_000);
537
+ await page.setViewportSize({ width: 1280, height: 800 });
538
+ await page.goto(baseURL);
539
+ await triggerTranscriptContinuity(page, "dwell");
540
+
541
+ const output = page.locator(".message.assistant.streaming .streaming-markdown").last();
542
+ const selectedText = "thirty second selection literal";
543
+ await expect(output).toContainText(selectedText);
544
+ const committedBlock = output.locator('[data-transcript-block="committed"]').first();
545
+ await expect(committedBlock).toBeVisible();
546
+ const outputHandle = await output.elementHandle();
547
+ const committedHandle = await committedBlock.elementHandle();
548
+ assert.ok(outputHandle && committedHandle, "the dwell fixture requires stable surface and committed-block identities");
549
+ assert.equal((await selectRenderedText(output, selectedText)).text, selectedText);
550
+ for (let checkpoint = 0; checkpoint < 6; checkpoint += 1) {
551
+ await delay(5_000);
552
+ await expect.poll(() => committedHandle.evaluate((node) => node.isConnected && node.dataset.transcriptBlock === "committed")).toBe(true);
553
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(selectedText);
554
+ }
555
+ await expect.poll(() => outputHandle.evaluate((node) => node.isConnected && node.textContent?.includes("d299") === true)).toBe(true);
556
+ await waitForFixtureSettlement(page);
557
+ await expect.poll(() => committedHandle.evaluate((node) => node.isConnected)).toBe(true);
558
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(selectedText);
559
+ });
560
+
561
+ test("output-mode transition explicitly invalidates the prior normal-output selection", async ({ page }) => {
562
+ await page.setViewportSize({ width: 1280, height: 800 });
563
+ await page.goto(baseURL);
564
+ await triggerTranscriptContinuity(page, "mode");
565
+ const normalOutput = page.locator(".message.assistant.streaming .streaming-markdown").last();
566
+ const selectedText = "output mode transition literal";
567
+ await expect(normalOutput).toContainText(selectedText);
568
+ assert.equal((await selectRenderedText(normalOutput, selectedText)).text, selectedText);
569
+ const originalSurface = await normalOutput.elementHandle();
570
+ await expect(page.locator(".message.compact-live-output .compact-live-text").last()).toContainText(selectedText);
571
+ await expect.poll(() => originalSurface.evaluate((node) => node.isConnected)).toBe(false);
572
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe("");
573
+ await waitForFixtureSettlement(page);
574
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe("");
575
+ });
576
+
577
+ test("Mermaid async rendering leaves selected source nodes connected", async ({ page }) => {
578
+ await page.setViewportSize({ width: 1280, height: 800 });
579
+ let delayedMermaidRequest = false;
580
+ await page.route("**/vendor/mermaid/**", async (route) => {
581
+ if (!delayedMermaidRequest) {
582
+ delayedMermaidRequest = true;
583
+ await delay(600);
584
+ }
585
+ await route.continue();
586
+ });
587
+ await page.goto(baseURL);
588
+ await triggerTranscriptContinuity(page, "mermaid");
589
+
590
+ const source = page.locator(".markdown-mermaid-source code").last();
591
+ await expect(source).toContainText("graph TD");
592
+ await source.evaluate((node) => { node.closest("details").open = true; });
593
+ assert.equal((await selectRenderedText(source, "graph TD")).text, "graph TD");
594
+ const sourceHandle = await source.elementHandle();
595
+ assert.ok(sourceHandle, "Mermaid source selection needs an inspectable source node");
596
+ const diagram = page.locator(".markdown-mermaid-diagram").last();
597
+ await expect(diagram).toHaveClass(/rendered/, { timeout: 15_000 });
598
+ await expect.poll(() => sourceHandle.evaluate((node) => node.isConnected)).toBe(true);
599
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe("graph TD");
600
+ await waitForFixtureSettlement(page);
601
+ });
602
+
603
+ test("cross-message selection survives a whole transcript rebuild", async ({ page }) => {
604
+ await page.setViewportSize({ width: 1280, height: 800 });
605
+ await page.goto(baseURL);
606
+ await triggerTranscriptContinuity(page, "duplicate");
607
+ await waitForFixtureSettlement(page);
608
+ const surfaces = page.locator(".message.assistant:not(.streaming) .markdown-body");
609
+ await expect.poll(() => surfaces.count()).toBeGreaterThanOrEqual(2);
610
+ const selectedLength = await page.locator("#chat").evaluate((chat) => {
611
+ const outputs = [...chat.querySelectorAll(".message.assistant:not(.streaming) .markdown-body")];
612
+ const textNodes = (root) => {
613
+ const nodes = [];
614
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
615
+ while (walker.nextNode()) {
616
+ if ((walker.currentNode.data || "").trim()) nodes.push(walker.currentNode);
617
+ }
618
+ return nodes;
619
+ };
620
+ const startNodes = textNodes(outputs[0]);
621
+ const endNodes = textNodes(outputs.at(-1));
622
+ const startNode = startNodes.at(-1);
623
+ const endNode = endNodes[0];
624
+ const range = document.createRange();
625
+ range.setStart(startNode, Math.max(0, startNode.data.length - 8));
626
+ range.setEnd(endNode, Math.min(18, endNode.data.length));
627
+ const selection = window.getSelection();
628
+ selection.removeAllRanges();
629
+ selection.addRange(range);
630
+ const textOffset = (surface, node, offset) => {
631
+ const prefix = document.createRange();
632
+ prefix.selectNodeContents(surface);
633
+ prefix.setEnd(node, offset);
634
+ return prefix.toString().length;
635
+ };
636
+ const endpoint = (surface, node, offset) => ({
637
+ itemKey: surface.closest(".message")?.dataset.transcriptMessageKey || surface.closest(".message")?.dataset.itemKey || "",
638
+ surfaceKey: surface.dataset.transcriptSurfaceKey || "",
639
+ offset: textOffset(surface, node, offset),
640
+ });
641
+ window.__crossMessageSelectionText = selection.toString();
642
+ window.__crossMessageSelectionBoundary = {
643
+ start: window.__crossMessageSelectionText.slice(0, 8),
644
+ end: window.__crossMessageSelectionText.slice(-18),
645
+ };
646
+ window.__crossMessageSelectionEndpoints = {
647
+ anchor: endpoint(outputs[0], selection.anchorNode, selection.anchorOffset),
648
+ focus: endpoint(outputs.at(-1), selection.focusNode, selection.focusOffset),
649
+ };
650
+ return window.__crossMessageSelectionText.length;
651
+ });
652
+ assert.ok(selectedLength > 20, "the fixture must create a real cross-message browser Range");
653
+
654
+ await page.evaluate(() => {
655
+ const key = "pi-webui-optional-features-disabled";
656
+ const current = JSON.parse(localStorage.getItem(key) || "[]");
657
+ const next = current.includes("bangCommandAutocomplete")
658
+ ? current.filter((id) => id !== "bangCommandAutocomplete")
659
+ : [...current, "bangCommandAutocomplete"];
660
+ localStorage.setItem(key, JSON.stringify(next));
661
+ window.dispatchEvent(new StorageEvent("storage", { key }));
662
+ });
663
+
664
+ await expect.poll(() => page.evaluate(() => {
665
+ const selection = window.getSelection();
666
+ const current = selection?.toString() || "";
667
+ const anchorSurface = selection?.anchorNode?.parentElement?.closest?.("[data-transcript-surface-key]");
668
+ const focusSurface = selection?.focusNode?.parentElement?.closest?.("[data-transcript-surface-key]");
669
+ const anchorBubble = anchorSurface?.closest(".message");
670
+ const focusBubble = focusSurface?.closest(".message");
671
+ const anchorItemKey = anchorBubble?.dataset.transcriptMessageKey || anchorBubble?.dataset.itemKey || "";
672
+ const focusItemKey = focusBubble?.dataset.transcriptMessageKey || focusBubble?.dataset.itemKey || "";
673
+ return current.length > 20
674
+ && current.startsWith(window.__crossMessageSelectionBoundary.start)
675
+ && current.endsWith(window.__crossMessageSelectionBoundary.end)
676
+ && anchorItemKey === window.__crossMessageSelectionEndpoints.anchor.itemKey
677
+ && focusItemKey === window.__crossMessageSelectionEndpoints.focus.itemKey;
678
+ })).toBe(true);
679
+ });
680
+
681
+ test("individually expanded tool details stay open through transcript rerenders", async ({ page }) => {
682
+ await page.setViewportSize({ width: 1280, height: 800 });
683
+ await page.goto(baseURL);
684
+ await triggerTranscriptContinuity(page, "tool");
685
+ const details = page.locator(".message.toolExecution .tool-raw-details").last();
686
+ await expect(details).toBeAttached();
687
+ await expect.poll(() => details.evaluate((node) => node.open)).toBe(false);
688
+ const summary = details.locator("summary");
689
+ await summary.click();
690
+ await expect.poll(() => details.evaluate((node) => node.open)).toBe(true);
691
+ await waitForFixtureSettlement(page);
692
+ const rawOutput = details.locator(".tool-raw-code");
693
+ const scrollTop = await rawOutput.evaluate((node) => {
694
+ node.scrollTop = Math.min(140, node.scrollHeight - node.clientHeight);
695
+ return node.scrollTop;
696
+ });
697
+ assert.ok(scrollTop > 0, "the settled raw-tool fixture must create reader scroll");
698
+ await summary.focus();
699
+ await expect(summary).toBeFocused();
700
+
701
+ await page.evaluate(() => {
702
+ const key = "pi-webui-optional-features-disabled";
703
+ const current = JSON.parse(localStorage.getItem(key) || "[]");
704
+ const next = current.includes("bangCommandAutocomplete")
705
+ ? current.filter((id) => id !== "bangCommandAutocomplete")
706
+ : [...current, "bangCommandAutocomplete"];
707
+ localStorage.setItem(key, JSON.stringify(next));
708
+ window.dispatchEvent(new StorageEvent("storage", { key }));
709
+ });
710
+
711
+ await delay(4_000);
712
+ await expect.poll(() => details.evaluate((node) => node.open)).toBe(true);
713
+ await expect.poll(() => rawOutput.evaluate((node) => node.scrollTop)).toBe(scrollTop);
714
+ await expect(summary).toBeFocused();
715
+ });
716
+
717
+ test("same-mode output control preserves settled output selection", async ({ page }) => {
718
+ await page.setViewportSize({ width: 1280, height: 800 });
719
+ await page.goto(baseURL);
720
+ const output = page.locator(".message.assistant .markdown-body").first();
721
+ const selectedText = "fake answer";
722
+ await expect(output).toContainText(selectedText);
723
+ await waitForFixtureSettlement(page);
724
+ assert.equal((await selectRenderedText(output, selectedText)).text, selectedText);
725
+
726
+ await api(page, "/api/webui-output-mode", { method: "PUT", data: { outputModeDefault: "normal" } });
727
+
728
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(selectedText);
729
+ });
730
+
731
+ test("tab navigation clears transcript selection and never restores it into another context", async ({ page }) => {
732
+ await page.setViewportSize({ width: 1280, height: 800 });
733
+ await page.goto(baseURL);
734
+ const initialOutput = page.locator(".message.assistant .markdown-body").first();
735
+ await expect(initialOutput).toContainText("fake answer");
736
+ assert.equal((await selectRenderedText(initialOutput, "fake answer")).text, "fake answer");
737
+ await page.locator("#newTabButton").click();
738
+ await page.locator("#newTabCurrentDirectoryButton").click();
739
+ await expect.poll(async () => (await tabIds(page)).length).toBe(2);
740
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe("");
741
+ const originalTab = page.locator("#tabBar [role=\"tab\"]").first();
742
+ const originalTabId = await originalTab.evaluate((node) => node.closest("[data-tab-id]")?.dataset.tabId || "");
743
+ await originalTab.click();
744
+ await expect(page.locator("#promptInput")).toBeFocused();
745
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe("");
746
+ const extraTabId = (await tabIds(page)).find((id) => id !== originalTabId);
747
+ assert.ok(extraTabId, "navigation fixture should create a distinct tab to clean up");
748
+ await api(page, `/api/tabs/${encodeURIComponent(extraTabId)}`, { method: "DELETE" });
749
+ await expect.poll(async () => (await tabIds(page)).length).toBe(1);
750
+ });
751
+
752
+ test("semantic tooltip, held pointer, open dropdown, and stale tab contexts survive only when valid", async ({ page }) => {
753
+ await page.setViewportSize({ width: 1280, height: 800 });
754
+ await page.goto(baseURL);
755
+ const initialIds = await tabIds(page);
756
+ assert.equal(initialIds.length, 1, "continuity fixture starts with one terminal tab");
757
+
758
+ await page.locator("#newTabButton").click();
759
+ await page.locator("#newTabCurrentDirectoryButton").click();
760
+ await expect.poll(async () => (await tabIds(page)).length).toBe(2);
761
+ await expect(page.locator("#tabBar [role=\"tab\"]")).toHaveCount(2);
762
+
763
+ const inactiveTabButton = page.locator("#tabBar [role=\"tab\"][aria-selected=\"false\"]");
764
+ await expect(inactiveTabButton).toBeVisible();
765
+ const inactiveTabId = await inactiveTabButton.evaluate((node) => node.closest("[data-tab-id]")?.dataset.tabId || "");
766
+ assert.ok(inactiveTabId, "the inactive grouped terminal button needs a semantic tab identity");
767
+
768
+ await inactiveTabButton.hover();
769
+ const tooltip = page.locator("#footerFloatingTooltip");
770
+ await expect(tooltip).toBeVisible();
771
+ const tooltipKey = await inactiveTabButton.getAttribute("data-tooltip-target-key");
772
+ assert.equal(tooltipKey, `terminal-tab:${inactiveTabId}:switch`, "tooltip continuity must use the tab identity rather than its display text");
773
+ const tooltipText = await inactiveTabButton.getAttribute("data-tooltip");
774
+
775
+ await triggerDelayedStream(page);
776
+ await expect(tooltip).toBeVisible();
777
+ await expect(tooltip).toHaveText(tooltipText || "");
778
+
779
+ const inactiveTab = page.locator(`[data-tab-id="${inactiveTabId}"]`);
780
+ await inactiveTab.locator(".terminal-tab-close").click();
781
+ await page.getByRole("button", { name: "Close tab", exact: true }).click();
782
+ await expect.poll(async () => (await tabIds(page)).length).toBe(1);
783
+ await expect(page.locator(`[data-tooltip-target-key="terminal-tab:${inactiveTabId}:switch"]`)).toHaveCount(0);
784
+ await page.mouse.move(0, 0);
785
+ await expect(tooltip).toBeHidden();
786
+
787
+ await page.locator("#newTabButton").click();
788
+ await expect(page.locator("#newTabButton")).toHaveAttribute("aria-expanded", "true");
789
+ await triggerDelayedStream(page);
790
+ await expect(page.locator("#newTabButton")).toHaveAttribute("aria-expanded", "true");
791
+ await expect(page.locator("#newTabMenu")).toHaveClass(/open/);
792
+ await page.locator("#promptInput").click();
793
+ await expect(page.locator("#newTabButton")).toHaveAttribute("aria-expanded", "false");
794
+
795
+ await page.locator("#newTabButton").click();
796
+ await page.locator("#newTabCurrentDirectoryButton").click();
797
+ await expect.poll(async () => (await tabIds(page)).length).toBe(2);
798
+ const heldButton = page.locator("#tabBar [role=\"tab\"][aria-selected=\"true\"]");
799
+ await expect(heldButton).toBeVisible();
800
+ await heldButton.hover();
801
+ await page.mouse.down();
802
+ const heldHandle = await heldButton.elementHandle();
803
+ assert.ok(heldHandle, "pointer deferral test needs the active terminal button element");
804
+ await triggerDelayedStream(page);
805
+ await expect.poll(() => heldHandle.evaluate((node) => node.isConnected)).toBe(true);
806
+ await page.mouse.up();
807
+ await expect.poll(() => heldHandle.evaluate((node) => node.isConnected)).toBe(false);
808
+
809
+ const secondTabId = await activeTabId(page);
810
+ assert.ok(secondTabId, "an active tab must remain after the pointer-deferred render flush");
811
+ await startContinuityRunner(page);
812
+ const runnerInput = page.locator(".app-runner-stdin-input");
813
+ await runnerInput.fill("stale runner draft");
814
+ await runnerInput.focus();
815
+ await page.keyboard.press("End");
816
+ await page.keyboard.press("Shift+ArrowLeft");
817
+ const otherTabButton = page.locator("#tabBar [role=\"tab\"][aria-selected=\"false\"]");
818
+ await expect(otherTabButton).toBeVisible();
819
+ await otherTabButton.click();
820
+ await expect(page.locator("#promptInput")).toBeFocused();
821
+ await expect(page.locator(".app-runner-stdin-input")).toHaveCount(0);
822
+ });
823
+
824
+ test("scrolled transcript stays pixel-stable while the live tail grows", async ({ page }) => {
825
+ await page.setViewportSize({ width: 900, height: 420 });
826
+ await page.goto(baseURL);
827
+ await expect.poll(() => page.locator("#chat .message.user").count()).toBeGreaterThanOrEqual(2);
828
+ await expect.poll(() => page.locator("#chat .message.assistant").count()).toBeGreaterThanOrEqual(1);
829
+ await page.addStyleTag({ content: "#chat .message { min-height: 11rem; }" });
830
+ await triggerTranscriptContinuity(page, "cadence");
831
+
832
+ const output = page.locator(".message.assistant.streaming .streaming-markdown").last();
833
+ await expect(output).toContainText("high cadence selection literal");
834
+ const chat = page.locator("#chat");
835
+ const baseline = await chat.evaluate((node) => {
836
+ node.style.scrollBehavior = "auto";
837
+ node.scrollTop = node.scrollHeight;
838
+ node.dispatchEvent(new WheelEvent("wheel", { deltaY: -120 }));
839
+ node.scrollTop = Math.max(0, node.scrollHeight - node.clientHeight - 120);
840
+ node.dispatchEvent(new Event("scroll"));
841
+ const value = node.scrollTop;
842
+ node.style.removeProperty("scroll-behavior");
843
+ return value;
844
+ });
845
+ assert.ok(baseline > 0, `scroll stability fixture needs a nonzero reader position, got ${baseline}`);
846
+
847
+ const samples = await chat.evaluate(async (node) => {
848
+ const values = [];
849
+ setTimeout(() => window.dispatchEvent(new KeyboardEvent("keydown", { key: "t", ctrlKey: true, bubbles: true })), 100);
850
+ const deadline = performance.now() + 1200;
851
+ while (performance.now() < deadline) {
852
+ await new Promise(requestAnimationFrame);
853
+ const sticky = document.querySelector("#stickyUserPromptButton");
854
+ values.push({
855
+ top: node.scrollTop,
856
+ remaining: node.scrollHeight - node.clientHeight - node.scrollTop,
857
+ autoFollow: document.querySelector("#jumpToLatestButton")?.hidden === true,
858
+ stickyHidden: sticky?.hidden !== false,
859
+ stickyHeight: sticky?.getBoundingClientRect().height || 0,
860
+ children: [...node.children].map((child) => `${child.className}:${Math.round(child.getBoundingClientRect().height)}`),
861
+ });
862
+ }
863
+ return values;
864
+ });
865
+ assert.ok(samples.length > 10, "scroll stability fixture should observe multiple rendered frames");
866
+ const tops = samples.map((sample) => sample.top);
867
+ const drift = Math.max(...tops) - Math.min(...tops);
868
+ assert.ok(drift <= 1, `reader scrollTop must stay stable while output grows; observed ${drift}px drift from ${Math.min(...tops)} to ${Math.max(...tops)}; states ${JSON.stringify(samples.filter((sample, index) => index === 0 || sample.top !== samples[index - 1].top))}`);
869
+ await waitForFixtureSettlement(page);
870
+ });
871
+
872
+ test("compact live output keeps the selected Text node through repeated flushes", async ({ page }) => {
873
+ await api(page, "/api/webui-output-mode", { method: "PUT", data: { outputModeDefault: "compact-v1" } });
874
+ try {
875
+ await page.setViewportSize({ width: 1280, height: 800 });
876
+ await page.goto(baseURL);
877
+ await triggerDelayedStream(page);
878
+
879
+ const compactOutput = page.locator(".message.compact-live-output .compact-live-text").last();
880
+ const selectedText = "continuity";
881
+ await expect(compactOutput).toContainText(selectedText);
882
+ assert.equal((await selectRenderedText(compactOutput, selectedText)).text, selectedText);
883
+ const textNode = await compactOutput.evaluateHandle((node) => node.firstChild);
884
+ const surfaceHandle = await compactOutput.elementHandle();
885
+ const bubbleHandle = await compactOutput.locator("xpath=ancestor::article[1]").elementHandle();
886
+ assert.ok(surfaceHandle && bubbleHandle, "compact settlement needs stable surface and bubble identities");
887
+ await expect(compactOutput).toContainText("continuity stream");
888
+ await expect.poll(() => textNode.evaluate((node) => node?.isConnected === true)).toBe(true);
889
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(selectedText);
890
+ await waitForFixtureSettlement(page);
891
+ await expect.poll(() => surfaceHandle.evaluate((node) => node.isConnected && node.classList.contains("markdown-body"))).toBe(true);
892
+ await expect.poll(() => bubbleHandle.evaluate((node) => node.isConnected && !node.classList.contains("streaming") && /^m:\d+$/.test(node.dataset.itemKey || ""))).toBe(true);
893
+ await expect.poll(() => page.evaluate(() => window.getSelection()?.toString() || "")).toBe(selectedText);
894
+ } finally {
895
+ await api(page, "/api/webui-output-mode", { method: "PUT", data: { outputModeDefault: "normal" } });
896
+ }
897
+ });