@firstpick/pi-package-webui 0.8.4 → 0.8.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 (50) hide show
  1. package/README.md +24 -2
  2. package/bin/pi-webui.mjs +383 -31
  3. package/index.ts +8 -1
  4. package/lib/git-workflow-preferences.mjs +3 -0
  5. package/lib/session-summary-core.mjs +4 -3
  6. package/lib/trust-boundaries.mjs +13 -0
  7. package/lib/workspace-session-summaries.mjs +400 -0
  8. package/package.json +2 -2
  9. package/public/app.js +1242 -267
  10. package/public/index.html +77 -4
  11. package/public/service-worker.js +3 -1
  12. package/public/stream-output-controller.mjs +327 -0
  13. package/public/styles.css +249 -70
  14. package/public/theme-contract.mjs +244 -0
  15. package/session-summary.ts +164 -4
  16. package/tests/aur-review-widget-static.test.mjs +2 -1
  17. package/tests/boot-failure-diagnostics.test.mjs +2 -2
  18. package/tests/browser/interaction-continuity.spec.mjs +2 -2
  19. package/tests/browser/session-summary.spec.mjs +131 -3
  20. package/tests/browser/stream-output-isolation.spec.mjs +510 -0
  21. package/tests/codex-fast-mode-static.test.mjs +2 -2
  22. package/tests/composer-action-grid-reorder-static.test.mjs +2 -2
  23. package/tests/fast-mode-client-static.test.mjs +3 -2
  24. package/tests/feature-decision-output-popup-static.test.mjs +1 -1
  25. package/tests/fixtures/fake-pi.mjs +203 -2
  26. package/tests/git-workflow-preferences.test.mjs +7 -1
  27. package/tests/guided-git-aur-review.test.mjs +4 -3
  28. package/tests/http-endpoints-harness.test.mjs +224 -13
  29. package/tests/mobile-continuity-tablet-static.test.mjs +2 -2
  30. package/tests/mobile-foundation-static.test.mjs +3 -4
  31. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  32. package/tests/mobile-static.test.mjs +63 -29
  33. package/tests/native-parity.test.mjs +1 -1
  34. package/tests/open-issue-wizard-static.test.mjs +2 -3
  35. package/tests/optional-feature-migration-frontend.test.mjs +3 -0
  36. package/tests/persistent-ui-layout-static.test.mjs +2 -2
  37. package/tests/questionnaire-dialog.test.mjs +2 -2
  38. package/tests/remote-auth-settings-harness.test.mjs +9 -0
  39. package/tests/session-summary-core.test.mjs +183 -1
  40. package/tests/side-panel-section-reorder-static.test.mjs +2 -2
  41. package/tests/stream-lifecycle-core.test.mjs +134 -0
  42. package/tests/stream-output-controller.test.mjs +252 -0
  43. package/tests/stream-output-isolation-static.test.mjs +89 -0
  44. package/tests/streaming-ui-coupling.test.mjs +50 -0
  45. package/tests/subagent-gate-visibility.test.mjs +1 -1
  46. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  47. package/tests/theme-contract.test.mjs +104 -0
  48. package/tests/theme-customizer-static.test.mjs +82 -0
  49. package/tests/theme-scheme-mode.test.mjs +15 -0
  50. package/tests/workspace-session-summaries.test.mjs +288 -0
@@ -0,0 +1,510 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { createServer } from "node:net";
4
+ import { mkdtemp, readFile, rm } 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
+ const deltaCount = 1_000;
15
+ const expectedIndexes = Array.from({ length: deltaCount }, (_, index) => index);
16
+ const expectedFinalText = expectedIndexes.map((index) => {
17
+ const digit = String(index % 10);
18
+ if (index === 0) return `ISOLATION-TEXT-BEGIN ${digit}`;
19
+ if (index === deltaCount - 1) return `${digit} ISOLATION-TEXT-TAIL`;
20
+ return digit;
21
+ }).join("");
22
+
23
+ async function freePort() {
24
+ const server = createServer();
25
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
26
+ const { port } = server.address();
27
+ await new Promise((resolve) => server.close(resolve));
28
+ return port;
29
+ }
30
+
31
+ let child;
32
+ let baseURL;
33
+ let tempRoot;
34
+ let logRoot;
35
+ let logFile;
36
+ let output = "";
37
+
38
+ async function serverApi(pathname, { method = "GET", data } = {}) {
39
+ const response = await fetch(`${baseURL}${pathname}`, {
40
+ method,
41
+ headers: data === undefined ? undefined : { "content-type": "application/json" },
42
+ body: data === undefined ? undefined : JSON.stringify(data),
43
+ signal: AbortSignal.timeout(8_000),
44
+ });
45
+ const payload = await response.json().catch(() => ({}));
46
+ assert.equal(response.ok, true, `${method} ${pathname} should succeed: ${payload.error || output}`);
47
+ return payload;
48
+ }
49
+
50
+ async function activeTabId(page) {
51
+ return page.locator("#tabBar [role=\"tab\"][aria-selected=\"true\"]").evaluate((node) => node.closest("[data-tab-id]")?.dataset.tabId || "");
52
+ }
53
+
54
+ async function fixtureLogEntries(runId) {
55
+ const text = await readFile(logFile, "utf8").catch(() => "");
56
+ const entries = [];
57
+ for (const line of text.split("\n")) {
58
+ if (!line) continue;
59
+ try { entries.push(JSON.parse(line)); } catch { /* Ignore only the concurrently appended trailing row. */ }
60
+ }
61
+ return entries.filter((entry) => entry.isolationRunId === runId);
62
+ }
63
+
64
+ async function waitForFixtureLog(runId, predicate) {
65
+ let matching = [];
66
+ await expect.poll(async () => {
67
+ matching = await fixtureLogEntries(runId);
68
+ return predicate(matching);
69
+ }).toBe(true);
70
+ return matching;
71
+ }
72
+
73
+ async function waitForPhase(runId, phase) {
74
+ return waitForFixtureLog(runId, (entries) => entries.some((entry) => entry.direction === "isolation-phase" && entry.isolationPhase === phase));
75
+ }
76
+
77
+ async function assertFixtureContract(runId, mode, scenario = "standard") {
78
+ 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");
80
+ const expectedCount = scenario === "abort" ? 500 : deltaCount;
81
+ assert.equal(textDeltas.length, expectedCount, `${mode}/${scenario} fixture must emit the expected non-empty text deltas`);
82
+ assert.deepEqual(textDeltas.map((entry) => entry.isolationDeltaIndex), expectedIndexes.slice(0, expectedCount));
83
+ assert.ok(entries.some((entry) => entry.direction === "isolation-phase" && entry.isolationPhase === "raw-start"));
84
+ if (scenario !== "abort") assert.ok(entries.some((entry) => entry.direction === "isolation-phase" && entry.isolationPhase === "raw-end"));
85
+ }
86
+
87
+ async function selectPreservedText(page, { modal = false } = {}) {
88
+ const expected = modal ? "Confirm action" : "fake answer";
89
+ const target = modal
90
+ ? page.locator("#confirmationTitle")
91
+ : page.locator(".message.assistant:not(.streaming) .markdown-body", { hasText: expected }).first();
92
+ await expect(target).toContainText(expected);
93
+ const selected = await target.evaluate((root, text) => {
94
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
95
+ while (walker.nextNode()) {
96
+ const node = walker.currentNode;
97
+ const start = node.data.indexOf(text);
98
+ if (start < 0) continue;
99
+ const range = document.createRange();
100
+ range.setStart(node, start);
101
+ range.setEnd(node, start + text.length);
102
+ const selection = window.getSelection();
103
+ selection.removeAllRanges();
104
+ selection.addRange(range);
105
+ return selection.toString();
106
+ }
107
+ return "";
108
+ }, expected);
109
+ assert.equal(selected, expected);
110
+ return expected;
111
+ }
112
+
113
+ async function prepareInteractiveState(page, {
114
+ viewport = { width: 1280, height: 720 },
115
+ modal = false,
116
+ dropdown = false,
117
+ pauseChat = false,
118
+ } = {}) {
119
+ await page.setViewportSize(viewport);
120
+ await page.goto(`${baseURL}/?streamIsolationDebug=1`);
121
+ await expect(page.locator("#promptInput")).toBeVisible();
122
+ await page.waitForTimeout(500);
123
+ await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
124
+ await page.addStyleTag({ content: "#chat > .message { min-height: 10rem; }" });
125
+
126
+ if (viewport.width >= 700) {
127
+ const sideScroll = await page.locator("#sidePanel .side-panel-body").evaluate((node) => {
128
+ node.scrollTop = Math.min(120, Math.max(0, node.scrollHeight - node.clientHeight));
129
+ return node.scrollTop;
130
+ });
131
+ assert.ok(sideScroll > 0, `desktop proof requires a real side-panel reader position, got ${sideScroll}`);
132
+ }
133
+
134
+ if (pauseChat) {
135
+ const pausedTop = await page.locator("#chat").evaluate((node) => {
136
+ node.style.scrollBehavior = "auto";
137
+ node.scrollTop = node.scrollHeight;
138
+ node.dispatchEvent(new WheelEvent("wheel", { deltaY: -160, bubbles: true }));
139
+ node.scrollTop = Math.max(1, node.scrollHeight - node.clientHeight - 160);
140
+ node.dispatchEvent(new Event("scroll", { bubbles: true }));
141
+ node.style.removeProperty("scroll-behavior");
142
+ return node.scrollTop;
143
+ });
144
+ assert.ok(pausedTop > 0);
145
+ }
146
+
147
+ if (modal) {
148
+ await page.locator("#confirmationDialog").evaluate((dialog) => dialog.showModal());
149
+ await page.locator("#confirmationCancelButton").focus();
150
+ await expect(page.locator("#confirmationDialog")).toHaveAttribute("open", "");
151
+ } else if (dropdown) {
152
+ await page.locator("#newTabButton").click();
153
+ await expect(page.locator("#newTabButton")).toHaveAttribute("aria-expanded", "true");
154
+ } else {
155
+ await page.locator("#promptInput").focus();
156
+ }
157
+ return selectPreservedText(page, { modal });
158
+ }
159
+
160
+ async function installIsolationInstrumentation(page, { pauseChat = false } = {}) {
161
+ await page.evaluate(({ shouldPauseChat }) => {
162
+ const ledger = window.__piStreamIsolationDebug;
163
+ if (!ledger) throw new Error("stream-isolation debug ledger is unavailable");
164
+ for (const key of Object.keys(ledger.counters)) ledger.counters[key] = 0;
165
+ for (const key of ["receivedIndexes", "appliedIndexes", "records", "unknownEvidence"]) ledger[key].length = 0;
166
+
167
+ const identitySelectors = [
168
+ "html", "body", "#tabBar", "#newTabMenu", "#newTabButton", "#widgetArea",
169
+ "#feedbackTray", "#statusBar", "#contextMeterBar", "#gitWorkflowPanel", "#composer",
170
+ "#promptInput", "#abortButton", "#steerButton", "#followUpButton", "#sidePanel", "#fileViewerPane", "#eventLog",
171
+ "#confirmationDialog", "#confirmationCancelButton",
172
+ ];
173
+ const describe = (node) => {
174
+ const element = node?.nodeType === Node.ELEMENT_NODE ? node : node?.parentElement;
175
+ if (!element) return String(node?.nodeName || "unknown");
176
+ return `${element.tagName.toLowerCase()}${element.id ? `#${element.id}` : ""}${element.classList?.length ? `.${[...element.classList].slice(0, 3).join(".")}` : ""}`;
177
+ };
178
+ const underTranscript = (node) => (node?.nodeType === Node.ELEMENT_NODE ? node : node?.parentElement)?.closest?.("#chat") !== null;
179
+ const allowedFollowMutation = (record) => record.type === "attributes" && record.attributeName === "hidden" && record.target === document.querySelector("#jumpToLatestButton");
180
+ const scrollNodes = [...document.querySelectorAll("*")].filter((node) => {
181
+ if (node.closest?.("#chat")) return false;
182
+ return node === document.scrollingElement || node.scrollHeight > node.clientHeight || node.scrollWidth > node.clientWidth || node.scrollTop !== 0 || node.scrollLeft !== 0;
183
+ });
184
+ if (document.scrollingElement && !scrollNodes.includes(document.scrollingElement)) scrollNodes.push(document.scrollingElement);
185
+ const proof = {
186
+ allowedMutations: { attributes: 0, characterData: 0, childList: 0 },
187
+ allowedFollowMutations: 0,
188
+ forbiddenMutations: { attributes: 0, characterData: 0, childList: 0 },
189
+ forbiddenMutationExamples: [],
190
+ focusEvents: [], focusCalls: [], scrollIntoViewCalls: [], fetchCalls: [], eventSourceConstructions: [],
191
+ activeElement: document.activeElement,
192
+ activeElementDescription: describe(document.activeElement),
193
+ selectionText: window.getSelection()?.toString() || "",
194
+ selectionAnchor: window.getSelection()?.anchorNode || null,
195
+ selectionFocus: window.getSelection()?.focusNode || null,
196
+ identities: identitySelectors.map((selector) => ({ selector, node: document.querySelector(selector) })).filter(({ node }) => node),
197
+ scrolls: scrollNodes.map((node) => ({ node, top: node.scrollTop, left: node.scrollLeft, label: describe(node) })),
198
+ chatTop: document.querySelector("#chat")?.scrollTop || 0,
199
+ pauseChat: shouldPauseChat,
200
+ };
201
+ proof.recordMutations = (records) => {
202
+ for (const record of records) {
203
+ if (underTranscript(record.target)) proof.allowedMutations[record.type] += 1;
204
+ else if (allowedFollowMutation(record)) proof.allowedFollowMutations += 1;
205
+ else {
206
+ proof.forbiddenMutations[record.type] += 1;
207
+ if (proof.forbiddenMutationExamples.length < 20) proof.forbiddenMutationExamples.push(`${record.type}:${describe(record.target)}:${record.attributeName || ""}`);
208
+ }
209
+ }
210
+ };
211
+ proof.originalFocus = HTMLElement.prototype.focus;
212
+ HTMLElement.prototype.focus = function (...args) { proof.focusCalls.push(describe(this)); return proof.originalFocus.apply(this, args); };
213
+ proof.originalScrollIntoView = Element.prototype.scrollIntoView;
214
+ Element.prototype.scrollIntoView = function (...args) { proof.scrollIntoViewCalls.push(describe(this)); return proof.originalScrollIntoView?.apply(this, args); };
215
+ proof.originalFetch = window.fetch;
216
+ window.fetch = function (...args) { proof.fetchCalls.push(String(args[0])); return proof.originalFetch.apply(this, args); };
217
+ proof.originalEventSource = window.EventSource;
218
+ window.EventSource = new Proxy(proof.originalEventSource, {
219
+ construct(target, args, receiver) { proof.eventSourceConstructions.push(String(args[0])); return Reflect.construct(target, args, receiver); },
220
+ });
221
+ proof.onFocus = (event) => proof.focusEvents.push(`${event.type}:${describe(event.target)}`);
222
+ document.addEventListener("focusin", proof.onFocus, true);
223
+ document.addEventListener("focusout", proof.onFocus, true);
224
+ proof.observer = new MutationObserver(proof.recordMutations);
225
+ proof.observer.observe(document.documentElement, { subtree: true, childList: true, characterData: true, attributes: true });
226
+ window.__streamIsolationProof = proof;
227
+ }, { shouldPauseChat: pauseChat });
228
+ }
229
+
230
+ async function finishIsolationInstrumentation(page) {
231
+ return page.evaluate(() => {
232
+ const proof = window.__streamIsolationProof;
233
+ proof.recordMutations(proof.observer.takeRecords());
234
+ proof.observer.disconnect();
235
+ document.removeEventListener("focusin", proof.onFocus, true);
236
+ document.removeEventListener("focusout", proof.onFocus, true);
237
+ HTMLElement.prototype.focus = proof.originalFocus;
238
+ Element.prototype.scrollIntoView = proof.originalScrollIntoView;
239
+ window.fetch = proof.originalFetch;
240
+ window.EventSource = proof.originalEventSource;
241
+ const identityChanges = proof.identities.filter(({ selector, node }) => document.querySelector(selector) !== node || !node.isConnected).map(({ selector }) => selector);
242
+ const scrollChanges = proof.scrolls.filter(({ node, top, left }) => node.isConnected && (node.scrollTop !== top || node.scrollLeft !== left)).map(({ label, node, top, left }) => ({ label, before: [top, left], after: [node.scrollTop, node.scrollLeft] }));
243
+ const ledger = window.__piStreamIsolationDebug;
244
+ return {
245
+ allowedMutations: proof.allowedMutations,
246
+ allowedFollowMutations: proof.allowedFollowMutations,
247
+ forbiddenMutations: proof.forbiddenMutations,
248
+ forbiddenMutationExamples: proof.forbiddenMutationExamples,
249
+ focusEvents: proof.focusEvents,
250
+ focusCalls: proof.focusCalls,
251
+ scrollIntoViewCalls: proof.scrollIntoViewCalls,
252
+ fetchCalls: proof.fetchCalls,
253
+ eventSourceConstructions: proof.eventSourceConstructions,
254
+ activeElementChanged: document.activeElement !== proof.activeElement,
255
+ activeElementBefore: proof.activeElementDescription,
256
+ activeElementAfter: document.activeElement ? `${document.activeElement.tagName.toLowerCase()}#${document.activeElement.id || ""}` : "none",
257
+ identityChanges,
258
+ scrollChanges,
259
+ chatTopBefore: proof.chatTop,
260
+ chatTopAfter: document.querySelector("#chat")?.scrollTop || 0,
261
+ pauseChat: proof.pauseChat,
262
+ selectionBefore: proof.selectionText,
263
+ selectionAfter: window.getSelection()?.toString() || "",
264
+ selectionNodesConnected: proof.selectionAnchor?.isConnected === true && proof.selectionFocus?.isConnected === true,
265
+ debug: {
266
+ counters: { ...ledger.counters },
267
+ receivedIndexes: [...ledger.receivedIndexes],
268
+ appliedIndexes: [...ledger.appliedIndexes],
269
+ },
270
+ };
271
+ });
272
+ }
273
+
274
+ function isIndependentPollRequest(value) {
275
+ try {
276
+ return ["/api/tabs", "/api/state", "/api/subagents"].includes(new URL(String(value), baseURL).pathname);
277
+ } catch {
278
+ return false;
279
+ }
280
+ }
281
+
282
+ async function holdIndependentPollResponses(page) {
283
+ const held = [];
284
+ const matcher = /\/api\/(?:tabs|state|subagents)(?:\?|$)/;
285
+ const handler = (route) => { held.push(route); };
286
+ await page.route(matcher, handler);
287
+ return async () => {
288
+ await page.unroute(matcher, handler);
289
+ await Promise.allSettled(held.splice(0).map((route) => route.continue()));
290
+ };
291
+ }
292
+
293
+ function assertIsolationMetrics(metrics, networkRequests, surface, expectedSelection, expectedIndexCount = deltaCount) {
294
+ assert.deepEqual(metrics.forbiddenMutations, { attributes: 0, characterData: 0, childList: 0 }, `${surface}: ${metrics.forbiddenMutationExamples.join(", ")}`);
295
+ assert.deepEqual(metrics.focusEvents, []);
296
+ assert.deepEqual(metrics.focusCalls, []);
297
+ assert.deepEqual(metrics.scrollIntoViewCalls, []);
298
+ assert.deepEqual(metrics.fetchCalls.filter((url) => !isIndependentPollRequest(url)), [], `${surface}: raw deltas initiated fetch calls`);
299
+ assert.deepEqual(metrics.eventSourceConstructions, []);
300
+ assert.equal(metrics.activeElementChanged, false, `${surface}: active element changed from ${metrics.activeElementBefore} to ${metrics.activeElementAfter}`);
301
+ assert.deepEqual(metrics.identityChanges, []);
302
+ assert.deepEqual(metrics.scrollChanges, []);
303
+ if (metrics.pauseChat) assert.equal(metrics.chatTopAfter, metrics.chatTopBefore);
304
+ assert.equal(metrics.selectionBefore, expectedSelection);
305
+ assert.equal(metrics.selectionAfter, expectedSelection);
306
+ assert.equal(metrics.selectionNodesConnected, true);
307
+ const deltaTriggeredRequests = networkRequests.filter((request) => !isIndependentPollRequest(request.split(" ").slice(1).join(" ")));
308
+ assert.deepEqual(deltaTriggeredRequests, [], `${surface}: raw deltas initiated page requests`);
309
+ assert.ok(Object.values(metrics.allowedMutations).some((count) => count > 0));
310
+ assert.deepEqual(metrics.debug.receivedIndexes, expectedIndexes.slice(0, expectedIndexCount), `${surface}: browser receipt indexes must be complete`);
311
+ assert.deepEqual(metrics.debug.appliedIndexes, expectedIndexes.slice(0, expectedIndexCount), `${surface}: browser application indexes must be complete`);
312
+ assert.ok(metrics.debug.counters.sinkCalls <= 16, `${surface}: controller should batch transcript sinks, got ${metrics.debug.counters.sinkCalls}`);
313
+ assert.ok(metrics.debug.counters.highWaterPendingCount <= 8, `${surface}: pending high-water should remain bounded, got ${metrics.debug.counters.highWaterPendingCount}`);
314
+ assert.equal(metrics.debug.counters.overflows, 0, `${surface}: normal proof must not overflow the bounded accumulator`);
315
+ }
316
+
317
+ async function startFixture(page, mode, scenario = "standard") {
318
+ const tabId = await activeTabId(page);
319
+ const response = await serverApi(`/api/prompt?tab=${encodeURIComponent(tabId)}`, {
320
+ method: "POST",
321
+ data: { message: `fixture stream isolation ${mode} ${scenario}`, requestId: `stream-isolation-${mode}-${scenario}-${Date.now()}` },
322
+ });
323
+ assert.equal(response.data?.deltaCount, deltaCount);
324
+ assert.equal(response.data?.finalText, expectedFinalText);
325
+ await waitForPhase(response.data.runId, "ready");
326
+ await expect(page.locator("#abortButton")).toBeVisible();
327
+ await expect(page.locator(".message.toolExecution").last()).toContainText("read");
328
+ // The fixture does not start raw output until the test sends an explicit
329
+ // steer. Drain independent lifecycle/subagent polls first so the observed
330
+ // window contains only the requested raw stream.
331
+ const waitForRequestPath = (pathname) => new Promise((resolve) => {
332
+ const timer = setTimeout(() => { page.off("requestfinished", onFinished); resolve(); }, 6_000);
333
+ const onFinished = (request) => {
334
+ if (new URL(request.url()).pathname !== pathname) return;
335
+ clearTimeout(timer); page.off("requestfinished", onFinished); resolve();
336
+ };
337
+ page.on("requestfinished", onFinished);
338
+ });
339
+ await Promise.all([waitForRequestPath("/api/tabs"), waitForRequestPath("/api/subagents")]);
340
+ // The optional-feature ready card owns an independent auto-dismiss timer.
341
+ // Synchronize on its semantic end state so it cannot be mistaken for a
342
+ // stream-delta-caused chrome mutation in the observed window.
343
+ await expect(page.locator("#optionalFeatureMigrationSurface")).toBeHidden();
344
+ await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
345
+ return { tabId, runId: response.data.runId };
346
+ }
347
+
348
+ async function continueFixture(tabId, runId) {
349
+ await serverApi(`/api/steer?tab=${encodeURIComponent(tabId)}`, {
350
+ method: "POST",
351
+ data: { message: `fixture stream isolation continue ${runId}` },
352
+ });
353
+ }
354
+
355
+ async function waitForRawDrain(page, runId, expectedCount = deltaCount) {
356
+ await waitForPhase(runId, expectedCount === deltaCount ? "raw-end" : "abort-ready");
357
+ await expect.poll(() => page.evaluate(() => window.__piStreamIsolationDebug?.appliedIndexes?.length || 0)).toBe(expectedCount);
358
+ await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
359
+ }
360
+
361
+ async function waitForSettlement(page, tabId) {
362
+ await expect.poll(async () => (await serverApi(`/api/state?tab=${encodeURIComponent(tabId)}`)).data?.isStreaming).toBe(false);
363
+ const settled = page.locator(".message.assistant:not(.streaming) .markdown-body", { hasText: "ISOLATION-TEXT-TAIL" }).last();
364
+ await expect(settled).toContainText("ISOLATION-TEXT-BEGIN");
365
+ assert.equal((await settled.textContent()).trim(), expectedFinalText);
366
+ }
367
+
368
+ test.describe.configure({ mode: "serial" });
369
+
370
+ test.beforeAll(async () => {
371
+ const port = await freePort();
372
+ tempRoot = await mkdtemp(join(tmpdir(), "pi-webui-stream-isolation-"));
373
+ logRoot = await mkdtemp(join(tmpdir(), "pi-webui-stream-isolation-log-"));
374
+ logFile = join(logRoot, "fake-pi.jsonl");
375
+ baseURL = `http://127.0.0.1:${port}`;
376
+ child = spawn(process.execPath, [serverScript, "--cwd", tempRoot, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
377
+ stdio: ["ignore", "pipe", "pipe"],
378
+ env: { ...process.env, PI_WEBUI_RPC_SUPERVISOR: "0", PI_CODING_AGENT_DIR: join(tempRoot, "agent"), PI_WEBUI_SETTINGS_FILE: join(tempRoot, "settings.json"), FAKE_PI_LOG_FILE: logFile, FAKE_PI_STREAM_ISOLATION: "1" },
379
+ });
380
+ child.stdout.on("data", (chunk) => { output += String(chunk); });
381
+ child.stderr.on("data", (chunk) => { output += String(chunk); });
382
+ for (let attempt = 0; attempt < 80; attempt += 1) {
383
+ if (child.exitCode !== null) break;
384
+ try { if ((await fetch(`${baseURL}/api/health`, { signal: AbortSignal.timeout(500) })).ok) return; } catch {}
385
+ await delay(100);
386
+ }
387
+ throw new Error(`Pi Web UI did not start:\n${output}`);
388
+ });
389
+
390
+ test.afterAll(async () => {
391
+ if (child?.exitCode === null) { const exited = new Promise((resolve) => child.once("exit", resolve)); child.kill("SIGTERM"); await exited; }
392
+ await Promise.all([rm(tempRoot, { recursive: true, force: true }), rm(logRoot, { recursive: true, force: true })]);
393
+ });
394
+
395
+ async function runIsolationCase(page, { mode, viewport, modal = false, dropdown = false, pauseChat = false, label }) {
396
+ await serverApi("/api/webui-output-mode", { method: "PUT", data: { outputModeDefault: mode === "compact" ? "compact-v1" : "normal" } });
397
+ const expectedSelection = await prepareInteractiveState(page, { viewport, modal, dropdown, pauseChat });
398
+ const { tabId, runId } = await startFixture(page, mode);
399
+ const releaseIndependentPolls = await holdIndependentPollResponses(page);
400
+ const networkRequests = [];
401
+ const onRequest = (request) => networkRequests.push(`${request.method()} ${request.url()}`);
402
+ page.on("request", onRequest);
403
+ await installIsolationInstrumentation(page, { pauseChat });
404
+ await continueFixture(tabId, runId);
405
+ await waitForPhase(runId, "raw-start");
406
+ await waitForPhase(runId, "text-complete");
407
+ if (mode === "normal") {
408
+ await expect(page.locator(".message.assistant.streaming .streaming-markdown").last()).toContainText("ISOLATION-TEXT-TAIL");
409
+ } else {
410
+ await expect(page.locator(".message.compact-live-output .compact-live-text").last()).toContainText("ISOLATION-TEXT-TAIL");
411
+ }
412
+ await waitForRawDrain(page, runId);
413
+ if (mode === "normal") {
414
+ await expect(page.locator(".message.toolExecution").last()).toContainText("ISOLATION-TOOL-UPDATE-COMPLETE");
415
+ } else {
416
+ await expect(page.locator(".compact-tool-shell")).toHaveCount(0);
417
+ await expect(page.locator("#chat")).not.toContainText("ISOLATION-TOOL-UPDATE-COMPLETE");
418
+ }
419
+ const metrics = await finishIsolationInstrumentation(page);
420
+ page.off("request", onRequest);
421
+ await releaseIndependentPolls();
422
+ console.log(`stream-output-isolation raw metrics ${JSON.stringify({
423
+ mode,
424
+ label,
425
+ ...metrics,
426
+ debug: {
427
+ counters: metrics.debug.counters,
428
+ receivedCount: metrics.debug.receivedIndexes.length,
429
+ appliedCount: metrics.debug.appliedIndexes.length,
430
+ },
431
+ networkRequests,
432
+ })}`);
433
+ assertIsolationMetrics(metrics, networkRequests, label, expectedSelection);
434
+ if (mode === "compact") {
435
+ await waitForPhase(runId, "tool-complete");
436
+ await expect(page.locator(".compact-tool-shell .compact-tool-status").last()).toHaveText("done");
437
+ }
438
+ await waitForSettlement(page, tabId);
439
+ await assertFixtureContract(runId, mode);
440
+ }
441
+
442
+ test("desktop normal stream output isolation", async ({ page }) => runIsolationCase(page, { mode: "normal", viewport: { width: 1280, height: 720 }, dropdown: true, label: "desktop-normal" }));
443
+ test("desktop compact isolation preserves paused reader and modal", async ({ page }) => runIsolationCase(page, { mode: "compact", viewport: { width: 1280, height: 720 }, modal: true, pauseChat: true, label: "desktop-compact" }));
444
+ test("mobile 390x844 normal isolation", async ({ page }) => runIsolationCase(page, { mode: "normal", viewport: { width: 390, height: 844 }, label: "mobile-390" }));
445
+ test("mobile 320x568 compact isolation", async ({ page }) => runIsolationCase(page, { mode: "compact", viewport: { width: 320, height: 568 }, pauseChat: true, label: "mobile-320" }));
446
+
447
+ test("abort flushes and preserves the partial text tail before lifecycle chrome settles", async ({ page }) => {
448
+ await serverApi("/api/webui-output-mode", { method: "PUT", data: { outputModeDefault: "normal" } });
449
+ const expectedSelection = await prepareInteractiveState(page, { viewport: { width: 1280, height: 720 } });
450
+ const { tabId, runId } = await startFixture(page, "normal", "abort");
451
+ const indicator = await page.locator(".run-indicator-message").elementHandle();
452
+ const releaseIndependentPolls = await holdIndependentPollResponses(page);
453
+ const requests = [];
454
+ const onRequest = (request) => requests.push(`${request.method()} ${request.url()}`);
455
+ page.on("request", onRequest);
456
+ await installIsolationInstrumentation(page);
457
+ await continueFixture(tabId, runId);
458
+ await waitForRawDrain(page, runId, 500);
459
+ await expect(page.locator(".message.assistant.streaming .streaming-markdown").last()).toContainText("ISOLATION-TEXT-BEGIN");
460
+ const metrics = await finishIsolationInstrumentation(page);
461
+ page.off("request", onRequest);
462
+ await releaseIndependentPolls();
463
+ assertIsolationMetrics(metrics, requests, "abort-partial", expectedSelection, 500);
464
+ const barriersBeforeAbort = await page.evaluate(() => window.__piStreamIsolationDebug?.counters?.barriers || 0);
465
+ assert.equal(await indicator.evaluate((node) => node.isConnected), true, "wording updates must retain the run-indicator node");
466
+ const abortButton = page.locator("#abortButton");
467
+ await abortButton.hover();
468
+ await page.mouse.down();
469
+ await page.waitForTimeout(3_200);
470
+ await page.mouse.up();
471
+ await expect.poll(async () => (await serverApi(`/api/state?tab=${encodeURIComponent(tabId)}`)).data?.isStreaming).toBe(false);
472
+ await expect.poll(() => page.evaluate(() => window.__piStreamIsolationDebug?.counters?.barriers || 0)).toBeGreaterThan(barriersBeforeAbort);
473
+ await expect(page.locator("#abortButton")).toBeHidden();
474
+ await assertFixtureContract(runId, "normal", "abort");
475
+ });
476
+
477
+ test("retry compaction reconnect and settlement retain lifecycle control identity", async ({ page }) => {
478
+ await serverApi("/api/webui-output-mode", { method: "PUT", data: { outputModeDefault: "normal" } });
479
+ const expectedSelection = await prepareInteractiveState(page, { viewport: { width: 1280, height: 720 } });
480
+ const { tabId, runId } = await startFixture(page, "normal", "lifecycle");
481
+ const indicator = await page.locator(".run-indicator-message").elementHandle();
482
+ const abort = await page.locator("#abortButton").elementHandle();
483
+ const steer = await page.locator("#steerButton").elementHandle();
484
+ const followUp = await page.locator("#followUpButton").elementHandle();
485
+ const releaseIndependentPolls = await holdIndependentPollResponses(page);
486
+ const requests = [];
487
+ const onRequest = (request) => requests.push(`${request.method()} ${request.url()}`);
488
+ page.on("request", onRequest);
489
+ await installIsolationInstrumentation(page);
490
+ await continueFixture(tabId, runId);
491
+ await waitForRawDrain(page, runId);
492
+ const metrics = await finishIsolationInstrumentation(page);
493
+ page.off("request", onRequest);
494
+ await releaseIndependentPolls();
495
+ assertIsolationMetrics(metrics, requests, "lifecycle-raw", expectedSelection);
496
+ const barriersBeforeLifecycle = await page.evaluate(() => window.__piStreamIsolationDebug?.counters?.barriers || 0);
497
+ await continueFixture(tabId, runId);
498
+ await waitForPhase(runId, "lifecycle-complete");
499
+ await expect.poll(() => page.evaluate(() => window.__piStreamIsolationDebug?.counters?.barriers || 0)).toBeGreaterThanOrEqual(barriersBeforeLifecycle + 4);
500
+ assert.equal(await indicator.evaluate((node) => node.isConnected), true);
501
+ assert.equal(await abort.evaluate((node) => node.isConnected && !node.hidden), true);
502
+ assert.equal(await steer.evaluate((node) => node.isConnected && !node.hidden && !node.disabled), true);
503
+ assert.equal(await followUp.evaluate((node) => node.isConnected && !node.hidden && !node.disabled), true);
504
+ await waitForSettlement(page, tabId);
505
+ await expect(page.locator("#abortButton")).toBeHidden();
506
+ await expect(page.locator("#steerButton")).toBeHidden();
507
+ await expect(page.locator("#followUpButton")).toBeHidden();
508
+ assert.equal(await steer.evaluate((node) => node.isConnected), true, "Steer must retain node identity through settlement");
509
+ assert.equal(await followUp.evaluate((node) => node.isConnected), true, "Follow-up must retain node identity through settlement");
510
+ });
@@ -54,7 +54,7 @@ assert.match(app, /statusKey === CODEX_FAST_MODE_STATUS_KEY[\s\S]*?applyCodexFas
54
54
  assert.match(readme, /### Compact live output mode[\s\S]*?select \*\*Compact\*\*[\s\S]*?`compact-v1`/, "README should document Compact mode with the stable wire identifier");
55
55
  assert.match(readme, /### Codex subscription Fast mode[\s\S]*?service_tier: "priority"[\s\S]*?1\.5× faster[\s\S]*?2× Standard credits[\s\S]*?2\.5×/, "README should separately document subscription Fast mode and its cost semantics");
56
56
  // Intent preserved: browser-asset changes must advance the coherent cache tuple.
57
- assert.match(serviceWorker, /pi-webui-pwa-v71/, "PWA cache identity should be bumped for changed browser assets");
58
- assert.match(html, /data-app-src="\/app\.js\?v=112"/, "browser module URL should be cache-busted for Fast-mode wiring");
57
+ assert.match(serviceWorker, /pi-webui-pwa-v74/, "PWA cache identity should be bumped for changed browser assets");
58
+ assert.match(html, /data-app-src="\/app\.js\?v=113"/, "browser module URL should be cache-busted for Fast-mode wiring");
59
59
 
60
60
  console.log("codex-fast-mode-static.test.mjs passed");
@@ -57,7 +57,7 @@ assert.match(app, /event\.key === COMPOSER_ACTION_ORDER_STORAGE_KEY\) restoreCom
57
57
  assert.match(app, /initializeComposerActionOrdering\(\);[\s\S]*restoreSidePanelSectionOrder\(\);/, "composer ordering should initialize during guarded app startup");
58
58
 
59
59
  assert.match(html, /styles\.css\?v=98/, "changed composer styles should advance the stylesheet revision");
60
- assert.match(html, /app\.js\?v=112/, "changed composer behavior should advance the app revision");
61
- assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v71"/, "changed browser assets should advance the PWA cache identity");
60
+ assert.match(html, /app\.js\?v=113/, "changed composer behavior should advance the app revision");
61
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v74"/, "changed browser assets should advance the PWA cache identity");
62
62
 
63
63
  console.log("composer-action-grid-reorder-static.test.mjs passed");
@@ -91,7 +91,8 @@ assert.match(resetCompactLiveOutput, /clearCompactThinkingDisclosureState\("live
91
91
  assert.match(compactFlush, /compactThinkingNode\?\._rawThinkingText !== compactLiveState\.thinking[\s\S]*?renderThinkingMarkdown\(compactThinkingNode, compactLiveState\.thinking\)/, "compact live thinking should preserve Markdown formatting");
92
92
  assert.doesNotMatch(compactFlush, /compactThinkingNode\.textContent|renderStreamingMarkdown|renderToolExecution|normalizeToolExecution/, "compact thinking must not fall back to plain text or invoke rich tool renderers");
93
93
  assert.doesNotMatch(compactToolShell, /normalizeToolExecution|toolExecutionRenderSignature|renderToolExecution|handleToolExecutionUpdate|JSON\.stringify/, "compact tool shells must defer rich bodies and raw serialization");
94
- assert.match(app, /case "tool_execution_update":\s+if \(!compactOutputActive\(\)\) handleToolExecutionUpdate\(event\);/, "compact mode should not build intermediate rich tool updates");
94
+ assert.match(app, /applyToolExecutionUpdate: \(event\) => \{\s+if \(!compactOutputActive\(\)\) applyTranscriptToolExecutionUpdate\(event\);/, "compact mode should not build intermediate rich tool updates");
95
+ assert.doesNotMatch(app, /case "tool_execution_update":/, "raw tool updates should have only the controller-owned dispatch path");
95
96
  assert.match(app, /case "tool_execution_end":[\s\S]*?compactLiveScheduler\.flushNow\(\)[\s\S]*?renderCompactToolShell\(event, \{ complete: true \}\)[\s\S]*?finishCompactLiveOutput\(tabContext\)/, "compact tool completion should remain lightweight and request final reconciliation");
96
97
  assert.match(resetStream, /resetCompactLiveOutput\(\{ remove: !preserveCompact \}\)/, "reset and tab changes should cancel compact pending work while exact compact settlement may retain its adopted owner");
97
98
  assert.match(app, /case "message_end": \{\s+if \(compactOutputActive\(\)\) finishCompactLiveOutput\(tabContext\);/, "message ends should synchronously flush compact output before reconciliation");
@@ -155,7 +156,7 @@ assert.match(worker, /pi-webui-pwa-v\d+[\s\S]*?"\/fast-output-live\.mjs"/, "PWA
155
156
  assert.match(html, /<label for="fastOutputModeSelect">Compact mode \(Experimental\)<\/label>/, "the sidebar should mark compact mode as experimental");
156
157
  assert.match(html, /Lightweight browser rendering; Markdown final output; live thinking expanded; stored thinking grouped and collapsed/, "the sidebar should distinguish compact rendering from model inference");
157
158
  // Intent preserved: the guarded PWA entry point must advance whenever app wiring changes.
158
- assert.match(html, /id="webuiBootLoader"[^>]*data-app-src="\/app\.js\?v=112"/, "the guarded PWA entry point should cache-bust browser wiring");
159
+ assert.match(html, /id="webuiBootLoader"[^>]*data-app-src="\/app\.js\?v=113"/, "the guarded PWA entry point should cache-bust browser wiring");
159
160
  assert.match(JSON.parse(packageRaw).scripts.check, /node --check public\/fast-output-live\.mjs/, "package checks should parse the compact helper");
160
161
 
161
162
  const events = createFastModeOutputEvents();
@@ -167,6 +167,6 @@ assert.match(app, /case "webui_connected":[\s\S]*clearFeatureDecisionStateForTab
167
167
  assert.match(app, /statusKey === FEATURE_DECISION_OUTPUT_STATUS_KEY[\s\S]*handleFeatureDecisionOutputStatus[\s\S]*return;[\s\S]*statusKey === FEATURE_CATEGORY_STATUS_KEY[\s\S]*return;[\s\S]*statusEntries\.set/, "both feature statuses should be intercepted before generic footer storage while preserving category handling");
168
168
 
169
169
  assert.match(html, /\/styles\.css\?v=98/, "integrated stylesheet changes should advance the cache query");
170
- assert.match(html, /\/app\.js\?v=112/, "integrated app changes should advance the cache query");
170
+ assert.match(html, /\/app\.js\?v=113/, "integrated app changes should advance the cache query");
171
171
 
172
172
  console.log("feature decision-output popup static checks passed");