@firstpick/pi-package-webui 0.8.5 → 0.8.7

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 (110) hide show
  1. package/README.md +18 -584
  2. package/bin/pi-webui-launcher.mjs +22 -0
  3. package/bin/pi-webui-update-supervisor.mjs +86 -0
  4. package/bin/pi-webui.mjs +933 -554
  5. package/index.ts +16 -6
  6. package/lib/component-update-state.mjs +21 -0
  7. package/lib/git-workflow-preferences.mjs +20 -2
  8. package/lib/optional-feature-catalog.mjs +1 -0
  9. package/lib/sampling-parameter-capabilities.mjs +160 -0
  10. package/lib/session-summary-core.mjs +4 -3
  11. package/lib/session-summary-preferences.mjs +16 -1
  12. package/lib/subagent-launch-slots.mjs +14 -2
  13. package/lib/trust-boundaries.mjs +16 -0
  14. package/lib/update/executor.mjs +99 -0
  15. package/lib/update/journal.mjs +175 -0
  16. package/lib/update/owners.mjs +70 -0
  17. package/lib/update/plan.mjs +134 -0
  18. package/lib/update/resolver.mjs +168 -0
  19. package/lib/update/supervisor.mjs +238 -0
  20. package/lib/update/verify.mjs +52 -0
  21. package/lib/update-commands.mjs +25 -13
  22. package/lib/webui-workspaces.mjs +17 -1
  23. package/lib/workspace-session-summaries.mjs +400 -0
  24. package/package.json +4 -4
  25. package/public/app.js +2487 -349
  26. package/public/index.html +200 -51
  27. package/public/middle-button-drag-scroll.mjs +154 -0
  28. package/public/sampling-parameter-controls.mjs +361 -0
  29. package/public/service-worker.js +5 -1
  30. package/public/stream-output-controller.mjs +327 -0
  31. package/public/styles.css +666 -71
  32. package/public/theme-contract.mjs +244 -0
  33. package/session-summary.ts +164 -4
  34. package/tests/aur-review-widget-static.test.mjs +2 -1
  35. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  36. package/tests/browser/control-deck-component-updates.spec.mjs +20 -22
  37. package/tests/browser/interaction-continuity.spec.mjs +2 -2
  38. package/tests/browser/middle-button-drag-scroll.spec.mjs +145 -0
  39. package/tests/browser/persistent-ui-layout.spec.mjs +68 -23
  40. package/tests/browser/sampling-tooltip.spec.mjs +228 -0
  41. package/tests/browser/session-summary.spec.mjs +131 -3
  42. package/tests/browser/stream-output-isolation.spec.mjs +510 -0
  43. package/tests/browser/update-reconnect.spec.mjs +92 -0
  44. package/tests/codex-fast-mode-static.test.mjs +2 -2
  45. package/tests/common-options-submenus-interaction-static.test.mjs +172 -0
  46. package/tests/common-options-submenus-markup-static.test.mjs +152 -0
  47. package/tests/component-update-api-static.test.mjs +22 -61
  48. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  49. package/tests/control-deck-component-updates-static.test.mjs +13 -237
  50. package/tests/durable-rpc-supervisor-harness.test.mjs +3 -1
  51. package/tests/fast-mode-client-static.test.mjs +3 -2
  52. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  53. package/tests/feature-system-prompt-optional-feature-static.test.mjs +49 -0
  54. package/tests/fixtures/fake-pi.mjs +269 -2
  55. package/tests/fixtures/update/tree-timeout-descendant.mjs +6 -0
  56. package/tests/fixtures/update/tree-timeout-parent.mjs +11 -0
  57. package/tests/git-footer-context-menu-static.test.mjs +58 -0
  58. package/tests/git-workflow-preferences.test.mjs +7 -1
  59. package/tests/guided-git-aur-review.test.mjs +4 -3
  60. package/tests/http-endpoints-harness.test.mjs +274 -23
  61. package/tests/middle-button-drag-scroll-static.test.mjs +24 -0
  62. package/tests/middle-button-drag-scroll.test.mjs +170 -0
  63. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  64. package/tests/mobile-foundation-static.test.mjs +5 -6
  65. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  66. package/tests/mobile-static.test.mjs +85 -50
  67. package/tests/native-parity.test.mjs +1 -1
  68. package/tests/open-issue-wizard-static.test.mjs +2 -3
  69. package/tests/optional-feature-migration-frontend.test.mjs +9 -5
  70. package/tests/persistent-ui-layout-static.test.mjs +13 -2
  71. package/tests/questionnaire-dialog.test.mjs +3 -3
  72. package/tests/remote-auth-settings-harness.test.mjs +43 -0
  73. package/tests/rpc-supervisor-host.test.mjs +11 -2
  74. package/tests/safety-guard-auto-review-harness.test.mjs +117 -0
  75. package/tests/safety-guard-auto-review-static.test.mjs +34 -0
  76. package/tests/sampling-native-controls-user-flow.test.mjs +752 -0
  77. package/tests/sampling-parameter-capabilities.test.mjs +167 -0
  78. package/tests/sampling-parameter-controls.test.mjs +241 -0
  79. package/tests/session-sampling-helper.test.mjs +228 -0
  80. package/tests/session-sampling-http.test.mjs +168 -0
  81. package/tests/session-sampling-ui-static.test.mjs +370 -0
  82. package/tests/session-summary-core.test.mjs +205 -10
  83. package/tests/side-panel-section-height-removal-static.test.mjs +34 -0
  84. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  85. package/tests/staged-content-hash-contract.test.mjs +52 -11
  86. package/tests/stream-lifecycle-core.test.mjs +134 -0
  87. package/tests/stream-output-controller.test.mjs +252 -0
  88. package/tests/stream-output-isolation-static.test.mjs +89 -0
  89. package/tests/streaming-ui-coupling.test.mjs +50 -0
  90. package/tests/subagent-gate-visibility.test.mjs +1 -1
  91. package/tests/subagent-launch-slots-static.test.mjs +1 -1
  92. package/tests/subagent-launch-slots.test.mjs +18 -1
  93. package/tests/theme-contract.test.mjs +104 -0
  94. package/tests/theme-customizer-static.test.mjs +82 -0
  95. package/tests/theme-scheme-mode.test.mjs +15 -0
  96. package/tests/ui-layout-settings.test.mjs +18 -1
  97. package/tests/update-api-harness.test.mjs +111 -0
  98. package/tests/update-commands.test.mjs +15 -45
  99. package/tests/update-executor-process-tree-harness.test.mjs +22 -0
  100. package/tests/update-journal-harness.test.mjs +59 -0
  101. package/tests/update-lock-multiprocess-harness.test.mjs +46 -0
  102. package/tests/update-owners.test.mjs +27 -0
  103. package/tests/update-plan.test.mjs +58 -0
  104. package/tests/update-resolver.test.mjs +56 -0
  105. package/tests/update-supervisor-harness.test.mjs +57 -0
  106. package/tests/update-tab-restore-harness.test.mjs +24 -0
  107. package/tests/update-verify.test.mjs +31 -0
  108. package/tests/workspace-files-live-updates-static.test.mjs +13 -4
  109. package/tests/workspace-session-summaries.test.mjs +288 -0
  110. package/webui-rpc-helper.mjs +119 -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
+ });
@@ -0,0 +1,92 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { createServer } from "node:net";
4
+ import { mkdtemp, rm } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import path 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 = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
12
+ const serverEntry = path.join(root, "bin", "pi-webui.mjs");
13
+ const fakePi = path.join(root, "tests", "fixtures", "fake-pi.mjs");
14
+
15
+ async function freePort() {
16
+ const listener = createServer();
17
+ await new Promise((resolve) => listener.listen(0, "127.0.0.1", resolve));
18
+ const port = listener.address().port;
19
+ await new Promise((resolve) => listener.close(resolve));
20
+ return port;
21
+ }
22
+ function startServer(port, temp) {
23
+ const child = spawn(process.execPath, [serverEntry, "--cwd", temp, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
24
+ stdio: ["ignore", "pipe", "pipe"],
25
+ env: { ...process.env, PI_WEBUI_RPC_SUPERVISOR: "0", PI_CODING_AGENT_DIR: path.join(temp, "agent"), PI_WEBUI_SETTINGS_FILE: path.join(temp, "settings.json") },
26
+ });
27
+ child.output = "";
28
+ child.stdout.on("data", (chunk) => { child.output += chunk; });
29
+ child.stderr.on("data", (chunk) => { child.output += chunk; });
30
+ return child;
31
+ }
32
+ async function waitForHealth(baseURL, child) {
33
+ for (let attempt = 0; attempt < 120; attempt += 1) {
34
+ if (child.exitCode !== null) throw new Error(child.output);
35
+ try {
36
+ const response = await fetch(`${baseURL}/api/health`, { signal: AbortSignal.timeout(500) });
37
+ if (response.ok) return response.json();
38
+ } catch {}
39
+ await delay(100);
40
+ }
41
+ throw new Error(`server did not become healthy:\n${child.output}`);
42
+ }
43
+ async function stop(child) {
44
+ if (!child || child.exitCode !== null) return;
45
+ const exited = new Promise((resolve) => child.once("exit", resolve));
46
+ child.kill("SIGTERM");
47
+ await Promise.race([exited, delay(8_000)]);
48
+ if (child.exitCode === null) child.kill("SIGKILL");
49
+ }
50
+
51
+ test("reconnect ignores the old boot and accepts only a changed boot identity", async ({ page }) => {
52
+ test.setTimeout(120_000);
53
+ const port = await freePort();
54
+ const temp = await mkdtemp(path.join(tmpdir(), "pi-webui-update-reconnect-"));
55
+ const baseURL = `http://127.0.0.1:${port}`;
56
+ let first, second;
57
+ try {
58
+ first = startServer(port, temp);
59
+ const oldHealth = await waitForHealth(baseURL, first);
60
+ assert.match(oldHealth.bootIdentity, /^[a-f0-9-]{36}$/i);
61
+ await page.goto(baseURL);
62
+ await expect(page.locator("body")).toBeVisible();
63
+
64
+ const reconnect = page.evaluate(async ({ oldBootIdentity }) => {
65
+ const deadline = Date.now() + 90_000;
66
+ let sawOld = false;
67
+ while (Date.now() < deadline) {
68
+ try {
69
+ const response = await fetch("/api/health", { cache: "no-store" });
70
+ const health = await response.json();
71
+ if (health.bootIdentity === oldBootIdentity) sawOld = true;
72
+ if (health.ok && health.bootIdentity && health.bootIdentity !== oldBootIdentity) return { sawOld, bootIdentity: health.bootIdentity };
73
+ } catch {}
74
+ await new Promise((resolve) => setTimeout(resolve, 100));
75
+ }
76
+ throw new Error("changed boot identity did not appear within the 90-second reconnect budget");
77
+ }, { oldBootIdentity: oldHealth.bootIdentity });
78
+
79
+ second = startServer(port, temp);
80
+ await delay(700);
81
+ await stop(first);
82
+ await waitForHealth(baseURL, second);
83
+ const result = await reconnect;
84
+ assert.equal(result.sawOld, true, "the reconnect loop should observe and reject the still-running old server");
85
+ assert.notEqual(result.bootIdentity, oldHealth.bootIdentity);
86
+ await waitForHealth(baseURL, second);
87
+ } finally {
88
+ await stop(first);
89
+ await stop(second);
90
+ await rm(temp, { recursive: true, force: true });
91
+ }
92
+ });
@@ -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-v72/, "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");
57
+ assert.match(serviceWorker, /pi-webui-pwa-v81/, "PWA cache identity should be bumped for changed browser assets");
58
+ assert.match(html, /data-app-src="\/app\.js\?v=120"/, "browser module URL should be cache-busted for Fast-mode wiring");
59
59
 
60
60
  console.log("codex-fast-mode-static.test.mjs passed");