@firstpick/pi-package-webui 0.9.5 → 0.9.6

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 (61) hide show
  1. package/README.md +5 -3
  2. package/bin/pi-webui.mjs +90 -5
  3. package/lib/optional-feature-catalog.mjs +1 -1
  4. package/lib/session-actions.mjs +20 -2
  5. package/package.json +1 -1
  6. package/public/app.js +1823 -262
  7. package/public/index.html +51 -31
  8. package/public/service-worker.js +4 -1
  9. package/public/stream-derived-output.mjs +799 -0
  10. package/public/stream-markdown-tail.mjs +204 -0
  11. package/public/stream-output-controller.mjs +193 -51
  12. package/public/stream-render-scheduler.mjs +85 -0
  13. package/public/styles.css +249 -18
  14. package/public/transcript-renderer.mjs +73 -24
  15. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  16. package/tests/browser/composer-action-grid-reorder.spec.mjs +114 -31
  17. package/tests/browser/mobile-foundation.spec.mjs +28 -0
  18. package/tests/browser/stream-output-isolation.spec.mjs +308 -3
  19. package/tests/browser/user-noticeable-fixes.spec.mjs +204 -0
  20. package/tests/codex-fast-mode-static.test.mjs +2 -2
  21. package/tests/composer-action-grid-reorder-static.test.mjs +8 -7
  22. package/tests/control-visibility-static.test.mjs +3 -3
  23. package/tests/controls-layout-static.test.mjs +3 -3
  24. package/tests/cwd-footer-reliability-static.test.mjs +1 -1
  25. package/tests/fast-mode-client-static.test.mjs +1 -1
  26. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  27. package/tests/file-viewer-image-static.test.mjs +3 -3
  28. package/tests/fixtures/fake-pi.mjs +57 -10
  29. package/tests/fixtures/streaming-workloads.mjs +36 -0
  30. package/tests/footer-provider-usage-visual-static.test.mjs +15 -0
  31. package/tests/foreground-transcript-catch-up-static.test.mjs +7 -1
  32. package/tests/interaction-state-stability-static.test.mjs +3 -1
  33. package/tests/intercom-conversation-viewer-static.test.mjs +3 -3
  34. package/tests/intercom-conversations-http.test.mjs +16 -0
  35. package/tests/main-output-loading-static.test.mjs +3 -3
  36. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  37. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  38. package/tests/mobile-foundation-static.test.mjs +3 -3
  39. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  40. package/tests/mobile-static.test.mjs +74 -63
  41. package/tests/open-issue-wizard-static.test.mjs +1 -1
  42. package/tests/persistent-ui-layout-static.test.mjs +4 -4
  43. package/tests/prompt-input-vertical-scroll-static.test.mjs +26 -0
  44. package/tests/questionnaire-dialog.test.mjs +3 -3
  45. package/tests/runtime-error-visibility.test.mjs +3 -3
  46. package/tests/session-auth-harness.test.mjs +26 -1
  47. package/tests/session-sampling-ui-static.test.mjs +3 -3
  48. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  49. package/tests/stream-derived-output.test.mjs +121 -0
  50. package/tests/stream-markdown-tail.test.mjs +218 -0
  51. package/tests/stream-output-controller.test.mjs +119 -4
  52. package/tests/stream-output-isolation-static.test.mjs +27 -6
  53. package/tests/stream-output-workloads.test.mjs +40 -3
  54. package/tests/stream-render-scheduler.test.mjs +115 -0
  55. package/tests/streaming-ui-coupling.test.mjs +1 -1
  56. package/tests/subagent-observability-static.test.mjs +2 -2
  57. package/tests/syntax-highlighting-static.test.mjs +3 -3
  58. package/tests/theme-customizer-static.test.mjs +1 -1
  59. package/tests/thinking-format-parser.test.mjs +15 -0
  60. package/tests/todo-filter-static.test.mjs +148 -0
  61. package/tests/transcript-markdown-tail.test.mjs +137 -0
@@ -68,7 +68,8 @@ test.beforeEach(async () => {
68
68
  method: "PUT",
69
69
  headers: { "content-type": "application/json" },
70
70
  body: JSON.stringify({
71
- layout: { version: 1, composerActions: null },
71
+ sidePanelWidth: 384,
72
+ layout: { version: 3, composerActions: null },
72
73
  expectedLayoutRevision: current.data.layoutRevision,
73
74
  }),
74
75
  });
@@ -83,6 +84,14 @@ async function storedLayout(page) {
83
84
  return page.evaluate((key) => JSON.parse(localStorage.getItem(key) || "null"), layoutStorageKey);
84
85
  }
85
86
 
87
+ async function resizeControlDeckBy(handle, key, count) {
88
+ for (let index = 0; index < count; index += 1) {
89
+ const previous = await handle.getAttribute("aria-valuenow");
90
+ await handle.press(key);
91
+ await expect.poll(async () => handle.getAttribute("aria-valuenow")).not.toBe(previous);
92
+ }
93
+ }
94
+
86
95
  test("composer actions persist pointer and keyboard grid reordering", async ({ page }) => {
87
96
  await page.setViewportSize({ width: 1440, height: 900 });
88
97
  await page.goto(baseURL);
@@ -247,18 +256,81 @@ test("empty composer grid cells retain their space and accept later drops", asyn
247
256
  await expect.poll(async () => page.evaluate((key) => JSON.parse(localStorage.getItem(key) || "null")?.positions?.new, layoutStorageKey)).toBe(middleEmptyCellIndex);
248
257
  });
249
258
 
250
- test("sparse composer buttons keep responsive positions when the Control Deck width changes", async ({ page }) => {
259
+ test("narrow composer projection preserves the saved order of adjacent actions", async ({ page }) => {
251
260
  await page.setViewportSize({ width: 1440, height: 900 });
252
261
  await page.goto(baseURL);
253
262
 
254
263
  const row = page.locator(".composer-row");
255
264
  const options = page.locator('[data-composer-action-id="options"]');
265
+ const send = page.locator('[data-composer-action-id="send"]');
256
266
  const gridGuide = page.locator("#composerActionGridGuide");
257
267
  const resizeHandle = page.locator("#sidePanelResizeHandle");
268
+
269
+ const moveToCellFromEnd = async (action, offsetFromEnd) => {
270
+ const actionBox = await action.boundingBox();
271
+ expect(actionBox).toBeTruthy();
272
+ await page.mouse.move(actionBox.x + actionBox.width / 2, actionBox.y + actionBox.height / 2);
273
+ await page.mouse.down();
274
+ await page.mouse.move(actionBox.x + actionBox.width / 2 + 12, actionBox.y + actionBox.height / 2, { steps: 2 });
275
+ await expect(gridGuide).toBeVisible();
276
+ const cellCount = await gridGuide.locator(".composer-action-grid-cell").count();
277
+ const target = gridGuide.locator(".composer-action-grid-cell").nth(cellCount - offsetFromEnd);
278
+ const targetBox = await target.boundingBox();
279
+ expect(targetBox).toBeTruthy();
280
+ await page.mouse.move(targetBox.x + targetBox.width / 2, targetBox.y + targetBox.height / 2, { steps: 8 });
281
+ await page.mouse.up();
282
+ await expect(gridGuide).toBeHidden();
283
+ };
284
+
285
+ await moveToCellFromEnd(options, 3);
286
+ await moveToCellFromEnd(send, 2);
287
+ const savedWideLayout = await storedLayout(page);
288
+ expect(savedWideLayout?.positions?.options).toBeLessThan(savedWideLayout?.positions?.send);
258
289
  const wideRowBox = await row.boundingBox();
259
- const optionsBox = await options.boundingBox();
260
290
  expect(wideRowBox).toBeTruthy();
291
+
292
+ await resizeHandle.focus();
293
+ await resizeControlDeckBy(resizeHandle, "Shift+ArrowLeft", 3);
294
+ await expect.poll(async () => (await row.boundingBox()).width).toBeLessThan(wideRowBox.width - 150);
295
+ await expect.poll(async () => {
296
+ const [optionsBox, sendBox] = await Promise.all([options.boundingBox(), send.boundingBox()]);
297
+ if (!optionsBox || !sendBox) return false;
298
+ return optionsBox.y < sendBox.y || (Math.abs(optionsBox.y - sendBox.y) < 1 && optionsBox.x < sendBox.x);
299
+ }).toBe(true);
300
+ expect(await storedLayout(page)).toEqual(savedWideLayout);
301
+
302
+ await page.reload();
303
+ await expect.poll(async () => {
304
+ const [optionsBox, sendBox] = await Promise.all([options.boundingBox(), send.boundingBox()]);
305
+ if (!optionsBox || !sendBox) return false;
306
+ return optionsBox.y < sendBox.y || (Math.abs(optionsBox.y - sendBox.y) < 1 && optionsBox.x < sendBox.x);
307
+ }).toBe(true);
308
+ expect(await storedLayout(page)).toEqual(savedWideLayout);
309
+ });
310
+
311
+ test("sparse composer buttons keep fixed widths and stable columns when the Control Deck width changes", async ({ page }) => {
312
+ await page.setViewportSize({ width: 1440, height: 900 });
313
+ await page.goto(baseURL);
314
+
315
+ const row = page.locator(".composer-row");
316
+ const options = page.locator('[data-composer-action-id="options"]');
317
+ const send = page.locator('[data-composer-action-id="send"]');
318
+ const gridGuide = page.locator("#composerActionGridGuide");
319
+ const resizeHandle = page.locator("#sidePanelResizeHandle");
320
+ const initialRowBox = await row.boundingBox();
321
+ expect(initialRowBox).toBeTruthy();
322
+
323
+ await resizeHandle.focus();
324
+ await resizeControlDeckBy(resizeHandle, "Shift+ArrowLeft", 3);
325
+ await expect.poll(async () => (await row.boundingBox()).width).toBeLessThan(initialRowBox.width - 50);
326
+
327
+ const narrowRowBox = await row.boundingBox();
328
+ const optionsBox = await options.boundingBox();
329
+ expect(narrowRowBox).toBeTruthy();
261
330
  expect(optionsBox).toBeTruthy();
331
+ const rootFontSize = await page.evaluate(() => Number.parseFloat(getComputedStyle(document.documentElement).fontSize));
332
+ const fixedCellWidth = 3.2 * rootFontSize;
333
+ expect(Math.abs(optionsBox.width - fixedCellWidth)).toBeLessThan(1);
262
334
 
263
335
  await page.mouse.move(optionsBox.x + optionsBox.width / 2, optionsBox.y + optionsBox.height / 2);
264
336
  await page.mouse.down();
@@ -269,35 +341,46 @@ test("sparse composer buttons keep responsive positions when the Control Deck wi
269
341
  await page.mouse.move(lastCellBox.x + lastCellBox.width / 2, lastCellBox.y + lastCellBox.height / 2, { steps: 8 });
270
342
  await page.mouse.up();
271
343
 
272
- const wideColumn = await options.evaluate((node) => node.style.getPropertyValue("--composer-action-grid-column"));
273
- const savedWideLayout = await storedLayout(page);
274
- expect(Number(wideColumn)).toBeGreaterThan(1);
275
- expect(savedWideLayout?.columns).toBeGreaterThan(1);
344
+ const placedOptionsBox = await options.boundingBox();
345
+ const placedSendBox = await send.boundingBox();
346
+ const narrowColumn = await options.evaluate((node) => node.style.getPropertyValue("--composer-action-grid-column"));
347
+ const savedNarrowLayout = await storedLayout(page);
348
+ expect(placedOptionsBox).toBeTruthy();
349
+ expect(placedSendBox).toBeTruthy();
350
+ expect(Number(narrowColumn)).toBeGreaterThan(1);
351
+ expect(savedNarrowLayout?.columns).toBeGreaterThan(1);
276
352
 
277
- await resizeHandle.focus();
278
- await resizeHandle.press("Shift+ArrowLeft");
279
- await resizeHandle.press("Shift+ArrowLeft");
280
- await resizeHandle.press("Shift+ArrowLeft");
281
-
282
- await expect.poll(async () => (await row.boundingBox()).width).toBeLessThan(wideRowBox.width - 50);
283
- await expect.poll(async () => options.evaluate((node) => node.style.getPropertyValue("--composer-action-grid-column"))).not.toBe("");
284
- await expect.poll(async () => page.evaluate(() => {
285
- const composerRow = document.querySelector(".composer-row");
286
- const action = document.querySelector('[data-composer-action-id="options"]');
287
- const rowRect = composerRow.getBoundingClientRect();
288
- const actionRect = action.getBoundingClientRect();
289
- return Math.abs(rowRect.right - actionRect.right);
290
- })).toBeLessThan(2);
291
- expect(await storedLayout(page)).toEqual(savedWideLayout);
353
+ await resizeControlDeckBy(resizeHandle, "Shift+ArrowRight", 3);
354
+
355
+ await expect.poll(async () => (await row.boundingBox()).width).toBeGreaterThan(narrowRowBox.width + 50);
356
+ await expect.poll(async () => {
357
+ const wideOptionsBox = await options.boundingBox();
358
+ return Math.abs(wideOptionsBox.width - placedOptionsBox.width);
359
+ }).toBeLessThan(1);
360
+ await expect.poll(async () => {
361
+ const wideSendBox = await send.boundingBox();
362
+ return Math.abs(wideSendBox.width - placedSendBox.width);
363
+ }).toBeLessThan(1);
364
+ await expect.poll(async () => {
365
+ const wideOptionsBox = await options.boundingBox();
366
+ return Math.abs(wideOptionsBox.x - placedOptionsBox.x);
367
+ }).toBeLessThan(1);
368
+ await expect.poll(async () => {
369
+ const wideSendBox = await send.boundingBox();
370
+ return Math.abs(wideSendBox.x - placedSendBox.x);
371
+ }).toBeLessThan(1);
372
+ await expect.poll(async () => options.evaluate((node) => node.style.getPropertyValue("--composer-action-grid-column"))).toBe(narrowColumn);
373
+ expect(await storedLayout(page)).toEqual(savedNarrowLayout);
292
374
 
293
375
  await page.reload();
294
- await expect.poll(async () => options.evaluate((node) => node.style.getPropertyValue("--composer-action-grid-column"))).not.toBe("");
295
- await expect.poll(async () => page.evaluate(() => {
296
- const composerRow = document.querySelector(".composer-row");
297
- const action = document.querySelector('[data-composer-action-id="options"]');
298
- const rowRect = composerRow.getBoundingClientRect();
299
- const actionRect = action.getBoundingClientRect();
300
- return Math.abs(rowRect.right - actionRect.right);
301
- })).toBeLessThan(2);
302
- expect(await storedLayout(page)).toEqual(savedWideLayout);
376
+ await expect.poll(async () => options.evaluate((node) => node.style.getPropertyValue("--composer-action-grid-column"))).toBe(narrowColumn);
377
+ await expect.poll(async () => {
378
+ const restoredOptionsBox = await options.boundingBox();
379
+ return Math.abs(restoredOptionsBox.x - placedOptionsBox.x);
380
+ }).toBeLessThan(1);
381
+ await expect.poll(async () => {
382
+ const restoredSendBox = await send.boundingBox();
383
+ return Math.abs(restoredSendBox.x - placedSendBox.x);
384
+ }).toBeLessThan(1);
385
+ expect(await storedLayout(page)).toEqual(savedNarrowLayout);
303
386
  });
@@ -90,6 +90,34 @@ test("v2 flag is isolated on desktop and rollback remains explicit", async ({ pa
90
90
  await expect(page.locator("#mobileShellV2")).toBeHidden();
91
91
  });
92
92
 
93
+ test("the main prompt scrolls vertically after bounded auto-growth", async ({ page }) => {
94
+ await page.setViewportSize({ width: 1280, height: 800 });
95
+ await page.goto(baseURL);
96
+ const prompt = page.locator("#promptInput");
97
+ const longPrompt = Array.from({ length: 20 }, (_, index) => `line ${index + 1}: keep this prompt line reachable`).join("\n");
98
+
99
+ await prompt.fill(longPrompt);
100
+ const longMetrics = await prompt.evaluate((node) => {
101
+ const style = getComputedStyle(node);
102
+ node.scrollTop = node.scrollHeight;
103
+ return {
104
+ clientHeight: node.clientHeight,
105
+ maxHeight: Number.parseFloat(style.maxHeight),
106
+ overflowY: style.overflowY,
107
+ scrollHeight: node.scrollHeight,
108
+ scrollTop: node.scrollTop,
109
+ };
110
+ });
111
+ assert.equal(longMetrics.overflowY, "auto");
112
+ assert.ok(longMetrics.scrollHeight > longMetrics.clientHeight + 1, `long prompt should overflow vertically: ${JSON.stringify(longMetrics)}`);
113
+ assert.ok(longMetrics.scrollTop > 0, `long prompt should accept vertical scrolling: ${JSON.stringify(longMetrics)}`);
114
+ assert.ok(longMetrics.clientHeight <= longMetrics.maxHeight + 1, `prompt should retain its height cap: ${JSON.stringify(longMetrics)}`);
115
+
116
+ await prompt.fill("short prompt");
117
+ const shortMetrics = await prompt.evaluate((node) => ({ clientHeight: node.clientHeight, scrollHeight: node.scrollHeight }));
118
+ assert.ok(shortMetrics.clientHeight < longMetrics.clientHeight, `short prompt should shrink after long input: ${JSON.stringify(shortMetrics)}`);
119
+ });
120
+
93
121
  test("legacy phone keeps terminal navigation and secondary composer actions collapsed", async ({ browser }) => {
94
122
  const context = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
95
123
  const page = await context.newPage();
@@ -1,7 +1,9 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { spawn } from "node:child_process";
3
+ import { createHash } from "node:crypto";
3
4
  import { createServer } from "node:net";
4
5
  import { mkdtemp, readFile, rm } from "node:fs/promises";
6
+ import { cpus, hostname, release, totalmem } from "node:os";
5
7
  import { tmpdir } from "node:os";
6
8
  import { dirname, join } from "node:path";
7
9
  import { setTimeout as delay } from "node:timers/promises";
@@ -76,7 +78,7 @@ async function waitForPhase(runId, phase) {
76
78
 
77
79
  async function assertFixtureContract(runId, mode, scenario = "standard") {
78
80
  const entries = await waitForPhase(runId, scenario === "abort" ? "abort-ready" : "settled");
79
- const textDeltas = entries.filter((entry) => entry.isolationPhase === "raw" && entry.type === "message_update" && entry.assistantMessageEventType === "text_delta");
81
+ const textDeltas = entries.filter((entry) => entry.isolationPhase === "raw" && entry.type === "message_update" && entry.assistantMessageEventType === "text_delta" && Number.isInteger(entry.isolationDeltaIndex));
80
82
  const expectedCount = scenario === "abort" ? 500 : deltaCount;
81
83
  assert.equal(textDeltas.length, expectedCount, `${mode}/${scenario} fixture must emit the expected non-empty text deltas`);
82
84
  assert.deepEqual(textDeltas.map((entry) => entry.isolationDeltaIndex), expectedIndexes.slice(0, expectedCount));
@@ -177,6 +179,7 @@ async function installIsolationInstrumentation(page, { pauseChat = false } = {})
177
179
  };
178
180
  const underTranscript = (node) => (node?.nodeType === Node.ELEMENT_NODE ? node : node?.parentElement)?.closest?.("#chat") !== null;
179
181
  const allowedFollowMutation = (record) => record.type === "attributes" && record.attributeName === "hidden" && record.target === document.querySelector("#jumpToLatestButton");
182
+ const allowedElapsedMetadataMutation = (record) => record.type === "childList" && record.target?.matches?.("span.run-indicator-meta") === true;
180
183
  const scrollNodes = [...document.querySelectorAll("*")].filter((node) => {
181
184
  if (node.closest?.("#chat")) return false;
182
185
  return node === document.scrollingElement || node.scrollHeight > node.clientHeight || node.scrollWidth > node.clientWidth || node.scrollTop !== 0 || node.scrollLeft !== 0;
@@ -185,6 +188,7 @@ async function installIsolationInstrumentation(page, { pauseChat = false } = {})
185
188
  const proof = {
186
189
  allowedMutations: { attributes: 0, characterData: 0, childList: 0 },
187
190
  allowedFollowMutations: 0,
191
+ allowedElapsedMetadataMutations: 0,
188
192
  forbiddenMutations: { attributes: 0, characterData: 0, childList: 0 },
189
193
  forbiddenMutationExamples: [],
190
194
  focusEvents: [], focusCalls: [], scrollIntoViewCalls: [], fetchCalls: [], eventSourceConstructions: [],
@@ -202,6 +206,7 @@ async function installIsolationInstrumentation(page, { pauseChat = false } = {})
202
206
  for (const record of records) {
203
207
  if (underTranscript(record.target)) proof.allowedMutations[record.type] += 1;
204
208
  else if (allowedFollowMutation(record)) proof.allowedFollowMutations += 1;
209
+ else if (allowedElapsedMetadataMutation(record)) proof.allowedElapsedMetadataMutations += 1;
205
210
  else {
206
211
  proof.forbiddenMutations[record.type] += 1;
207
212
  if (proof.forbiddenMutationExamples.length < 20) proof.forbiddenMutationExamples.push(`${record.type}:${describe(record.target)}:${record.attributeName || ""}`);
@@ -244,6 +249,7 @@ async function finishIsolationInstrumentation(page) {
244
249
  return {
245
250
  allowedMutations: proof.allowedMutations,
246
251
  allowedFollowMutations: proof.allowedFollowMutations,
252
+ allowedElapsedMetadataMutations: proof.allowedElapsedMetadataMutations,
247
253
  forbiddenMutations: proof.forbiddenMutations,
248
254
  forbiddenMutationExamples: proof.forbiddenMutationExamples,
249
255
  focusEvents: proof.focusEvents,
@@ -266,6 +272,7 @@ async function finishIsolationInstrumentation(page) {
266
272
  counters: { ...ledger.counters },
267
273
  receivedIndexes: [...ledger.receivedIndexes],
268
274
  appliedIndexes: [...ledger.appliedIndexes],
275
+ records: ledger.records.map((record) => ({ ...record })),
269
276
  },
270
277
  };
271
278
  });
@@ -290,6 +297,12 @@ async function holdIndependentPollResponses(page) {
290
297
  };
291
298
  }
292
299
 
300
+ function percentileNearestRank(values, percentile) {
301
+ if (!values.length) return null;
302
+ const sorted = [...values].sort((left, right) => left - right);
303
+ return sorted[Math.max(0, Math.ceil(percentile * sorted.length) - 1)];
304
+ }
305
+
293
306
  function assertIsolationMetrics(metrics, networkRequests, surface, expectedSelection, expectedIndexCount = deltaCount) {
294
307
  assert.deepEqual(metrics.forbiddenMutations, { attributes: 0, characterData: 0, childList: 0 }, `${surface}: ${metrics.forbiddenMutationExamples.join(", ")}`);
295
308
  assert.deepEqual(metrics.focusEvents, []);
@@ -321,7 +334,12 @@ async function startFixture(page, mode, scenario = "standard") {
321
334
  data: { message: `fixture stream isolation ${mode} ${scenario}`, requestId: `stream-isolation-${mode}-${scenario}-${Date.now()}` },
322
335
  });
323
336
  assert.equal(response.data?.deltaCount, deltaCount);
324
- assert.equal(response.data?.finalText, expectedFinalText);
337
+ if (scenario !== "long-transcript") assert.equal(response.data?.finalText, expectedFinalText);
338
+ else {
339
+ assert.equal(response.data?.retainedMessageCount, 1000);
340
+ assert.ok(response.data?.finalText?.startsWith("```js\nconst v0000 = 0;\n"));
341
+ assert.ok(response.data?.finalText?.endsWith("```\nLONG-STREAM-TAIL"));
342
+ }
325
343
  await waitForPhase(response.data.runId, "ready");
326
344
  await expect(page.locator("#abortButton")).toBeVisible();
327
345
  await expect(page.locator(".message.toolExecution").last()).toContainText("read");
@@ -342,7 +360,7 @@ async function startFixture(page, mode, scenario = "standard") {
342
360
  // stream-delta-caused chrome mutation in the observed window.
343
361
  await expect(page.locator("#optionalFeatureMigrationSurface")).toBeHidden();
344
362
  await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
345
- return { tabId, runId: response.data.runId };
363
+ return { tabId, runId: response.data.runId, finalText: response.data.finalText, retainedMessageCount: response.data.retainedMessageCount || 0 };
346
364
  }
347
365
 
348
366
  async function continueFixture(tabId, runId) {
@@ -444,6 +462,54 @@ test("desktop compact isolation preserves paused reader and modal", async ({ pag
444
462
  test("mobile 390x844 normal isolation", async ({ page }) => runIsolationCase(page, { mode: "normal", viewport: { width: 390, height: 844 }, label: "mobile-390" }));
445
463
  test("mobile 320x568 compact isolation", async ({ page }) => runIsolationCase(page, { mode: "compact", viewport: { width: 320, height: 568 }, pauseChat: true, label: "mobile-320" }));
446
464
 
465
+ test("Chromium streaming baseline: hidden output reconciles exactly on foreground", async ({ page }) => {
466
+ await serverApi("/api/webui-output-mode", { method: "PUT", data: { outputModeDefault: "normal" } });
467
+ const expectedSelection = await prepareInteractiveState(page, { viewport: { width: 1280, height: 720 }, pauseChat: true });
468
+ const completed = page.locator(".message.assistant:not(.streaming) .markdown-body", { hasText: "ISOLATION-TEXT-TAIL" });
469
+ const completedBefore = await completed.count();
470
+ const { tabId, runId } = await startFixture(page, "normal", "background");
471
+ const before = await page.evaluate(() => ({
472
+ activeElement: document.activeElement?.id || "",
473
+ selection: window.getSelection()?.toString() || "",
474
+ chatTop: document.querySelector("#chat")?.scrollTop || 0,
475
+ }));
476
+
477
+ await page.evaluate(() => {
478
+ window.__ws0VisibilityState = "hidden";
479
+ Object.defineProperty(document, "visibilityState", {
480
+ configurable: true,
481
+ get: () => window.__ws0VisibilityState,
482
+ });
483
+ document.dispatchEvent(new Event("visibilitychange"));
484
+ });
485
+ await page.waitForTimeout(200);
486
+ await continueFixture(tabId, runId);
487
+ await waitForPhase(runId, "settled");
488
+ await expect(completed).toHaveCount(completedBefore);
489
+
490
+ await page.evaluate(() => {
491
+ window.__ws0VisibilityState = "visible";
492
+ document.dispatchEvent(new Event("visibilitychange"));
493
+ });
494
+ await expect(completed).toHaveCount(completedBefore + 1);
495
+ await waitForSettlement(page, tabId);
496
+ const after = await page.evaluate(() => {
497
+ const selection = window.getSelection();
498
+ return {
499
+ activeElement: document.activeElement?.id || "",
500
+ selection: selection?.toString() || "",
501
+ selectionConnected: selection?.anchorNode?.isConnected === true && selection?.focusNode?.isConnected === true,
502
+ chatTop: document.querySelector("#chat")?.scrollTop || 0,
503
+ };
504
+ });
505
+ assert.equal(before.activeElement, "promptInput");
506
+ assert.equal(after.activeElement, before.activeElement, "foreground reconciliation must preserve composer focus");
507
+ assert.equal(after.selection, expectedSelection, "foreground reconciliation must preserve exact selected text");
508
+ assert.equal(after.selectionConnected, true);
509
+ assert.equal(after.chatTop, before.chatTop, "foreground reconciliation must preserve detached scroll position exactly");
510
+ await assertFixtureContract(runId, "normal", "background");
511
+ });
512
+
447
513
  test("abort flushes and preserves the partial text tail before lifecycle chrome settles", async ({ page }) => {
448
514
  await serverApi("/api/webui-output-mode", { method: "PUT", data: { outputModeDefault: "normal" } });
449
515
  const expectedSelection = await prepareInteractiveState(page, { viewport: { width: 1280, height: 720 } });
@@ -508,3 +574,242 @@ test("retry compaction reconnect and settlement retain lifecycle control identit
508
574
  assert.equal(await steer.evaluate((node) => node.isConnected), true, "Steer must retain node identity through settlement");
509
575
  assert.equal(await followUp.evaluate((node) => node.isConnected), true, "Follow-up must retain node identity through settlement");
510
576
  });
577
+
578
+ test("WS3 paced cadence and slow-renderer queue pressure remain bounded", async ({ page }) => {
579
+ test.setTimeout(120_000);
580
+ await serverApi("/api/webui-output-mode", { method: "PUT", data: { outputModeDefault: "normal" } });
581
+ const expectedSelection = await prepareInteractiveState(page, { viewport: { width: 1280, height: 720 }, pauseChat: true });
582
+ const { tabId, runId, finalText } = await startFixture(page, "normal", "paced-pressure");
583
+ const releaseIndependentPolls = await holdIndependentPollResponses(page);
584
+ const networkRequests = [];
585
+ const onRequest = (request) => networkRequests.push(`${request.method()} ${request.url()}`);
586
+ page.on("request", onRequest);
587
+ await installIsolationInstrumentation(page, { pauseChat: true });
588
+ await page.evaluate(() => {
589
+ const original = window.requestAnimationFrame.bind(window);
590
+ window.__ws3OriginalRequestAnimationFrame = original;
591
+ window.requestAnimationFrame = (callback) => original((timestamp) => {
592
+ const deadline = performance.now() + 8;
593
+ while (performance.now() < deadline) { /* deterministic slow-renderer pressure */ }
594
+ callback(timestamp);
595
+ });
596
+ });
597
+
598
+ await continueFixture(tabId, runId);
599
+ await waitForPhase(runId, "text-complete");
600
+ await expect.poll(() => page.evaluate(() => window.__piStreamIsolationDebug?.appliedIndexes?.length || 0)).toBe(deltaCount);
601
+ const liveMarkdown = page.locator(".message.assistant.streaming .streaming-markdown").last();
602
+ await expect(liveMarkdown).toContainText("ISOLATION-TEXT-TAIL");
603
+ assert.equal((await liveMarkdown.textContent()).trim(), finalText, "paced pressure must end on the authoritative exact snapshot");
604
+ await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
605
+
606
+ const metrics = await finishIsolationInstrumentation(page);
607
+ await page.evaluate(() => {
608
+ if (window.__ws3OriginalRequestAnimationFrame) window.requestAnimationFrame = window.__ws3OriginalRequestAnimationFrame;
609
+ delete window.__ws3OriginalRequestAnimationFrame;
610
+ });
611
+ page.off("request", onRequest);
612
+ await releaseIndependentPolls();
613
+
614
+ assert.deepEqual(metrics.forbiddenMutations, { attributes: 0, characterData: 0, childList: 0 }, metrics.forbiddenMutationExamples.join(", "));
615
+ assert.deepEqual(metrics.focusEvents, []);
616
+ assert.deepEqual(metrics.focusCalls, []);
617
+ assert.equal(metrics.activeElementChanged, false);
618
+ assert.deepEqual(metrics.identityChanges, []);
619
+ assert.deepEqual(metrics.scrollChanges, []);
620
+ assert.equal(metrics.chatTopAfter, metrics.chatTopBefore, "slow rendering must not move a detached reader");
621
+ assert.equal(metrics.selectionBefore, expectedSelection);
622
+ assert.equal(metrics.selectionAfter, expectedSelection);
623
+ assert.equal(metrics.selectionNodesConnected, true);
624
+ assert.deepEqual(metrics.debug.receivedIndexes, expectedIndexes);
625
+ assert.deepEqual(metrics.debug.appliedIndexes, expectedIndexes);
626
+ assert.deepEqual(networkRequests.filter((request) => !isIndependentPollRequest(request.split(" ").slice(1).join(" "))), []);
627
+
628
+ const counters = metrics.debug.counters;
629
+ assert.ok(counters.renderSchedulerFlushes > 2, "paced output must exercise sustained normal formatting");
630
+ assert.ok(counters.renderSchedulerDefers > 0, "paced output must defer at least one latest-wins render");
631
+ assert.ok(counters.renderSchedulerFlushes < counters.appliedEvents, "formatting publishes must remain below applied transport sources");
632
+ assert.ok(counters.pressureDeferred > 0, "the first queue-pressure drain must leave the EventSource callback");
633
+ assert.ok(counters.pressureSynchronousFallbacks > 0, "repeated same-task pressure must exercise the synchronous lossless fallback");
634
+ assert.ok(counters.highWaterPendingCount <= 129, `primary plus urgent entry should cap at 129, got ${counters.highWaterPendingCount}`);
635
+ assert.ok(counters.highWaterPendingBytes <= 2 * 256 * 1024, "primary plus urgent bytes must remain explicitly bounded");
636
+ assert.equal(counters.focusLossNearStreamBatch, 0);
637
+ assert.equal(counters.detachedScrollMoves, 0);
638
+
639
+ const records = metrics.debug.records;
640
+ const paintMs = records.filter((record) => record.type === "paint-opportunity").map((record) => Number(record.ms)).filter(Number.isFinite);
641
+ const longTaskMs = records.filter((record) => record.type === "longtask").map((record) => Number(record.ms)).filter(Number.isFinite);
642
+ const longFrameMs = records.filter((record) => record.type === "long-animation-frame").map((record) => Number(record.ms)).filter(Number.isFinite);
643
+ console.log(`WS3_STREAMING_CANDIDATE ${JSON.stringify({
644
+ scenario: {
645
+ sourceIndexedTextDeltas: deltaCount,
646
+ finalTextBytesUtf8: Buffer.byteLength(finalText),
647
+ finalTextSha256: createHash("sha256").update(finalText).digest("hex"),
648
+ injectedFrameDelayMs: 8,
649
+ selectedCadenceMs: 40,
650
+ },
651
+ eventAndRenderCounts: {
652
+ receivedEvents: counters.receivedEvents,
653
+ appliedEvents: counters.appliedEvents,
654
+ sinkCalls: counters.sinkCalls,
655
+ controllerBatches: counters.batches,
656
+ renderSchedulerFlushes: counters.renderSchedulerFlushes,
657
+ renderSchedulerDefers: counters.renderSchedulerDefers,
658
+ markdownCommits: counters.markdownCommits,
659
+ },
660
+ pressure: {
661
+ overflows: counters.overflows,
662
+ deferred: counters.pressureDeferred,
663
+ synchronousFallbacks: counters.pressureSynchronousFallbacks,
664
+ queueHighWaterEntries: counters.highWaterPendingCount,
665
+ queueHighWaterBytes: counters.highWaterPendingBytes,
666
+ },
667
+ receiptToPaintMs: {
668
+ samples: paintMs.length,
669
+ p95: percentileNearestRank(paintMs, 0.95),
670
+ max: paintMs.length ? Math.max(...paintMs) : null,
671
+ },
672
+ longestMs: {
673
+ batchDrain: counters.batchDrainMaxMs,
674
+ markdownCommit: counters.markdownCommitMaxMs,
675
+ longTask: longTaskMs.length ? Math.max(...longTaskMs) : null,
676
+ longAnimationFrame: longFrameMs.length ? Math.max(...longFrameMs) : null,
677
+ },
678
+ continuity: {
679
+ focusLossNearStreamBatch: counters.focusLossNearStreamBatch,
680
+ detachedScrollMoves: counters.detachedScrollMoves,
681
+ },
682
+ })}`);
683
+
684
+ await waitForSettlement(page, tabId);
685
+ await assertFixtureContract(runId, "normal", "paced-pressure");
686
+ });
687
+
688
+ test("Chromium streaming baseline: long transcript plus active fenced stream", async ({ page, browser }) => {
689
+ test.setTimeout(120_000);
690
+ await serverApi("/api/webui-output-mode", { method: "PUT", data: { outputModeDefault: "normal" } });
691
+ await page.setViewportSize({ width: 1280, height: 720 });
692
+ await page.goto(`${baseURL}/?streamIsolationDebug=1`);
693
+ await expect(page.locator("#promptInput")).toBeVisible();
694
+ const initialTabId = await activeTabId(page);
695
+ const populated = await serverApi(`/api/prompt?tab=${encodeURIComponent(initialTabId)}`, {
696
+ method: "POST",
697
+ data: { message: "fixture stream isolation populate long transcript", requestId: `stream-isolation-populate-${Date.now()}` },
698
+ });
699
+ assert.equal(populated.data?.retainedMessageCount, 1000);
700
+
701
+ // Load the deterministic retained transcript before the active stream starts.
702
+ await page.reload();
703
+ await expect(page.locator("#promptInput")).toBeVisible();
704
+ const retained = page.locator("#chat .message", { hasText: /LONG-TRANSCRIPT-\d{4}/ });
705
+ await expect(retained).toHaveCount(1000);
706
+ await expect(retained.first()).toContainText("LONG-TRANSCRIPT-0000");
707
+ await expect(retained.last()).toContainText("LONG-TRANSCRIPT-0999");
708
+ const { tabId, runId, finalText, retainedMessageCount } = await startFixture(page, "normal", "long-transcript");
709
+ assert.equal(retainedMessageCount, 1000);
710
+
711
+ const pausedTop = await page.locator("#chat").evaluate((node) => {
712
+ node.style.scrollBehavior = "auto";
713
+ node.scrollTop = Math.max(1, Math.floor((node.scrollHeight - node.clientHeight) / 3));
714
+ node.dispatchEvent(new WheelEvent("wheel", { deltaY: -160, bubbles: true }));
715
+ node.dispatchEvent(new Event("scroll", { bubbles: true }));
716
+ node.style.removeProperty("scroll-behavior");
717
+ return node.scrollTop;
718
+ });
719
+ assert.ok(pausedTop > 0, "long-transcript baseline requires a detached reader position");
720
+ await page.locator("#promptInput").focus();
721
+ const expectedSelection = await selectPreservedText(page);
722
+ const releaseIndependentPolls = await holdIndependentPollResponses(page);
723
+ const networkRequests = [];
724
+ const onRequest = (request) => networkRequests.push(`${request.method()} ${request.url()}`);
725
+ page.on("request", onRequest);
726
+ await installIsolationInstrumentation(page, { pauseChat: true });
727
+ await continueFixture(tabId, runId);
728
+ await waitForPhase(runId, "raw-start");
729
+ await waitForPhase(runId, "text-complete");
730
+ await expect.poll(() => page.evaluate(() => window.__piStreamIsolationDebug?.appliedIndexes?.length || 0)).toBe(deltaCount);
731
+ await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
732
+
733
+ // The Markdown renderer intentionally omits the delimiter-adjacent trailing
734
+ // newline from the code text node; every source character before it remains
735
+ // exact and the authoritative raw-output hash below covers the full string.
736
+ const expectedCode = finalText.slice("```js\n".length, finalText.lastIndexOf("```\n")).replace(/\n$/, "");
737
+ const liveMarkdown = page.locator(".message.assistant.streaming .streaming-markdown").last();
738
+ await expect(liveMarkdown).toContainText("LONG-STREAM-TAIL");
739
+ assert.equal(await liveMarkdown.locator("code").textContent(), expectedCode, "live fenced source must remain exact");
740
+
741
+ const metrics = await finishIsolationInstrumentation(page);
742
+ page.off("request", onRequest);
743
+ await releaseIndependentPolls();
744
+ assertIsolationMetrics(metrics, networkRequests, "long-transcript-active-stream", expectedSelection);
745
+ assert.equal(metrics.debug.counters.focusLossNearStreamBatch, 0);
746
+ assert.equal(metrics.debug.counters.detachedScrollMoves, 0);
747
+ assert.ok(metrics.debug.counters.transcriptNodeMax >= 1000, "node ledger must observe the retained transcript");
748
+ assert.ok(metrics.debug.counters.currentMessageNodeMax > 0, "node ledger must observe the active stream");
749
+ assert.ok(metrics.debug.counters.deriveCalls > 0, "derived-text diagnostics must be exercised");
750
+ assert.ok(metrics.debug.counters.markdownCommits > 0, "Markdown diagnostics must be exercised");
751
+ assert.equal(metrics.debug.counters.tokenizeCalls, 1, "the live open fence must skip accumulated syntax tokenization and highlight authoritatively once");
752
+
753
+ const records = metrics.debug.records;
754
+ const markdownRecords = records.filter((record) => record.type === "markdown-commit");
755
+ const tokenizeRecords = records.filter((record) => record.type === "tokenize");
756
+ const boundaryScannedChars = markdownRecords.reduce((sum, record) => sum + (Number(record.boundaryScannedChars) || 0), 0);
757
+ assert.equal(tokenizeRecords.length, 1, "only the authoritative fence close/completion may invoke the tokenizer");
758
+ assert.ok(boundaryScannedChars <= finalText.length, "incremental boundary work must not rescan the committed prefix");
759
+ const paintMs = records.filter((record) => record.type === "paint-opportunity").map((record) => Number(record.ms)).filter(Number.isFinite);
760
+ const markdownMs = markdownRecords.map((record) => Number(record.ms)).filter(Number.isFinite);
761
+ const tokenizeMs = tokenizeRecords.map((record) => Number(record.ms)).filter(Number.isFinite);
762
+ const longTaskMs = records.filter((record) => record.type === "longtask").map((record) => Number(record.ms)).filter(Number.isFinite);
763
+ const longFrameMs = records.filter((record) => record.type === "long-animation-frame").map((record) => Number(record.ms)).filter(Number.isFinite);
764
+ const environment = await page.evaluate(() => ({
765
+ userAgent: navigator.userAgent,
766
+ hardwareConcurrency: navigator.hardwareConcurrency,
767
+ deviceMemoryGiB: navigator.deviceMemory ?? null,
768
+ viewport: { width: innerWidth, height: innerHeight, devicePixelRatio },
769
+ }));
770
+ const counters = metrics.debug.counters;
771
+ const baseline = {
772
+ scenario: { retainedMessages: retainedMessageCount, sourceDeltaEvents: deltaCount, finalTextBytesUtf8: Buffer.byteLength(finalText), finalTextSha256: createHash("sha256").update(finalText).digest("hex") },
773
+ eventAndBatchCounts: { receivedEvents: counters.receivedEvents, appliedEvents: counters.appliedEvents, sinkCalls: counters.sinkCalls, batches: counters.batches, barriers: counters.barriers, overflows: counters.overflows },
774
+ receiptToPaintMs: { samples: paintMs.length, p50: percentileNearestRank(paintMs, 0.50), p95: percentileNearestRank(paintMs, 0.95), max: paintMs.length ? Math.max(...paintMs) : null },
775
+ longestCostsMs: { batchReceiptAge: counters.batchLatencyMaxMs, batchDrain: counters.batchDrainMaxMs, derive: counters.deriveMaxMs, tokenize: counters.tokenizeMaxMs, markdownCommit: counters.markdownCommitMaxMs, longTask: longTaskMs.length ? Math.max(...longTaskMs) : null, longAnimationFrame: longFrameMs.length ? Math.max(...longFrameMs) : null },
776
+ costInputs: { deriveCalls: counters.deriveCalls, deriveMaxBytes: counters.deriveMaxBytes, tokenizeCalls: counters.tokenizeCalls, tokenizeMaxBytes: counters.tokenizeMaxBytes, markdownCommits: counters.markdownCommits, tailMaxBytes: counters.tailMaxBytes },
777
+ queueHighWater: { entries: counters.highWaterPendingCount, bytes: counters.highWaterPendingBytes },
778
+ nodeMax: { transcript: counters.transcriptNodeMax, currentMessage: counters.currentMessageNodeMax },
779
+ continuity: { focusLossNearStreamBatch: counters.focusLossNearStreamBatch, detachedScrollMoves: counters.detachedScrollMoves },
780
+ environment: {
781
+ browserName: "chromium",
782
+ browserVersion: browser.version(),
783
+ ...environment,
784
+ node: process.version,
785
+ platform: process.platform,
786
+ architecture: process.arch,
787
+ hostname: hostname(),
788
+ kernelRelease: release(),
789
+ cpuModel: cpus()[0]?.model || "unknown",
790
+ logicalCpuCount: cpus().length,
791
+ totalMemoryBytes: totalmem(),
792
+ },
793
+ };
794
+ console.log(`WS0_STREAMING_BASELINE ${JSON.stringify(baseline)}`);
795
+ console.log(`WS2_STREAMING_CANDIDATE ${JSON.stringify({
796
+ ...baseline,
797
+ incrementalMarkdown: {
798
+ boundaryScannedChars,
799
+ tokenizeCalls: tokenizeRecords.length,
800
+ authoritativeCommits: markdownRecords.filter((record) => record.authoritative).length,
801
+ reusedTailCommits: markdownRecords.filter((record) => record.reusedTail).length,
802
+ markdownTotalMs: markdownMs.reduce((sum, value) => sum + value, 0),
803
+ tokenizeTotalMs: tokenizeMs.reduce((sum, value) => sum + value, 0),
804
+ },
805
+ })}`);
806
+
807
+ await expect.poll(
808
+ async () => (await serverApi(`/api/state?tab=${encodeURIComponent(tabId)}`)).data?.isStreaming,
809
+ { timeout: 30_000 },
810
+ ).toBe(false);
811
+ const settled = page.locator(".message.assistant:not(.streaming) .markdown-body", { hasText: "LONG-STREAM-TAIL" }).last();
812
+ await expect(settled).toContainText("LONG-STREAM-TAIL");
813
+ assert.equal(await settled.locator("code").textContent(), expectedCode, "settled fenced source must remain exact");
814
+ await assertFixtureContract(runId, "normal", "long-transcript");
815
+ });