@firstpick/pi-package-webui 0.9.1 → 0.9.3

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 (107) hide show
  1. package/README.md +31 -9
  2. package/bin/pi-webui-launcher.mjs +23 -12
  3. package/bin/pi-webui.mjs +729 -93
  4. package/index.ts +266 -1
  5. package/lib/agent-run-adapters.mjs +500 -0
  6. package/lib/agent-run-protocol.mjs +262 -0
  7. package/lib/agent-run-registry.mjs +339 -0
  8. package/lib/git-workflow-preferences.mjs +18 -28
  9. package/lib/intercom-conversations.mjs +491 -0
  10. package/lib/intercom-transcript-filter.mjs +99 -0
  11. package/lib/resource-selection.mjs +140 -0
  12. package/lib/trust-boundaries.mjs +2 -0
  13. package/lib/ui-layout-settings.mjs +172 -28
  14. package/lib/update/package-layout.mjs +50 -0
  15. package/lib/update/plan.mjs +11 -0
  16. package/package.json +2 -2
  17. package/public/app.js +2276 -419
  18. package/public/index.html +142 -72
  19. package/public/service-worker.js +2 -1
  20. package/public/stream-output-controller.mjs +15 -0
  21. package/public/styles.css +764 -92
  22. package/public/syntax-highlight.mjs +622 -0
  23. package/tests/agent-run-adapters.test.mjs +217 -0
  24. package/tests/agent-run-launcher.test.mjs +41 -0
  25. package/tests/agent-run-protocol.test.mjs +82 -0
  26. package/tests/agent-run-registry.test.mjs +102 -0
  27. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  28. package/tests/browser/control-deck-side-panels.spec.mjs +354 -0
  29. package/tests/browser/controls-layout.spec.mjs +122 -0
  30. package/tests/browser/file-tree-git-ignored.spec.mjs +113 -0
  31. package/tests/browser/interaction-continuity.spec.mjs +161 -0
  32. package/tests/browser/intercom-conversation-viewer.spec.mjs +355 -0
  33. package/tests/browser/mobile-foundation.spec.mjs +26 -0
  34. package/tests/browser/model-search-focus.spec.mjs +96 -0
  35. package/tests/browser/optimistic-prompt.spec.mjs +22 -0
  36. package/tests/browser/persistent-ui-layout.spec.mjs +285 -66
  37. package/tests/browser/resource-profiles.spec.mjs +200 -0
  38. package/tests/browser/subagent-observability.spec.mjs +116 -0
  39. package/tests/codex-fast-mode-static.test.mjs +7 -6
  40. package/tests/common-options-submenus-interaction-static.test.mjs +2 -0
  41. package/tests/common-options-submenus-markup-static.test.mjs +1 -0
  42. package/tests/component-update-api-static.test.mjs +2 -1
  43. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  44. package/tests/composer-skill-tag-layout.test.mjs +32 -2
  45. package/tests/control-deck-component-updates-static.test.mjs +6 -0
  46. package/tests/control-deck-side-panels-static.test.mjs +68 -0
  47. package/tests/controls-layout-static.test.mjs +22 -0
  48. package/tests/fast-mode-client-static.test.mjs +2 -2
  49. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  50. package/tests/feature-system-prompt-optional-feature-static.test.mjs +5 -5
  51. package/tests/file-tree-git-ignored-static.test.mjs +152 -0
  52. package/tests/file-tree-search-layout-static.test.mjs +2 -1
  53. package/tests/file-viewer-image-static.test.mjs +69 -0
  54. package/tests/fixtures/fake-pi.mjs +147 -12
  55. package/tests/foreground-transcript-catch-up-static.test.mjs +1 -1
  56. package/tests/git-panel-file-preview-static.test.mjs +5 -5
  57. package/tests/git-panel-live-updates-static.test.mjs +3 -3
  58. package/tests/git-workflow-preferences.test.mjs +55 -6
  59. package/tests/http-endpoints-harness.test.mjs +295 -14
  60. package/tests/intercom-conversation-viewer-static.test.mjs +105 -0
  61. package/tests/intercom-conversations-http.test.mjs +252 -0
  62. package/tests/intercom-conversations.test.mjs +374 -0
  63. package/tests/intercom-main-transcript-suppression-static.test.mjs +52 -0
  64. package/tests/intercom-tag-layout-static.test.mjs +46 -0
  65. package/tests/intercom-transcript-filter.test.mjs +98 -0
  66. package/tests/main-output-loading-static.test.mjs +59 -0
  67. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  68. package/tests/mobile-compact-layout.test.mjs +2 -3
  69. package/tests/mobile-continuity-tablet-static.test.mjs +6 -6
  70. package/tests/mobile-foundation-static.test.mjs +3 -3
  71. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  72. package/tests/mobile-static.test.mjs +76 -42
  73. package/tests/native-parity.test.mjs +8 -7
  74. package/tests/open-issue-wizard-static.test.mjs +2 -2
  75. package/tests/optional-feature-migration-frontend.test.mjs +5 -5
  76. package/tests/optional-feature-resource-setup-static.test.mjs +29 -0
  77. package/tests/persistent-ui-layout-static.test.mjs +13 -13
  78. package/tests/questionnaire-dialog.test.mjs +3 -3
  79. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  80. package/tests/resource-defaults-helper.test.mjs +60 -6
  81. package/tests/resource-selection.test.mjs +114 -0
  82. package/tests/resource-tui-extension.test.mjs +23 -0
  83. package/tests/session-sampling-ui-static.test.mjs +3 -3
  84. package/tests/side-panel-context-menu-static.test.mjs +1 -1
  85. package/tests/side-panel-resize-static.test.mjs +26 -16
  86. package/tests/side-panel-section-height-removal-static.test.mjs +4 -4
  87. package/tests/side-panel-section-reorder-static.test.mjs +16 -70
  88. package/tests/stream-output-controller.test.mjs +8 -0
  89. package/tests/stream-output-isolation-static.test.mjs +2 -2
  90. package/tests/streaming-ui-coupling.test.mjs +5 -0
  91. package/tests/subagent-gate-visibility.test.mjs +2 -1
  92. package/tests/subagent-launch-slots.test.mjs +1 -1
  93. package/tests/subagent-observability-static.test.mjs +32 -0
  94. package/tests/subagent-reliability-integration.test.mjs +183 -0
  95. package/tests/subagent-workflow-section-static.test.mjs +67 -0
  96. package/tests/subagents-helper.test.mjs +548 -5
  97. package/tests/syntax-highlight.test.mjs +235 -0
  98. package/tests/syntax-highlighting-static.test.mjs +84 -0
  99. package/tests/terminal-tabs-resize-static.test.mjs +35 -0
  100. package/tests/theme-customizer-static.test.mjs +5 -5
  101. package/tests/thinking-format-parser.test.mjs +64 -0
  102. package/tests/ui-layout-settings.test.mjs +104 -32
  103. package/tests/update-api-harness.test.mjs +24 -10
  104. package/tests/update-package-layout.test.mjs +38 -0
  105. package/tests/update-plan.test.mjs +11 -1
  106. package/tests/webui-settings-locking.test.mjs +33 -3
  107. package/webui-rpc-helper.mjs +700 -89
@@ -210,6 +210,40 @@ test.afterAll(async () => {
210
210
  await rm(tempRoot, { recursive: true, force: true });
211
211
  });
212
212
 
213
+ test("main output shows non-blocking inline feedback while transcript data loads", async ({ page }) => {
214
+ await page.setViewportSize({ width: 1280, height: 800 });
215
+ let releaseMessages;
216
+ const messagesReleased = new Promise((resolve) => { releaseMessages = resolve; });
217
+ let delayedMessagesRequest = false;
218
+ const messagesPattern = "**/api/messages?*";
219
+ await page.route(messagesPattern, async (route) => {
220
+ if (!delayedMessagesRequest) {
221
+ delayedMessagesRequest = true;
222
+ await messagesReleased;
223
+ }
224
+ await route.continue();
225
+ });
226
+
227
+ try {
228
+ await page.goto(baseURL);
229
+ const loading = page.locator("#mainOutputLoading");
230
+ const chat = page.locator("#chat");
231
+ await expect(loading).toBeVisible();
232
+ await expect(loading).toContainText("Loading agent output…");
233
+ await expect(loading).toHaveCSS("pointer-events", "none");
234
+ await expect(chat).toHaveAttribute("aria-busy", "true");
235
+ await expect(page.locator("#promptInput")).toBeEnabled();
236
+ assert.equal(await page.evaluate(() => document.querySelectorAll("dialog:modal").length), 0, "loading feedback should not open a popup");
237
+
238
+ releaseMessages();
239
+ await expect(loading).toBeHidden();
240
+ await expect(chat).toHaveAttribute("aria-busy", "false");
241
+ } finally {
242
+ releaseMessages?.();
243
+ await page.unroute(messagesPattern);
244
+ }
245
+ });
246
+
213
247
  test("only hidden pages disconnect live events and resume from one authoritative snapshot", async ({ page }) => {
214
248
  await page.setViewportSize({ width: 1280, height: 800 });
215
249
  await page.goto(baseURL);
@@ -367,6 +401,133 @@ test("same-context app-runner refresh preserves directional selection, control s
367
401
  await expect.poll(async () => (await tabIds(page)).length).toBe(1);
368
402
  });
369
403
 
404
+ test("unchanged background-tab polling keeps the followed transcript and terminal controls stable", async ({ page }) => {
405
+ await page.setViewportSize({ width: 1280, height: 800 });
406
+ await page.goto(baseURL);
407
+ const foregroundTabId = await activeTabId(page) || (await tabIds(page))[0];
408
+ const created = await api(page, "/api/tabs", { method: "POST", data: {} });
409
+ const backgroundTabId = created.data?.tab?.id;
410
+ assert.ok(backgroundTabId && backgroundTabId !== foregroundTabId, "background polling fixture requires a second terminal tab");
411
+
412
+ await page.reload();
413
+ await expect.poll(() => activeTabId(page)).toBe(foregroundTabId);
414
+ await expect(page.locator(`[data-tab-id="${backgroundTabId}"] .terminal-tab-button`)).toBeVisible();
415
+ await page.locator(`[data-tab-id="${backgroundTabId}"] .terminal-tab-button`).click();
416
+ await startContinuityRunner(page);
417
+ await page.locator(`[data-tab-id="${foregroundTabId}"] .terminal-tab-button`).click();
418
+ await expect.poll(() => activeTabId(page)).toBe(foregroundTabId);
419
+
420
+ // Let the first poll observe the background runner. Subsequent identical
421
+ // snapshots must not rebuild the terminal strip or disturb chat follow.
422
+ await page.waitForTimeout(1700);
423
+ const foregroundButton = await page.locator(`[data-tab-id="${foregroundTabId}"] .terminal-tab-button`).elementHandle();
424
+ assert.ok(foregroundButton, "foreground terminal control should be mounted before stability sampling");
425
+ const movement = await page.locator("#chat").evaluate(async (chat) => {
426
+ const spacer = document.createElement("div");
427
+ spacer.dataset.pollingContinuityFixture = "true";
428
+ spacer.style.height = "3000px";
429
+ chat.append(spacer);
430
+ chat.scrollTop = chat.scrollHeight;
431
+ const positions = [];
432
+ const started = performance.now();
433
+ while (performance.now() - started < 1800) {
434
+ positions.push(chat.scrollTop);
435
+ await new Promise((resolve) => requestAnimationFrame(resolve));
436
+ }
437
+ spacer.remove();
438
+ return Math.max(...positions) - Math.min(...positions);
439
+ });
440
+ assert.equal(await foregroundButton.evaluate((node) => node.isConnected), true, "an unchanged background-tab poll should preserve the existing foreground terminal control");
441
+ expect(movement).toBeLessThanOrEqual(1.5);
442
+
443
+ await api(page, `/api/tabs/${encodeURIComponent(backgroundTabId)}`, { method: "DELETE" });
444
+ await expect.poll(async () => (await tabIds(page)).length).toBe(1);
445
+ });
446
+
447
+ test("focus reconciliation and terminal switching keep the running status geometry stable", async ({ page }) => {
448
+ await page.setViewportSize({ width: 1280, height: 800 });
449
+ await page.goto(baseURL);
450
+ const foregroundTabId = await activeTabId(page) || (await tabIds(page))[0];
451
+ const created = await api(page, "/api/tabs", { method: "POST", data: {} });
452
+ const backgroundTabId = created.data?.tab?.id;
453
+ assert.ok(backgroundTabId && backgroundTabId !== foregroundTabId, "focus continuity requires a second terminal tab");
454
+ await page.reload();
455
+ await expect.poll(() => activeTabId(page)).toBe(foregroundTabId);
456
+ await expect(page.locator(`[data-tab-id="${backgroundTabId}"] .terminal-tab-button`)).toBeVisible();
457
+
458
+ await triggerDelayedStream(page, foregroundTabId);
459
+ await waitForFixtureSettlement(page, foregroundTabId);
460
+ await page.waitForTimeout(1500);
461
+ const runIndicator = page.locator("#runIndicatorHost .runIndicator");
462
+ await expect(runIndicator).toBeHidden();
463
+
464
+ const focusMovement = await page.locator("#chat").evaluate(async (chat) => {
465
+ chat.style.paddingBottom = "3000px";
466
+ chat.scrollTop = chat.scrollHeight;
467
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
468
+ const sticky = document.querySelector("#stickyUserPromptButton");
469
+ window.dispatchEvent(new FocusEvent("focus"));
470
+ await new Promise((resolve) => setTimeout(resolve, 800));
471
+ const stickyChildren = [...sticky.children];
472
+ const samples = [];
473
+ window.dispatchEvent(new FocusEvent("focus"));
474
+ const started = performance.now();
475
+ while (performance.now() - started < 800) {
476
+ samples.push({
477
+ gap: chat.scrollHeight - chat.clientHeight - chat.scrollTop,
478
+ stickyStable: stickyChildren.every((node, index) => node === sticky.children[index] && node.isConnected),
479
+ });
480
+ await new Promise((resolve) => requestAnimationFrame(resolve));
481
+ }
482
+ chat.style.removeProperty("padding-bottom");
483
+ const gaps = samples.map((sample) => sample.gap);
484
+ return {
485
+ gapDrift: Math.max(...gaps) - Math.min(...gaps),
486
+ stickyStable: samples.every((sample) => sample.stickyStable),
487
+ };
488
+ });
489
+ expect(focusMovement.gapDrift).toBeLessThanOrEqual(1.5);
490
+ assert.equal(focusMovement.stickyStable, true, "focus reconciliation should preserve unchanged sticky-prompt children");
491
+
492
+ await triggerDelayedStream(page, foregroundTabId);
493
+ await expect(runIndicator).toBeVisible();
494
+ await page.locator(`[data-tab-id="${backgroundTabId}"] .terminal-tab-button`).click();
495
+ await expect.poll(() => activeTabId(page)).toBe(backgroundTabId);
496
+ await page.locator(`[data-tab-id="${foregroundTabId}"] .terminal-tab-button`).click();
497
+ const switchMovement = await page.evaluate(async () => {
498
+ const samples = [];
499
+ const started = performance.now();
500
+ while (performance.now() - started < 900) {
501
+ const indicator = document.querySelector("#runIndicatorHost .runIndicator");
502
+ samples.push({
503
+ connected: indicator?.isConnected === true,
504
+ indicatorTop: indicator?.getBoundingClientRect().top ?? null,
505
+ composerHeight: document.querySelector("#composer")?.getBoundingClientRect().height ?? null,
506
+ contextHeight: document.querySelector("#contextMeterBar")?.getBoundingClientRect().height ?? null,
507
+ });
508
+ await new Promise((resolve) => requestAnimationFrame(resolve));
509
+ }
510
+ const visibleSamples = samples.filter((sample) => sample.connected);
511
+ const range = (key) => {
512
+ const values = visibleSamples.map((sample) => sample[key]).filter(Number.isFinite);
513
+ return Math.max(...values) - Math.min(...values);
514
+ };
515
+ return {
516
+ observed: visibleSamples.length >= 5,
517
+ indicatorTop: range("indicatorTop"),
518
+ composerHeight: range("composerHeight"),
519
+ contextHeight: range("contextHeight"),
520
+ };
521
+ });
522
+ assert.equal(switchMovement.observed, true, "the running status should become visible again during the terminal switch");
523
+ expect(switchMovement.indicatorTop).toBeLessThanOrEqual(1.5);
524
+ expect(switchMovement.composerHeight).toBeLessThanOrEqual(1.5);
525
+ expect(switchMovement.contextHeight).toBeLessThanOrEqual(1.5);
526
+
527
+ await api(page, `/api/tabs/${encodeURIComponent(backgroundTabId)}`, { method: "DELETE" });
528
+ await expect.poll(async () => (await tabIds(page)).length).toBe(1);
529
+ });
530
+
370
531
  test("main output text selection survives streaming-tail and settlement rerenders", async ({ page }) => {
371
532
  await page.setViewportSize({ width: 1280, height: 800 });
372
533
  await page.goto(baseURL);
@@ -0,0 +1,355 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { createServer } from "node:net";
4
+ import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { dirname, join } from "node:path";
7
+ import { setTimeout as delay } from "node:timers/promises";
8
+ import { fileURLToPath } from "node:url";
9
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
10
+ import { expect, test } from "@playwright/test";
11
+
12
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
13
+ const serverScript = join(root, "bin", "pi-webui.mjs");
14
+ const fakePi = join(root, "tests", "fixtures", "fake-pi.mjs");
15
+ const longPeerId = "peer-browser-long-layout";
16
+ const longPeerName = "An Exceptionally Long Browser Peer Name That Must Be Visually Truncated";
17
+ const expectedConversationCount = 32;
18
+
19
+ async function freePort() {
20
+ const server = createServer();
21
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
22
+ const { port } = server.address();
23
+ await new Promise((resolve) => server.close(resolve));
24
+ return port;
25
+ }
26
+
27
+ let child;
28
+ let baseURL;
29
+ let tempRoot;
30
+ let manager;
31
+ let output = "";
32
+
33
+ async function waitForServer() {
34
+ for (let attempt = 0; attempt < 100; attempt += 1) {
35
+ if (child.exitCode !== null) break;
36
+ try {
37
+ const response = await fetch(`${baseURL}/api/health`, { signal: AbortSignal.timeout(500) });
38
+ if (response.ok) return;
39
+ } catch {
40
+ // Wait for the isolated WebUI fixture.
41
+ }
42
+ await delay(100);
43
+ }
44
+ throw new Error(`Pi WebUI did not start:\n${output}`);
45
+ }
46
+
47
+ test.beforeAll(async () => {
48
+ const port = await freePort();
49
+ tempRoot = await mkdtemp(join(tmpdir(), "pi-webui-intercom-viewer-"));
50
+ const agentDir = join(tempRoot, "agent");
51
+ const sessionDir = join(agentDir, "sessions");
52
+ const cwd = join(tempRoot, "project");
53
+ const settingsFile = join(tempRoot, "settings.json");
54
+ await mkdir(sessionDir, { recursive: true });
55
+ await mkdir(cwd, { recursive: true });
56
+ await writeFile(join(agentDir, "trust.json"), `${JSON.stringify({ [cwd]: true }, null, 2)}\n`, "utf8");
57
+ await writeFile(settingsFile, `${JSON.stringify({ version: 3 })}\n`, "utf8");
58
+ await chmod(fakePi, 0o755);
59
+
60
+ manager = SessionManager.create(cwd, sessionDir);
61
+ manager.appendCustomMessageEntry("intercom_message", "rendered prose must stay hidden", true, {
62
+ from: { id: "peer-browser", name: "Browser Peer", cwd: "/private/peer/path" },
63
+ message: {
64
+ id: "browser-in-1",
65
+ timestamp: 1_700_000_000_000,
66
+ content: { text: "Hello from the peer", attachments: [{ name: "secret.txt", content: "BROWSER_ATTACHMENT_SECRET" }] },
67
+ },
68
+ });
69
+ manager.appendCustomEntry("intercom_sent", {
70
+ to: "Browser Peer",
71
+ message: { text: "Hello from the local agent", replyTo: "browser-in-1" },
72
+ messageId: "browser-out-1",
73
+ timestamp: 1_700_000_001_000,
74
+ });
75
+ for (const peer of [
76
+ {
77
+ id: longPeerId,
78
+ name: longPeerName,
79
+ messageId: "browser-layout-long",
80
+ timestamp: 1_699_999_999_000,
81
+ text: "Long-label conversation selected correctly",
82
+ },
83
+ {
84
+ id: "peer-browser-layout-alpha",
85
+ name: "Layout Peer Alpha",
86
+ messageId: "browser-layout-alpha",
87
+ timestamp: 1_699_999_998_000,
88
+ text: "Alpha layout fixture",
89
+ },
90
+ {
91
+ id: "peer-browser-layout-beta",
92
+ name: "Layout Peer Beta",
93
+ messageId: "browser-layout-beta",
94
+ timestamp: 1_699_999_997_000,
95
+ text: "Beta layout fixture",
96
+ },
97
+ ...Array.from({ length: 28 }, (_, index) => ({
98
+ id: `peer-browser-dense-${String(index + 1).padStart(2, "0")}`,
99
+ name: `Dense Layout Peer ${String(index + 1).padStart(2, "0")}`,
100
+ messageId: `browser-layout-dense-${String(index + 1).padStart(2, "0")}`,
101
+ timestamp: 1_699_999_996_000 - index * 1_000,
102
+ text: `Dense layout fixture ${index + 1}`,
103
+ })),
104
+ ]) {
105
+ manager.appendCustomMessageEntry("intercom_message", `rendered prose for ${peer.id} must stay hidden`, true, {
106
+ from: { id: peer.id, name: peer.name },
107
+ message: { id: peer.messageId, timestamp: peer.timestamp, content: { text: peer.text } },
108
+ });
109
+ }
110
+ manager.appendMessage({
111
+ role: "assistant",
112
+ content: [{ type: "text", text: "ordinary assistant output must stay outside the conversation" }],
113
+ api: "openai-responses",
114
+ provider: "fake",
115
+ model: "fake-model",
116
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } },
117
+ stopReason: "stop",
118
+ timestamp: 1_700_000_001_500,
119
+ });
120
+ const sessionFile = manager.getSessionFile();
121
+ assert.ok(sessionFile, "the browser fixture needs a persisted session");
122
+
123
+ baseURL = `http://127.0.0.1:${port}`;
124
+ child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
125
+ stdio: ["ignore", "pipe", "pipe"],
126
+ env: {
127
+ ...process.env,
128
+ PI_WEBUI_RPC_SUPERVISOR: "0",
129
+ PI_CODING_AGENT_DIR: agentDir,
130
+ PI_WEBUI_SETTINGS_FILE: settingsFile,
131
+ FAKE_PI_CONTINUITY_MODE: "1",
132
+ FAKE_PI_CONTINUITY_SESSION_FILE: sessionFile,
133
+ FAKE_PI_INTERCOM_LIVE: "1",
134
+ },
135
+ });
136
+ child.stdout.on("data", (chunk) => { output += String(chunk); });
137
+ child.stderr.on("data", (chunk) => { output += String(chunk); });
138
+ await waitForServer();
139
+ });
140
+
141
+ test.afterAll(async () => {
142
+ if (child?.exitCode === null) child.kill("SIGTERM");
143
+ if (child && child.exitCode === null) await new Promise((resolve) => child.once("exit", resolve));
144
+ await rm(tempRoot, { recursive: true, force: true }).catch(() => {});
145
+ });
146
+
147
+ test("the 32-conversation dense grid stays contained and opens the correct truncated conversation", async ({ page }) => {
148
+ await page.setViewportSize({ width: 900, height: 760 });
149
+ await page.goto(baseURL);
150
+ const container = page.locator("#intercomConversationTags");
151
+ const tags = container.locator(":scope > .composer-intercom-tag");
152
+ const longTag = tags.filter({ hasText: longPeerName });
153
+ const longLabel = longTag.locator(".composer-intercom-tag-label");
154
+
155
+ await expect(tags).toHaveCount(expectedConversationCount);
156
+ await expect(container).toHaveClass(/\bdense\b/);
157
+ for (let index = 0; index < expectedConversationCount; index += 1) await expect(tags.nth(index)).toBeVisible();
158
+
159
+ const layout = await container.evaluate((element) => {
160
+ const containerRect = element.getBoundingClientRect();
161
+ const tagRects = [...element.querySelectorAll(":scope > .composer-intercom-tag")].map((tag) => tag.getBoundingClientRect());
162
+ return {
163
+ clientWidth: element.clientWidth,
164
+ scrollWidth: element.scrollWidth,
165
+ widths: tagRects.map((rect) => rect.width),
166
+ rowTops: [...new Set(tagRects.map((rect) => Math.round(rect.top)))],
167
+ allContained: tagRects.every((rect) => rect.left >= containerRect.left - 0.5 && rect.right <= containerRect.right + 0.5),
168
+ };
169
+ });
170
+ assert.ok(layout.allContained, "every desktop conversation tag should remain within the tag container");
171
+ assert.ok(layout.scrollWidth <= layout.clientWidth, `the desktop tag grid should not overflow horizontally (${layout.scrollWidth} > ${layout.clientWidth})`);
172
+ assert.ok(Math.min(...layout.widths) >= 44, `every dense desktop target should be at least 44px wide (minimum ${Math.min(...layout.widths)})`);
173
+ assert.ok(layout.rowTops.length > 1, "the 32-conversation desktop fixture should wrap into multiple rows");
174
+
175
+ await expect(longTag).toHaveCount(1);
176
+ const fullVisualLabel = await longLabel.textContent();
177
+ assert.ok(fullVisualLabel?.includes(longPeerName), "the long label fixture should retain its full DOM text");
178
+ await expect(longTag).toHaveAttribute("aria-label", `Open agent conversation ${fullVisualLabel}`);
179
+ await expect(longTag).toHaveAttribute("title", `${fullVisualLabel} · 1 message`);
180
+ const truncation = await longLabel.evaluate((element) => ({ clientWidth: element.clientWidth, scrollWidth: element.scrollWidth }));
181
+ assert.ok(truncation.scrollWidth > truncation.clientWidth, `the long label should be visually truncated (${truncation.scrollWidth} <= ${truncation.clientWidth})`);
182
+
183
+ await longTag.click();
184
+ await expect(page.locator("#intercomConversationDialog")).toBeVisible();
185
+ await expect(page.locator("#intercomConversationParticipants")).toContainText(`${longPeerName} (${longPeerId})`);
186
+ await expect(page.locator("#intercomConversationTranscript")).toContainText("Long-label conversation selected correctly");
187
+ await page.locator("#intercomConversationCloseButton").click();
188
+ await expect(longTag).toBeFocused();
189
+ });
190
+
191
+ test("conversation tag opens a safe chat dialog, refreshes, and restores focus", async ({ page }) => {
192
+ await page.goto(baseURL);
193
+ const tags = page.locator("#intercomConversationTags .composer-intercom-tag");
194
+ const tag = tags.filter({
195
+ has: page.locator(".composer-intercom-tag-label").filter({ hasText: /↔ Browser Peer \(peer-browser\)$/ }),
196
+ });
197
+ const dialog = page.locator("#intercomConversationDialog");
198
+ const transcript = page.locator("#intercomConversationTranscript");
199
+ const close = page.locator("#intercomConversationCloseButton");
200
+
201
+ await expect(tags).toHaveCount(expectedConversationCount);
202
+ await expect(tag).toHaveCount(1);
203
+ await expect(tag).toContainText("Browser Peer");
204
+ await tag.click();
205
+ await expect(dialog).toBeVisible();
206
+ await expect(close).toBeFocused();
207
+ await expect(page.locator("#intercomConversationParticipants")).toContainText("Browser Peer (peer-browser)");
208
+ await expect(transcript.locator(".intercom-conversation-message.peer")).toContainText("Hello from the peer");
209
+ await expect(transcript.locator(".intercom-conversation-message.local")).toContainText("Hello from the local agent");
210
+ await expect(transcript).not.toContainText("BROWSER_ATTACHMENT_SECRET");
211
+ await expect(transcript).not.toContainText("ordinary assistant output");
212
+ await expect(transcript).not.toContainText("/private/peer/path");
213
+
214
+ const firstMessage = transcript.locator(".intercom-conversation-message").first();
215
+ await firstMessage.evaluate((node) => { node.dataset.stableNodeMarker = "retained"; });
216
+ await expect(tag.locator(".composer-intercom-tag-count")).toHaveText("2");
217
+
218
+ const longMessage = [
219
+ "Arrived while the dialog was open",
220
+ ...Array.from({ length: 90 }, (_, index) => `Live message line ${index + 1}`),
221
+ ].join("\n");
222
+ manager.appendCustomMessageEntry("intercom_message", "new rendered prose must stay hidden", true, {
223
+ from: { id: "peer-browser", name: "Browser Peer" },
224
+ message: { id: "browser-in-2", timestamp: 1_700_000_002_000, content: { text: longMessage } },
225
+ });
226
+ await expect(transcript).toContainText("Arrived while the dialog was open", { timeout: 8_000 });
227
+ await expect(firstMessage).toHaveAttribute("data-stable-node-marker", "retained");
228
+ await expect(tag.locator(".composer-intercom-tag-count")).toHaveText("2", { timeout: 1_000 });
229
+
230
+ const scrollBefore = await transcript.evaluate((element) => {
231
+ const max = element.scrollHeight - element.clientHeight;
232
+ element.scrollTop = Math.floor(max / 2);
233
+ return { top: element.scrollTop, max };
234
+ });
235
+ assert.ok(scrollBefore.max > 100 && scrollBefore.top > 0, "the long fixture should create a meaningful scrolled-up transcript position");
236
+
237
+ manager.appendCustomMessageEntry("intercom_message", "another rendered prose message must stay hidden", true, {
238
+ from: { id: "peer-browser", name: "Browser Peer" },
239
+ message: { id: "browser-in-3", timestamp: 1_700_000_003_000, content: { text: "Arrived after the reader scrolled up" } },
240
+ });
241
+ await expect(transcript).toContainText("Arrived after the reader scrolled up", { timeout: 8_000 });
242
+ await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
243
+ const scrollAfter = await transcript.evaluate((element) => element.scrollTop);
244
+ assert.ok(Math.abs(scrollAfter - scrollBefore.top) <= 4, `live refresh should preserve the scrolled-up position (${scrollBefore.top} -> ${scrollAfter})`);
245
+ await expect(firstMessage).toHaveAttribute("data-stable-node-marker", "retained");
246
+ await expect(tag.locator(".composer-intercom-tag-count")).toHaveText("2", { timeout: 1_000 });
247
+
248
+ await close.click();
249
+ await expect(dialog).toBeHidden();
250
+ await expect(tag).toBeFocused();
251
+ await expect(tag.locator(".composer-intercom-tag-count")).toHaveText("4");
252
+ const stableTagLabel = tag.locator(".composer-intercom-tag-label");
253
+ await stableTagLabel.evaluate((node) => { node.dataset.stableVisualMarker = "retained"; });
254
+ await tag.press("Enter");
255
+ await expect(dialog).toBeVisible();
256
+ await page.keyboard.press("Escape");
257
+ await expect(dialog).toBeHidden();
258
+ await expect(tag).toBeFocused();
259
+ await expect(stableTagLabel).toHaveAttribute("data-stable-visual-marker", "retained");
260
+ });
261
+
262
+ test("conversation tags remain reachable through the narrow composer disclosure", async ({ page }) => {
263
+ await page.setViewportSize({ width: 390, height: 760 });
264
+ await page.goto(baseURL);
265
+ const more = page.locator("#composerActionsButton");
266
+ await expect(more).toBeVisible();
267
+ await more.focus();
268
+ await more.press("Enter");
269
+ const tags = page.locator("#intercomConversationTags");
270
+ const tagButtons = tags.locator(":scope > .composer-intercom-tag");
271
+ const tag = tagButtons.filter({
272
+ has: page.locator(".composer-intercom-tag-label").filter({ hasText: /↔ Browser Peer \(peer-browser\)$/ }),
273
+ });
274
+ await expect(tags).toBeVisible();
275
+ await expect(tagButtons).toHaveCount(expectedConversationCount);
276
+ for (let index = 0; index < expectedConversationCount; index += 1) {
277
+ await expect(tagButtons.nth(index)).toBeVisible();
278
+ await expect(tagButtons.nth(index)).toHaveCSS("min-height", "44px");
279
+ }
280
+ const layout = await tags.evaluate((element) => {
281
+ const containerRect = element.getBoundingClientRect();
282
+ const tagRects = [...element.querySelectorAll(":scope > .composer-intercom-tag")].map((button) => button.getBoundingClientRect());
283
+ return {
284
+ clientWidth: element.clientWidth,
285
+ scrollWidth: element.scrollWidth,
286
+ widths: tagRects.map((rect) => rect.width),
287
+ heights: tagRects.map((rect) => rect.height),
288
+ rowTops: [...new Set(tagRects.map((rect) => Math.round(rect.top)))],
289
+ allContained: tagRects.every((rect) => rect.left >= containerRect.left - 0.5 && rect.right <= containerRect.right + 0.5),
290
+ };
291
+ });
292
+ assert.ok(layout.allContained, "every narrow conversation tag should remain within the tag container");
293
+ assert.ok(layout.scrollWidth <= layout.clientWidth, `the narrow tag grid should not overflow horizontally (${layout.scrollWidth} > ${layout.clientWidth})`);
294
+ assert.ok(Math.min(...layout.widths) >= 44, `every narrow touch target should be at least 44px wide (minimum ${Math.min(...layout.widths)})`);
295
+ assert.ok(Math.min(...layout.heights) >= 44, `every narrow touch target should be at least 44px high (minimum ${Math.min(...layout.heights)})`);
296
+ assert.ok(layout.rowTops.length > 1, "the 32-conversation narrow fixture should wrap into multiple rows");
297
+ const clippedLabels = await tagButtons.locator(".composer-intercom-tag-label").evaluateAll((labels) => labels.filter((label) => label.scrollWidth > label.clientWidth).length);
298
+ assert.ok(clippedLabels > 0, "dense narrow labels should be allowed to truncate visually");
299
+ await tag.focus();
300
+ await tag.press("Enter");
301
+ await expect(page.locator("#intercomConversationDialog")).toBeVisible();
302
+ await expect(page.locator("#intercomConversationParticipants")).toContainText("Browser Peer (peer-browser)");
303
+ await expect(page.locator("#intercomConversationCloseButton")).toBeVisible();
304
+ });
305
+
306
+ test("live generic Intercom transport never reaches the main transcript or event log", async ({ page }) => {
307
+ await page.setViewportSize({ width: 900, height: 760 });
308
+ await page.goto(baseURL);
309
+ await page.evaluate(() => {
310
+ const chat = document.querySelector("#chat");
311
+ const eventLog = document.querySelector("#eventLog");
312
+ window.__intercomLiveLeaks = [];
313
+ const inspect = () => {
314
+ const chatText = chat?.textContent || "";
315
+ const eventText = eventLog?.textContent || "";
316
+ if (/LIVEINTERCOM(?:ARGUMENT|RESULT)SECRET/.test(chatText)) window.__intercomLiveLeaks.push("secret text reached main transcript");
317
+ if (/LIVEINTERCOM(?:ARGUMENT|RESULT)SECRET/.test(eventText)) window.__intercomLiveLeaks.push("secret text reached event log");
318
+ if (chat?.querySelector('[data-tool-call-id="live-intercom-call"]')) window.__intercomLiveLeaks.push("Intercom tool card reached main transcript");
319
+ if (eventLog?.querySelector('[data-chat-tool-call-id="live-intercom-call"]') || /tool intercom (?:started|finished)/i.test(eventText)) {
320
+ window.__intercomLiveLeaks.push("Intercom execution line reached event log");
321
+ }
322
+ };
323
+ const observer = new MutationObserver(inspect);
324
+ if (chat) observer.observe(chat, { childList: true, subtree: true, characterData: true });
325
+ if (eventLog) observer.observe(eventLog, { childList: true, subtree: true, characterData: true });
326
+ window.__intercomLiveObserver = observer;
327
+ inspect();
328
+ });
329
+
330
+ const tabsResponse = await page.request.get(`${baseURL}/api/tabs`);
331
+ assert.equal(tabsResponse.ok(), true, await tabsResponse.text());
332
+ const tabId = (await tabsResponse.json()).data?.tabs?.[0]?.id;
333
+ assert.ok(tabId, "the live Intercom fixture requires an active tab");
334
+ const promptResponse = await page.request.post(`${baseURL}/api/prompt?tab=${encodeURIComponent(tabId)}`, {
335
+ data: { message: "fixture modal transport live", requestId: `intercom-live-${Date.now()}` },
336
+ });
337
+ assert.equal(promptResponse.ok(), true, await promptResponse.text());
338
+
339
+ await expect(page.locator("#chat")).toContainText("LIVE NORMAL OUTPUT VISIBLE", { timeout: 8_000 });
340
+ await expect.poll(async () => {
341
+ const response = await page.request.get(`${baseURL}/api/state?tab=${encodeURIComponent(tabId)}`);
342
+ return (await response.json()).data?.isStreaming;
343
+ }, { timeout: 8_000 }).toBe(false);
344
+ await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
345
+
346
+ await expect(page.locator("#chat")).not.toContainText("LIVEINTERCOMARGUMENTSECRET");
347
+ await expect(page.locator("#chat")).not.toContainText("LIVEINTERCOMRESULTSECRET");
348
+ await expect(page.locator('#chat [data-tool-call-id="live-intercom-call"]')).toHaveCount(0);
349
+ await expect(page.locator("#eventLog")).not.toContainText(/tool intercom (?:started|finished)/i);
350
+ const leaks = await page.evaluate(() => {
351
+ window.__intercomLiveObserver?.disconnect();
352
+ return [...(window.__intercomLiveLeaks || [])];
353
+ });
354
+ assert.deepEqual(leaks, [], `live Intercom transport leaked before reconciliation: ${leaks.join(", ")}`);
355
+ });
@@ -44,6 +44,7 @@ test.beforeAll(async () => {
44
44
  env: {
45
45
  ...process.env,
46
46
  PI_WEBUI_RPC_SUPERVISOR: "0",
47
+ FAKE_PI_CONTINUITY_MODE: "1",
47
48
  PI_CODING_AGENT_DIR: join(tempRoot, "agent"),
48
49
  PI_WEBUI_SETTINGS_FILE: join(tempRoot, "settings.json"),
49
50
  },
@@ -538,6 +539,31 @@ test("phone v2 destinations, canonical actions, history, and presentation remain
538
539
  await phoneContext.close();
539
540
  });
540
541
 
542
+ test("mobile model search retains focus while agent output streams", async ({ browser }) => {
543
+ const context = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
544
+ const page = await context.newPage();
545
+ await page.goto(`${baseURL}/?mobileShell=v2`);
546
+ await page.locator("#updateNotification").evaluate((notification) => { notification.hidden = true; notification.classList.remove("show"); });
547
+
548
+ await page.locator("#mobileMoreButton").click();
549
+ await page.getByRole("button", { name: "Settings" }).click();
550
+ await page.locator("#modelControlLabel").click();
551
+ const modelSearch = page.locator("#modelSearchInput");
552
+ await expect(modelSearch).toBeVisible();
553
+ await modelSearch.fill("gpt");
554
+
555
+ const tabsPayload = await (await page.request.get(`${baseURL}/api/tabs`)).json();
556
+ const streamingTabId = tabsPayload.data.activeTabId || tabsPayload.data.tabs[0].id;
557
+ const streamResponse = await page.request.post(`${baseURL}/api/prompt?tab=${encodeURIComponent(streamingTabId)}`, {
558
+ data: { message: "fixture continuity delayed stream", requestId: `model-search-focus-${Date.now()}` },
559
+ });
560
+ assert.equal(streamResponse.ok(), true);
561
+ await expect(page.locator(".message.assistant.streaming .streaming-markdown").last()).toContainText("continuity stream");
562
+ await expect(modelSearch).toBeFocused();
563
+ await expect(modelSearch).toHaveValue("gpt");
564
+ await context.close();
565
+ });
566
+
541
567
  test("mobile continuity preserves drafts, restores metadata honestly, and retries only on command", async ({ browser }) => {
542
568
  const context = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
543
569
  const page = await context.newPage();
@@ -0,0 +1,96 @@
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 { dirname, join } from "node:path";
7
+ import { setTimeout as delay } from "node:timers/promises";
8
+ import { fileURLToPath } from "node:url";
9
+ import { expect, test } from "@playwright/test";
10
+
11
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
12
+ const serverScript = join(root, "bin", "pi-webui.mjs");
13
+ const fakePi = join(root, "tests", "fixtures", "fake-pi.mjs");
14
+
15
+ async function freePort() {
16
+ const server = createServer();
17
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
18
+ const { port } = server.address();
19
+ await new Promise((resolve) => server.close(resolve));
20
+ return port;
21
+ }
22
+
23
+ let child;
24
+ let baseURL;
25
+ let tempRoot;
26
+ let output = "";
27
+
28
+ test.beforeAll(async () => {
29
+ const port = await freePort();
30
+ tempRoot = await mkdtemp(join(tmpdir(), "pi-webui-model-search-focus-"));
31
+ baseURL = `http://127.0.0.1:${port}`;
32
+ child = spawn(process.execPath, [serverScript, "--cwd", tempRoot, "--host", "127.0.0.1", "--port", String(port), "--pi", fakePi], {
33
+ stdio: ["ignore", "pipe", "pipe"],
34
+ env: {
35
+ ...process.env,
36
+ PI_WEBUI_RPC_SUPERVISOR: "0",
37
+ FAKE_PI_CONTINUITY_MODE: "1",
38
+ PI_CODING_AGENT_DIR: join(tempRoot, "agent"),
39
+ PI_WEBUI_SETTINGS_FILE: join(tempRoot, "settings.json"),
40
+ },
41
+ });
42
+ child.stdout.on("data", (chunk) => { output += String(chunk); });
43
+ child.stderr.on("data", (chunk) => { output += String(chunk); });
44
+ for (let attempt = 0; attempt < 80; attempt += 1) {
45
+ if (child.exitCode !== null) break;
46
+ try {
47
+ const response = await fetch(`${baseURL}/api/health`, { signal: AbortSignal.timeout(500) });
48
+ if (response.ok) return;
49
+ } catch {
50
+ // Wait for the local server and fake Pi fixture.
51
+ }
52
+ await delay(100);
53
+ }
54
+ throw new Error(`Pi Web UI did not start:\n${output}`);
55
+ });
56
+
57
+ test.afterAll(async () => {
58
+ child?.kill("SIGTERM");
59
+ if (child) await new Promise((resolve) => child.once("exit", resolve));
60
+ await rm(tempRoot, { recursive: true, force: true });
61
+ });
62
+
63
+ test("desktop model search retains focus while agent output streams", async ({ page }) => {
64
+ await page.setViewportSize({ width: 1440, height: 900 });
65
+ await page.goto(baseURL);
66
+ await page.locator("#updateNotification").evaluate((node) => { node.hidden = true; node.classList.remove("show"); });
67
+
68
+ const sidePanel = page.locator("#sidePanel");
69
+ if (!(await sidePanel.isVisible())) await page.locator("#sidePanelExpandButton").click();
70
+ const controlsToggle = page.locator('[data-side-panel-section-toggle="controls"]');
71
+ if (await controlsToggle.getAttribute("aria-expanded") !== "true") await controlsToggle.click();
72
+ await expect(page.locator("#sidePanelSectionControls")).toBeVisible();
73
+
74
+ await page.locator(".control-row-label:has(#modelControlLabel)").click();
75
+ const modelSearch = page.locator("#modelSearchInput");
76
+ await expect(modelSearch).toBeVisible();
77
+ await modelSearch.fill("claude");
78
+ await expect(modelSearch).toBeFocused();
79
+
80
+ const tabsPayload = await (await page.request.get(`${baseURL}/api/tabs`)).json();
81
+ const tabId = tabsPayload.data.activeTabId || tabsPayload.data.tabs[0].id;
82
+ const response = await page.request.post(`${baseURL}/api/prompt?tab=${encodeURIComponent(tabId)}`, {
83
+ data: { message: "fixture continuity delayed stream", requestId: `desktop-focus-${Date.now()}` },
84
+ });
85
+ assert.equal(response.ok(), true);
86
+
87
+ await expect(page.locator(".message.assistant.streaming .streaming-markdown").last()).toContainText("continuity stream");
88
+ await expect(modelSearch).toBeFocused();
89
+ await expect(modelSearch).toHaveValue("claude");
90
+ await expect.poll(async () => {
91
+ const state = await (await page.request.get(`${baseURL}/api/state?tab=${encodeURIComponent(tabId)}`)).json();
92
+ return state.data?.isStreaming === false;
93
+ }, { timeout: 15_000 }).toBe(true);
94
+ await expect(modelSearch).toBeFocused();
95
+ await expect(modelSearch).toHaveValue("claude");
96
+ });