@firstpick/pi-package-webui 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +34 -5
  2. package/bin/pi-webui.mjs +606 -102
  3. package/lib/component-update-state.mjs +126 -0
  4. package/lib/npm-command.mjs +81 -0
  5. package/lib/queue-mutation.mjs +6 -0
  6. package/lib/trust-boundaries.mjs +1 -0
  7. package/lib/workspace-files-live-watcher.mjs +138 -0
  8. package/package.json +8 -3
  9. package/public/app.js +4231 -376
  10. package/public/index.html +265 -52
  11. package/public/mobile-shell-state.mjs +166 -0
  12. package/public/service-worker.js +60 -13
  13. package/public/styles.css +1790 -383
  14. package/public/subagent-gate-visibility.mjs +16 -0
  15. package/public/subagent-launch-slot-state.mjs +16 -0
  16. package/public/transcript-renderer.mjs +433 -0
  17. package/tests/boot-failure-diagnostics.test.mjs +63 -5
  18. package/tests/browser/control-deck-component-updates.spec.mjs +180 -0
  19. package/tests/browser/interaction-continuity.spec.mjs +897 -0
  20. package/tests/browser/mobile-foundation.spec.mjs +363 -0
  21. package/tests/browser/optimistic-prompt.spec.mjs +130 -0
  22. package/tests/browser/side-panel-section-reorder.spec.mjs +101 -0
  23. package/tests/browser/stats-overlay.spec.mjs +265 -0
  24. package/tests/chat-scroll-intent-static.test.mjs +6 -1
  25. package/tests/codex-fast-mode-static.test.mjs +8 -5
  26. package/tests/compact-sections-static.test.mjs +20 -2
  27. package/tests/compaction-mutation-contract.test.mjs +18 -4
  28. package/tests/compaction-static.test.mjs +1 -0
  29. package/tests/completion-signal-contract.test.mjs +13 -2
  30. package/tests/component-update-api-static.test.mjs +67 -0
  31. package/tests/component-update-state.test.mjs +80 -0
  32. package/tests/control-deck-component-updates-static.test.mjs +251 -0
  33. package/tests/fast-mode-client-static.test.mjs +7 -4
  34. package/tests/fixtures/fake-pi.mjs +305 -2
  35. package/tests/footer-provider-usage-visual-static.test.mjs +71 -0
  36. package/tests/git-panel-gitignore-static.test.mjs +104 -0
  37. package/tests/http-endpoints-harness.test.mjs +228 -2
  38. package/tests/interaction-state-stability-static.test.mjs +271 -0
  39. package/tests/mobile-continuity-tablet-static.test.mjs +55 -0
  40. package/tests/mobile-foundation-static.test.mjs +71 -0
  41. package/tests/mobile-phone-experience-static.test.mjs +65 -0
  42. package/tests/mobile-shell-state.test.mjs +69 -0
  43. package/tests/mobile-static.test.mjs +246 -39
  44. package/tests/mobile-transcript-cache-characterization.test.mjs +34 -0
  45. package/tests/native-parity-harness.test.mjs +2 -0
  46. package/tests/npm-command.test.mjs +64 -1
  47. package/tests/open-issue-wizard-static.test.mjs +2 -1
  48. package/tests/queue-edit-reorder-static.test.mjs +9 -1
  49. package/tests/queue-mutation-contract.test.mjs +22 -0
  50. package/tests/service-worker-lifecycle.test.mjs +120 -0
  51. package/tests/side-panel-section-reorder-static.test.mjs +68 -0
  52. package/tests/sse-backpressure-harness.test.mjs +137 -0
  53. package/tests/stats-dashboard-static.test.mjs +266 -0
  54. package/tests/streaming-ui-coupling.test.mjs +7 -1
  55. package/tests/subagent-gate-visibility.test.mjs +18 -2
  56. package/tests/subagent-launch-slot-state.test.mjs +32 -0
  57. package/tests/subagent-launch-slots-static.test.mjs +8 -2
  58. package/tests/subagents-helper.test.mjs +90 -0
  59. package/tests/terminal-tab-workspace-static.test.mjs +1 -1
  60. package/tests/update-commands.test.mjs +4 -0
  61. package/tests/workspace-files-live-updates-static.test.mjs +76 -0
  62. package/tests/workspace-files-live-watcher.test.mjs +95 -0
  63. package/webui-rpc-helper.mjs +175 -3
@@ -67,7 +67,7 @@ assert.match(html, /id="newTabChooseDirectoryButton" class="terminal-new-tab-men
67
67
  assert.match(html, /id="newTabWorktreeButton" class="terminal-new-tab-menu-item composer-publish-menu-item"[\s\S]*<span>Branch Worktree…<\/span>/, "new-tab menu should offer branch worktree tabs");
68
68
  assert.match(html, /id="closeAllTabsButton"[\s\S]*?>Close all Tabs<\/button>/, "tab header should expose a top-right close-all tabs action");
69
69
  assert.match(html, /id="sidePanelBackdrop"/, "mobile side panel needs an overlay/backdrop close target");
70
- assert.match(html, /<div class="side-panel-heading">[\s\S]*<strong class="side-panel-title">Control Deck<\/strong>[\s\S]*<div class="side-panel-version-row"[\s\S]*<button id="piVersionButton"[\s\S]*aria-controls="piReleaseNotesDialog"[\s\S]*<button id="webuiVersionButton"[\s\S]*aria-controls="confirmationDialog"[\s\S]*id="webuiDevBadge"/, "Control Deck header should keep its title separate from an aligned version and build row");
70
+ assert.match(html, /<div class="side-panel-heading">[\s\S]*<strong class="side-panel-title">Control Deck<\/strong>[\s\S]*<div class="side-panel-version-row"[\s\S]*<button id="piVersionButton"[\s\S]*aria-controls="piReleaseNotesDialog"[\s\S]*<button id="webuiVersionButton"[\s\S]*aria-controls="webuiPackageDialog"[\s\S]*id="webuiDevBadge"/, "Control Deck header should keep its title separate from an aligned version and build row");
71
71
  assert.match(html, /<div class="side-panel-brand-row">[\s\S]*<span class="side-panel-kicker">Pi Web UI<\/span>[\s\S]*<a class="sponsor-link" href="https:\/\/github\.com\/sponsors\/Firstp1ck" target="_blank" rel="noopener noreferrer" aria-label="Sponsor Firstp1ck on GitHub"[^>]*>♡<\/a>/, "Control Deck brand should expose a subtle, accessible sponsor link beside the Pi Web UI name");
72
72
  assert.match(html, /<dialog id="piReleaseNotesDialog"[\s\S]*id="piReleaseNotesTitle"[\s\S]*id="piReleaseNotesStatus"[\s\S]*id="piReleaseNotesBody"[\s\S]*id="piReleaseNotesGithubLink"/, "Pi release notes should use a dedicated accessible dialog");
73
73
  assert.doesNotMatch(html, /Safer option|confirmationAlternative/, "shared confirmation dialogs should not render a safer-option row");
@@ -175,6 +175,7 @@ assert.match(html, /id="codexUsageBox"/, "side panel should expose Codex subscri
175
175
  assert.match(html, /data-side-panel-section="codex-usage"/, "Codex usage should live in a collapsible side-panel section");
176
176
  assert.match(html, /data-side-panel-section="subagents"[\s\S]*class="side-panel-section-label">Subagents<\/span>[\s\S]*id="subagentCountBadge"[\s\S]*class="subagents-help"[\s\S]*<code>subagent<\/code>[\s\S]*<code>subagent_gate<\/code>[\s\S]*bounded retries or a success quorum[\s\S]*id="subagentsBox"/, "side panel should explain ordinary delegation and retry-gate workflows with a live count");
177
177
  assert.match(html, /id="subagentOpenModeSelect"[\s\S]*<option value="overlay">Overlay<\/option>[\s\S]*<option value="tab">Tab \/ terminal<\/option>[\s\S]*id="subagentOpenModeStatus"/, "Subagents should offer a browser-persisted overlay or terminal-tab opening choice");
178
+ assert.match(html, /class="subagents-status-row"[\s\S]*id="subagentsStatus"[\s\S]*id="subagentsClearFinishedButton"[^>]*disabled[^>]*>Clear finished<\/button>/, "Subagents should expose a clear-finished control beside its live status");
178
179
  const subagentCancelDialogHtml = html.match(/<dialog id="subagentCancelDialog"[\s\S]*?<\/dialog>/)?.[0] || "";
179
180
  assert.match(subagentCancelDialogHtml, /id="subagentCancelDialogTitle">Cancel subagent<[\s\S]*id="subagentCancelDialogSubtitle"/, "subagent cancellation should use a titled dialog with dynamic target context");
180
181
  assert.match(subagentCancelDialogHtml, /<select id="subagentCancelReason">[\s\S]*<option value="" selected>No reason<\/option>[\s\S]*Wrong model\/provider\/thinking effort[\s\S]*Wrong agent or task[\s\S]*Taking too long[\s\S]*Wrong approach or direction[\s\S]*Output no longer needed[\s\S]*Started by mistake[\s\S]*<option value="Other">Other<\/option>/, "subagent cancellation should offer every approved optional reason");
@@ -188,6 +189,56 @@ assert.match(html, /id="subagentLaunchSlotScope"[^>]*aria-describedby="subagentL
188
189
  assert.match(html, /id="subagentLaunchSlotsAnnouncer"[^>]*aria-live="polite"[^>]*aria-atomic="true"/, "launch-slot additions and removals should have a dedicated live announcement");
189
190
  assert.match(css, /\.subagent-launch-slots-reload-actions span \{\s*flex: 1 1 auto;\s*min-width: min\(12rem, 100%\);/, "narrow launch-slot reload prompts should size from their content instead of reserving a tall fixed flex basis");
190
191
  assert.match(html, /id="subagentTerminalView"[\s\S]*Subagent · view only[\s\S]*id="subagentTerminalTranscript"[\s\S]*id="subagentTerminalStatus"[^>]*aria-live="off"[\s\S]*id="subagentTerminalInput"[^>]*placeholder="View only — send messages from the parent terminal"[^>]*disabled[\s\S]*Use its parent terminal to interact with the run/, "dedicated subagent tabs should expose a view-only transcript, non-announcing routine status, and disabled input");
192
+ const subagentTerminalCardsHtml = html.match(/<footer id="subagentTerminalCards"[\s\S]*?<\/footer>/)?.[0] || "";
193
+ assert.match(subagentTerminalCardsHtml, /^<footer id="subagentTerminalCards"[^>]*class="subagent-terminal-cards"[^>]*aria-label="Subagent session telemetry"[^>]*>[\s\S]*<dl class="subagent-terminal-card-list">/, "dedicated subagent telemetry should use a labelled footer and definition list");
194
+ const subagentTerminalCards = [
195
+ ["pi", "subagentTerminalCardPi", "PI", "—"],
196
+ ["speed", "subagentTerminalCardSpeed", "Speed", "—"],
197
+ ["context", "subagentTerminalCardContext", "Context", "—"],
198
+ ["model", "subagentTerminalCardModel", "Model", "unknown"],
199
+ ["effort", "subagentTerminalCardEffort", "Effort", "unknown"],
200
+ ["tokens", "subagentTerminalCardTokens", "Tokens", "—"],
201
+ ];
202
+ assert.equal((subagentTerminalCardsHtml.match(/\bdata-subagent-card=/g) || []).length, 6, "dedicated subagent telemetry should retain exactly six card slots");
203
+ for (const [slot, id, label, fallback] of subagentTerminalCards) {
204
+ assert.equal((subagentTerminalCardsHtml.match(new RegExp(`data-subagent-card="${slot}"`, "g")) || []).length, 1, `${slot} telemetry card should have one stable slot`);
205
+ assert.match(subagentTerminalCardsHtml, new RegExp(`<div[^>]*data-subagent-card="${slot}"[^>]*>[\\s\\S]*?<dt[^>]*>${label}<\\/dt>[\\s\\S]*?<dd id="${id}"[^>]*>${fallback}<\\/dd>`), `${slot} telemetry card should expose a labelled definition with an honest initial fallback`);
206
+ }
207
+ assert.match(subagentTerminalCardsHtml, /data-subagent-card="tokens"[^>]*title="[^"]*bounded recent child-session scan/, "token totals should disclose their bounded recent-session scope");
208
+ const subagentTerminalTelemetryNumberSource = appFunctionSource("subagentTerminalTelemetryNumber", "formatSubagentTerminalTelemetryTokens");
209
+ const formatSubagentTerminalTelemetryTokensSource = appFunctionSource("formatSubagentTerminalTelemetryTokens", "formatSubagentTerminalTelemetryText");
210
+ const formatSubagentTerminalTelemetryTextSource = appFunctionSource("formatSubagentTerminalTelemetryText", "renderSubagentTerminalCards");
211
+ const renderSubagentTerminalCardsSource = appFunctionSource("renderSubagentTerminalCards", "renderSubagentTerminalView");
212
+ assert.match(renderSubagentTerminalCardsSource, /agent\?\.telemetry/, "terminal telemetry cards should consume the normalized telemetry object");
213
+ assert.doesNotMatch(renderSubagentTerminalCardsSource, /\b(?:transcript|recentOutput|messages|content)\b/i, "terminal telemetry cards must not derive metrics from transcript output");
214
+ const telemetryCardElements = Object.fromEntries(subagentTerminalCards.map(([, id]) => [id, { textContent: "" }]));
215
+ vm.runInNewContext(`${subagentTerminalTelemetryNumberSource}\n${formatSubagentTerminalTelemetryTokensSource}\n${formatSubagentTerminalTelemetryTextSource}\n${renderSubagentTerminalCardsSource}\nrenderSubagentTerminalCards({ telemetry: [] });`, {
216
+ elements: telemetryCardElements,
217
+ formatFooterTokenCount: (value) => String(value),
218
+ });
219
+ assert.deepEqual(Object.fromEntries(Object.entries(telemetryCardElements).map(([id, element]) => [id, element.textContent])), {
220
+ subagentTerminalCardPi: "—",
221
+ subagentTerminalCardSpeed: "—",
222
+ subagentTerminalCardContext: "— / unknown",
223
+ subagentTerminalCardModel: "unknown",
224
+ subagentTerminalCardEffort: "unknown",
225
+ subagentTerminalCardTokens: "↑— · ↓—",
226
+ }, "missing or invalid telemetry should keep every card visible with explicit unknown fallbacks");
227
+ vm.runInNewContext(`${subagentTerminalTelemetryNumberSource}\n${formatSubagentTerminalTelemetryTokensSource}\n${formatSubagentTerminalTelemetryTextSource}\n${renderSubagentTerminalCardsSource}\nrenderSubagentTerminalCards({ telemetry: { promptInjectionTokens: 1200, tokenSpeed: 42.5, contextTokens: 1234, contextWindow: 9999, model: "provider/model", effort: "high", inputTokens: 12, outputTokens: 34 } });`, {
228
+ elements: telemetryCardElements,
229
+ formatFooterTokenCount: (value) => String(value),
230
+ });
231
+ assert.deepEqual(Object.fromEntries(Object.entries(telemetryCardElements).map(([id, element]) => [id, element.textContent])), {
232
+ subagentTerminalCardPi: "1200",
233
+ subagentTerminalCardSpeed: "42.5 tok/s",
234
+ subagentTerminalCardContext: "1234 / 9999",
235
+ subagentTerminalCardModel: "provider/model",
236
+ subagentTerminalCardEffort: "high",
237
+ subagentTerminalCardTokens: "↑12 · ↓34",
238
+ }, "terminal telemetry cards should render only normalized telemetry values");
239
+ assert.match(css, /\.subagent-terminal-card-list\s*\{[\s\S]*?display:\s*grid;[\s\S]*?grid-template-columns:\s*repeat\(auto-fit,\s*minmax\(/, "telemetry cards should wrap responsively through a grid rather than require a fixed row");
240
+ assert.match(css, /@media\s*\([^)]*max-width[^)]*\)\s*\{[\s\S]*?\.subagent-terminal-card-list\s*\{[\s\S]*?grid-template-columns:\s*minmax\(0,\s*1fr\)/, "narrow viewports should collapse telemetry cards without horizontal overflow");
241
+ assert.match(readme, /exactly six telemetry cards: PI, measured token speed, context, model, effort, and input\/output tokens from a bounded recent session scan; unavailable or legacy evidence remains `—` or `unknown` rather than an estimate/, "README should document each subagent telemetry card, bounded scan scope, and honest unknown behavior");
191
242
  assert.doesNotMatch(html, /id="subagentOverlayDialog"/, "subagent output should not use a blocking modal dialog");
192
243
  assert.match(html, /data-side-panel-section="session"[\s\S]*data-side-panel-section="subagents"[\s\S]*data-side-panel-section="queue"/, "Subagents should appear between Session and Queue in the side panel");
193
244
  assert.match(html, /data-side-panel-section="queue"[\s\S]*id="createPromptListButton"[\s\S]*>Create prompt list<\/button>/, "Queue section should expose prompt-list creation");
@@ -371,7 +422,8 @@ assert.match(css, /@media \(max-width: 1050px\)[\s\S]*?body:not\(\.side-panel-co
371
422
  assert.match(css, /@media \(max-width: 1050px\)[\s\S]*?\.side-panel-backdrop \{[\s\S]*?z-index:\s*110;[\s\S]*?\.side-panel \{[\s\S]*?z-index:\s*111;[\s\S]*?body\.side-panel-collapsed \.terminal-tabs-shell \{[\s\S]*?padding-right:\s*4\.85rem;[\s\S]*?\.side-panel-expand-button \{[\s\S]*?z-index:\s*120/, "narrow side-panel overlay and expand button should stay above and reserve space from terminal header controls");
372
423
  assert.match(css, /@media \(max-width: 720px\), \(max-device-width: 720px\), \(pointer: coarse\) and \(hover: none\)[\s\S]*?body\.side-panel-collapsed \.terminal-tabs-shell \{ padding-right:\s*calc\(44px \+ 0\.8rem\); \}[\s\S]*?\.side-panel-expand-button \{[\s\S]*?z-index:\s*120[\s\S]*?\.side-panel-backdrop \{[\s\S]*?z-index:\s*110;[\s\S]*?\.side-panel \{[\s\S]*?z-index:\s*111;/, "mobile side-panel controls should not hide behind terminal header buttons");
373
424
  assert.match(css, /button, select, input \{ min-height: 44px; \}/, "base controls should meet 44px touch-target height");
374
- assert.match(css, /\.composer-row button \{\n\s+width:\s*100%;\n\s+min-height:\s*40px/, "mobile composer buttons should use compact 40px footer controls");
425
+ // Intent superseded: Phase 0 raises all phone/coarse composer hit areas to 44px.
426
+ assert.match(css, /\.composer-row button \{\n\s+width:\s*100%;\n\s+min-height:\s*44px/, "mobile composer buttons should retain compact layout with 44px footer hit areas");
375
427
  assert.match(css, /\.composer-abort-button,\n\.composer-row button\.primary \{[\s\S]*?min-width:/, "Abort and Send should share stable bottom-row sizing");
376
428
  assert.match(css, /\.composer-abort-button\.long-pressing::after[\s\S]*?animation:\s*abort-long-press-fill var\(--abort-long-press-duration, 3000ms\) linear forwards/, "Abort should expose a visible 3-second long-press progress affordance");
377
429
  assert.match(css, /body\.pi-run-active:not\(\.mobile-keyboard-open\) \.composer-abort-button:not\(\[hidden\]\) \{\n\s+order:\s*1;\n\s+grid-column:\s*span 2;/, "active mobile runs should move Abort to the top row");
@@ -462,7 +514,7 @@ assert.match(css, /\.subagents-help \{[\s\S]*border-left:[\s\S]*font-size:\s*0\.
462
514
  assert.match(css, /\.subagent-launch-slots \{[\s\S]*\.subagent-launch-slot-role \{[\s\S]*\.subagent-launch-slot-controls \{[\s\S]*grid-template-columns: repeat\(2, minmax\(0, 1fr\)\)/, "launch-slot cards should group role slots with paired model and thinking controls");
463
515
  assert.match(css, /@media \(max-width: 720px\), \(max-device-width: 720px\), \(pointer: coarse\) and \(hover: none\) \{[\s\S]*min-height: 44px[\s\S]*\.subagent-launch-slot-scope,[\s\S]*\.subagent-launch-slot-row,[\s\S]*\.subagent-launch-slot-controls \{ grid-template-columns: minmax\(0, 1fr\); \}/, "launch-slot controls should stack with coarse-pointer touch targets");
464
516
  assert.match(css, /\.subagents-box\.has-items[\s\S]*\.subagent-tab-group[\s\S]*\.subagent-agent-row/, "running subagents should render as grouped terminal/session cards");
465
- assert.match(css, /\.subagent-gate-card[\s\S]*\.subagent-gate-status[\s\S]*\.subagent-gate-attempt[\s\S]*\.subagent-gate-attempt-error/, "retry gates should render quorum, attempt status, and failure details");
517
+ assert.match(css, /\.subagent-gate-card \{[\s\S]*gap: 0\.12rem;[\s\S]*background: transparent;[\s\S]*\.subagent-gate-title \{[\s\S]*display: flex;[\s\S]*\.subagent-gate-attempt \{[\s\S]*min-height: 1\.68rem;[\s\S]*background: transparent;[\s\S]*\.subagent-gate-attempt-identity \{[\s\S]*white-space: nowrap;/, "retry gates should use compact, flat, single-line attempt rows");
466
518
  assert.match(css, /\.subagent-agent-row:hover,[\s\S]*\.subagent-agent-row:focus-visible/, "subagent rows should expose clickable hover and keyboard focus states");
467
519
  assert.match(css, /\.subagent-overlay-widget[\s\S]*\.subagent-overlay-transcript[\s\S]*\.subagent-overlay-message[\s\S]*\.subagent-overlay-close-action/, "subagent output should combine the non-blocking widget shell with the main transcript message styling");
468
520
  assert.match(css, /\.terminal-tab-subagent-indicator[\s\S]*\.terminal-tab-subagent[\s\S]*\.subagent-terminal-view[\s\S]*\.subagent-terminal-composer textarea:disabled/, "subagent terminal tabs should be visibly marked and retain an explicit disabled composer");
@@ -470,7 +522,8 @@ assert.match(css, /body\.subagent-terminal-active \.workspace-dashboard,[\s\S]*b
470
522
  assert.match(css, /\.subagent-run-indicator[\s\S]*\.subagent-run-indicator \.run-indicator-meta/, "subagent output should reuse the main live run-indicator treatment with wrapping activity metadata");
471
523
  assert.match(css, /\.subagent-terminal-transcript > \.message \{[\s\S]*width: 100%;[\s\S]*max-width: none;/, "dedicated subagent transcript cards should fill the available tab width");
472
524
  assert.doesNotMatch(css, /\.extension-dialog\.subagent-overlay-dialog/, "subagent output should not retain blocking dialog styles");
473
- assert.match(css, /@keyframes subagent-running-pulse/, "running subagents should expose a live activity indicator");
525
+ assert.match(css, /\.subagent-running-dot \{[\s\S]*background: var\(--ctp-yellow\);[\s\S]*animation: subagent-running-pulse/, "running subagents should expose a blinking yellow activity indicator");
526
+ assert.match(css, /@keyframes subagent-running-pulse/, "running subagents should expose a live activity animation");
474
527
  assert.match(css, /\.optional-feature-pill\.enabled/, "optional features should visually distinguish enabled state");
475
528
  assert.match(css, /\.todo-widget \{[\s\S]*?display:\s*grid/, "todo-progress widget should render as a styled checklist card");
476
529
  assert.match(css, /\.todo-widget-summary \{[\s\S]*?cursor:\s*pointer/, "todo-progress widget should expose a compact expandable summary");
@@ -547,11 +600,12 @@ assert.match(css, /@media \(max-width: 720px\) \{[\s\S]*?\.command-palette-dialo
547
600
  assert.match(css, /@media \(max-width: 720px\) \{[\s\S]*?\.command-palette-item-kind \{[\s\S]*?font-size:\s*var\(--text-xs\);[\s\S]*?\.command-palette-item-label \{ font-size:\s*0\.82rem; \}[\s\S]*?\.command-palette-item-description \{ font-size:\s*var\(--text-xs\); \}/, "mobile command palette result text should respect the typography floor");
548
601
  assert.match(css, /body\.terminal-tabs-left \.chat-panel \{[\s\S]*?grid-template-columns:\s*clamp\(13rem, 18vw, 19rem\) minmax\(0, 1fr\)/, "terminal tabs left layout should split the chat panel into a sidebar and transcript area");
549
602
  assert.match(css, /body\.terminal-tabs-left \.terminal-tabs-shell \{[\s\S]*?grid-column:\s*1;[\s\S]*?grid-row:\s*1 \/ -1;[\s\S]*?flex-direction:\s*column/, "terminal tabs left layout should turn the top tab strip into a vertical sidebar");
550
- assert.match(html, /class="terminal-sidebar-actions"[^>]*aria-label="Tab and workspace actions"[\s\S]*id="splitTabButton"[\s\S]*>Split<\/span>[\s\S]*id="workspaceSaveButton"[\s\S]*>Save workspace<\/span>[\s\S]*id="commandPaletteButton"[\s\S]*>Commands<\/span>[\s\S]*id="workspaceDashboardToggleButton"[\s\S]*>Overview<\/span>/, "tab, save, command, and workspace actions should share one labeled sidebar toolbar");
551
- assert.match(css, /body\.terminal-tabs-left \.terminal-sidebar-actions \{[\s\S]*?display:\s*grid;[\s\S]*?grid-template-columns:\s*repeat\(4, minmax\(0, 1fr\)\);[\s\S]*?body\.terminal-tabs-left \.terminal-sidebar-actions > button \{[\s\S]*?min-height:\s*3\.55rem;/, "left-sidebar actions should render as an equal-width four-button toolbar with readable touch targets");
603
+ assert.match(html, /class="terminal-sidebar-actions"[^>]*aria-label="Tab and workspace actions"[\s\S]*id="splitTabButton"[^>]*aria-label="Split the active terminal to the right"[\s\S]*id="workspaceSaveButton"[^>]*aria-label="Save workspace"[\s\S]*id="commandPaletteButton"[^>]*aria-label="Open command palette"[\s\S]*id="workspaceDashboardToggleButton"[^>]*aria-label="Show workspace overview"/, "tab, save, command, and workspace actions should share one accessibly labelled sidebar toolbar");
604
+ assert.doesNotMatch(html, /terminal-sidebar-action-label/, "left-sidebar action buttons should be icon-only without redundant visible labels");
605
+ assert.match(css, /body\.terminal-tabs-left \.terminal-sidebar-actions \{[\s\S]*?display:\s*grid;[\s\S]*?grid-template-columns:\s*repeat\(4, minmax\(0, 1fr\)\);[\s\S]*?body\.terminal-tabs-left \.terminal-sidebar-actions > button \{[\s\S]*?place-items:\s*center;[\s\S]*?min-height:\s*2\.75rem;[\s\S]*?padding:\s*0\.42rem;/, "left-sidebar actions should render as compact equal-width icon buttons with 44px targets");
552
606
  assert.match(css, /@media \(min-width: 721px\) \{[\s\S]*?body\.terminal-tabs-left \.terminal-sidebar-actions \{[\s\S]*?z-index:\s*130;[\s\S]*?overflow:\s*visible;[\s\S]*?terminal-workspace-save-button\[data-tooltip\]::after,[\s\S]*?terminal-command-palette-button\[data-tooltip\]::after,[\s\S]*?terminal-dashboard-button\[data-tooltip\]::after \{[\s\S]*?bottom:\s*calc\(100% \+ 0\.62rem\);[\s\S]*?z-index:\s*220;[\s\S]*?width:\s*calc\(400% \+ 1\.26rem\);/, "left-sidebar save, command, and overview tooltips should render above the full toolbar without clipping");
553
607
  assert.match(css, /terminal-workspace-save-button\[data-tooltip\]::after \{\s+left:\s*calc\(-100% - 0\.42rem\);[\s\S]*?terminal-command-palette-button\[data-tooltip\]::after \{\s+left:\s*calc\(-200% - 0\.84rem\);[\s\S]*?terminal-dashboard-button\[data-tooltip\]::after \{\s+left:\s*calc\(-300% - 1\.26rem\);/, "left-sidebar tooltips should align to the toolbar edges from their individual buttons");
554
- assert.match(css, /terminal-split-button\[aria-pressed="true"\] \.terminal-sidebar-action-label-split[\s\S]*?display:\s*none;[\s\S]*?terminal-split-button\[aria-pressed="true"\] \.terminal-sidebar-action-label-unsplit[\s\S]*?display:\s*block;/, "split toolbar label should change to Unsplit with the pressed state");
608
+ assert.match(app, /elements\.splitTabButton\.setAttribute\("aria-pressed", canShowSplit \? "true" : "false"\);[\s\S]*?applyStyledTooltip\(elements\.splitTabButton, label, \{ ariaLabel: label \}\);/, "icon-only split action should expose its Split or Close state through accessibility text and the tooltip");
555
609
  assert.match(css, /body\.terminal-tabs-left \.terminal-close-all-button \{[\s\S]*?margin-top:\s*0;[\s\S]*?justify-content:\s*center;[\s\S]*?text-align:\s*center;/, "left-sidebar close-all action should remain a separate centered destructive row");
556
610
  assert.match(css, /body\.terminal-tabs-left \.terminal-tabs \{[\s\S]*?flex-direction:\s*column/, "terminal tabs left layout should stack tabs vertically");
557
611
  assert.match(css, /body\.terminal-tabs-left \.terminal-tab-group-menu \{[\s\S]*?inset:\s*0 auto auto 100%;[\s\S]*?padding-left:\s*var\(--terminal-left-dropdown-bridge\)/, "left-sidebar grouped tab menus should include a hover bridge so they do not vanish between button and dropdown");
@@ -637,7 +691,8 @@ assert.match(css, /\.footer-model-picker[\s\S]*?position:\s*absolute[\s\S]*?left
637
691
  assert.match(css, /@media \(max-width: 720px\), \(max-device-width: 720px\), \(pointer: coarse\) and \(hover: none\)[\s\S]*?\.footer-model-picker \{[\s\S]*?position:\s*fixed/, "mobile footer model picker should escape footer-details stacking as a fixed overlay on narrow, device-width-narrow, or touch-only devices");
638
692
  assert.match(css, /bottom:\s*var\(--footer-model-picker-bottom/, "mobile footer model picker should be anchored by a JS-computed viewport offset");
639
693
  assert.match(css, /\.footer-model-option\.active/, "footer model picker should style the selected scoped model");
640
- assert.match(css, /\.model-search-result-main,\n\.model-search-result-name \{[\s\S]*?line-height:\s*1\.3;/, "side-panel model titles should reserve enough line height to avoid clipping heavy font glyphs");
694
+ assert.match(css, /\.side-panel-controls \.model-search-result \{[\s\S]*?align-content:\s*center;[\s\S]*?min-height:\s*3\.2rem;[\s\S]*?padding:\s*0\.48rem 0\.62rem;/, "side-panel model rows should override generic control-button sizing and center both text lines");
695
+ assert.match(css, /\.model-search-result-main,\n\.model-search-result-name \{[\s\S]*?line-height:\s*1\.4;/, "side-panel model titles should reserve enough line height to avoid clipping heavy font glyphs");
641
696
  assert.match(app, /async function createPathPickerDirectory\(\)/, "cwd picker should implement create-directory behavior in the browser");
642
697
  assert.match(app, /function renderPathPickerDirectoryList\(\)[\s\S]*pathPickerDirectoryMatchesSearch/, "cwd picker should filter current-directory entries in the browser");
643
698
  assert.match(app, /elements\.pathPickerSearchInput\.addEventListener\("input", renderPathPickerDirectoryList\)/, "cwd picker should update directory matches as the user types");
@@ -679,7 +734,8 @@ assert.match(app, /const MOBILE_VIEW_QUERY = "\(max-width: 720px\), \(max-device
679
734
  assert.match(app, /const SIDE_PANEL_OVERLAY_QUERY = "\(max-width: 1050px\), \(max-device-width: 720px\), \(pointer: coarse\) and \(hover: none\)"/, "side-panel overlay mode should also activate at the stacked narrow layout breakpoint");
680
735
  assert.match(app, /function isSidePanelOverlayView\(\)[\s\S]*sidePanelOverlayMedia\?\.matches/, "side-panel overlay detection should be separate from full mobile mode");
681
736
  assert.match(app, /const showBackdrop = !collapsed && isSidePanelOverlayView\(\)/, "side-panel backdrop should show for the overlay breakpoint, not only phone layouts");
682
- assert.match(app, /function restoreSidePanelState\(\) \{\n\s+if \(isSidePanelOverlayView\(\)\) \{\n\s+setSidePanelCollapsed\(true, \{ persist: false \}\);/, "side-panel should start collapsed in narrow overlay mode");
737
+ // Intent preserved for legacy; v2 suppresses this legacy surface writer.
738
+ assert.match(app, /function restoreSidePanelState\(\) \{\n\s+if \(isMobileShellV2Active\(\)\) return;\n\s+if \(isSidePanelOverlayView\(\)\) \{\n\s+setSidePanelCollapsed\(true, \{ persist: false \}\);/, "legacy side-panel should start collapsed in narrow overlay mode");
683
739
  assert.match(app, /function bindSidePanelOverlayViewChanges\(\)/, "side-panel overlay breakpoint changes should be monitored separately from full mobile changes");
684
740
  assert.match(app, /if \(isSidePanelOverlayView\(\) && !document\.body\.classList\.contains\("side-panel-collapsed"\)\)/, "Escape should close the side-panel overlay at narrow widths");
685
741
  assert.match(app, /const THEME_STORAGE_KEY = "pi-webui-theme"/, "theme selection should be persisted in browser storage");
@@ -755,7 +811,7 @@ assert.match(server, /PI_WEBUI_RESTORE_TABS: JSON\.stringify\(restorableTabs \|\
755
811
  assert.match(server, /if \(webuiDevServer\) env\.PI_WEBUI_DEV = "1";/, "server restart should explicitly preserve dev mode");
756
812
  assert.match(server, /async function piUpdateCommandSupportsAll\(command\)[\s\S]*runCommand\(command\.command, command\.args \|\| \[\][\s\S]*piUpdateHelpSupportsAll/, "server should check the selected Pi executable's update help");
757
813
  assert.match(server, /const supportsAll = all && await piUpdateCommandSupportsAll\(await resolveCommand\(\["update", "--help"\]\)\)[\s\S]*piUpdateCommandSteps\(\{ all, supportsAll \}\)/, "server should prefer --all only when the capability check succeeds");
758
- assert.match(server, /async function resolveUpdateTasks\(\{ all = false \} = \{\}\)[\s\S]*const piTasks = await resolvePiUpdateCommands\(\{ all \}\)[\s\S]*if \(!all\) return uniqueUpdateTasks\(piTasks\)[\s\S]*currentWebuiPackageUpdateTask\(\)[\s\S]*agentPackageRootUpdateTask\(\)[\s\S]*projectPackageRootUpdateTasks\(\)[\s\S]*npmGlobalPackageRootUpdateTask\(\)[\s\S]*bunGlobalPackageRootUpdateTask\(\)/, "server all-update should run the selected Pi plan plus detected local/global Pi package root tasks");
814
+ assert.match(server, /async function resolveUpdateTasks\(\{ all = false \} = \{\}\)[\s\S]*const piTasks = await resolvePiUpdateCommands\(\{ all \}\)[\s\S]*if \(!all\) return uniqueUpdateTasks\(piTasks\)[\s\S]*currentWebuiPackageUpdateTask\(npmRuntime\)[\s\S]*agentPackageRootUpdateTask\(npmRuntime\)[\s\S]*projectPackageRootUpdateTasks\(npmRuntime\)[\s\S]*npmGlobalPackageRootUpdateTask\(npmRuntime\)[\s\S]*bunGlobalPackageRootUpdateTask\(\)/, "server all-update should run the selected Pi plan plus detected local/global Pi package root tasks with install-aware npm resolution");
759
815
  assert.match(server, /const UPDATE_PACKAGE_NAMES = \[\.\.\.new Set\(\[[\s\S]*WEBUI_CONTROLLED_PACKAGES[\s\S]*OPTIONAL_FEATURE_PACKAGES\.values\(\)/, "package-inclusive updates should include Web UI controlled Optional Feature packages");
760
816
  assert.match(app, /const commandText = all \? '"pi update --all" when supported, otherwise "pi update --self" followed by "pi update --extensions"' : '"pi update --self"'/, "frontend update confirmation should describe capability selection and fallback");
761
817
  assert.match(app, /Optional Features, and detected Pi package roots/, "frontend all-update confirmation should describe optional-feature and detected-root coverage");
@@ -820,6 +876,7 @@ assert.match(app, /if \(request\.replayed\) addEvent\(`recovered pending \$\{req
820
876
  assert.match(app, /case "webui_extension_ui_cancelled":/, "frontend should close dialogs cancelled by backend abort handling");
821
877
  assert.match(app, /case "webui_extension_ui_resolved":[\s\S]*?removeQueuedDialogRequests\(\[event\.id\]\)/, "frontend should close dialogs resolved by another connected browser");
822
878
  assert.match(app, /if \(responseId && activeDialog && String\(activeDialog\.id \|\| ""\) !== responseId\) return;/, "dialog response cleanup should not close the next queued dialog after a resolve-event race");
879
+ assert.match(app, /if \(runIndicatorIsActive\(\)\) \{\s*setRunIndicatorActivity\("Continuing after your response…"\);[\s\S]*?scheduleRefreshState\(120, tabContext\);\s*\}/, "extension UI responses should promptly reconcile canonical state so background release commands cannot leave a stale running indicator");
823
880
  assert.match(app, /function parseTodoProgressWidget\(lines\)/, "todo-progress widgets should be parsed from extension widget lines");
824
881
  assert.ok(app.includes("const goalLine = cleanLines.find((line) => /^Goal\\s*[::]/i.test(line));"), "todo-progress parser should preserve an optional Goal line from extension widget lines");
825
882
  assert.ok(app.includes("if (todo.goal) summary.append(make(\"div\", \"todo-widget-goal\", `Goal: ${todo.goal}`));"), "todo-progress widget should display the goal above the progress header");
@@ -851,15 +908,87 @@ assert.match(
851
908
  );
852
909
  assert.match(app, /function renderCodexUsage\(\)/, "frontend should render Codex usage buckets in the side panel");
853
910
  assert.match(app, /function renderSubagents\(\)[\s\S]*subagentTabsWithRunningAgents\(\)[\s\S]*totalGates[\s\S]*renderSubagentTabGroup\(tab\)/, "frontend should group running subagents and retained retry gates by terminal and session");
854
- assert.match(app, /function renderSubagents\(\)[\s\S]*latestSubagents\?\.runningAgents[\s\S]*subagentCountBadge\.textContent = String\(totalAgents\)/, "the subagent count badge should count running agents only, not retained rows or gates");
855
- assert.match(app, /function renderSubagentRun\(tab, run\)[\s\S]*subagentRunStateLabel\(run\)[\s\S]*Dismiss finished run[\s\S]*dismissSubagentRun\(tab, run\)/, "terminal subagent rows should show retained state badges and dismiss only terminal runs");
856
- assert.match(app, /function renderSubagentRun\(tab, run\)[\s\S]*subagentRunCanCancel\(run\)[\s\S]*openSubagentCancelDialog\(tab, run\)/, "running subagent rows should route cancel through the shared dialog");
911
+ assert.match(app, /function renderSubagents\(\)[\s\S]*latestSubagents\?\.runningAgents[\s\S]*subagentCountBadge\.textContent = String\(totalAgents\)/, "the subagent count badge should count running agents once while retry-gated attempts render only inside their gate");
912
+ const compactSubagentAgentSource = appFunctionSource("renderSubagentAgent", "renderSubagentRun");
913
+ const compactSubagentRunSource = appFunctionSource("renderSubagentRun", "subagentGateStatusLabel");
914
+ assert.match(compactSubagentAgentSource, /const \[model, thinking\] = subagentExecutionValues\(agent\)[\s\S]*identity\.append\([\s\S]*"subagent-agent-name", name[\s\S]*"subagent-agent-inline-meta", `· \$\{model\} · \$\{thinking\}`[\s\S]*row\.append\(dot, identity, open\)/, "side-panel agent rows should show type, provider\/model, and thinking effort on one compact line");
915
+ assert.doesNotMatch(compactSubagentAgentSource, /subagent-agent-meta|subagentExecutionFacts|subagentSourceLabel|subagentRunElapsed|currentTool/, "side-panel agent rows should leave all other execution metadata to the selected subagent view");
916
+ assert.doesNotMatch(compactSubagentRunSource, /subagent-run-(?:header|title|meta|state)|`Run \$\{/, "side-panel run groups should not repeat IDs, metadata headers, or state badges");
917
+ assert.match(compactSubagentRunSource, /Dismiss finished run[\s\S]*dismissSubagentRun\(tab, run\)/, "compact terminal subagent runs should retain their dismiss action");
918
+ assert.match(compactSubagentRunSource, /subagentRunCanCancel\(run\)[\s\S]*Cancel entire subagent run[\s\S]*openSubagentCancelDialog\(tab, run\)/, "compact running subagent runs should retain whole-run cancellation through the shared dialog");
919
+ assert.match(app, /function renderSubagentTerminalView\(\)[\s\S]*subagentRunElapsed\(view\.run\)[\s\S]*subagentExecutionFacts\(agent\)[\s\S]*parent \$\{parent\?\.title[\s\S]*run \$\{view\.runId\}/, "the dedicated subagent view should own elapsed, execution, parent, and run details removed from the side panel");
920
+ const subagentTerminalViewGroupsSource = appFunctionSource("subagentTerminalViewGroups", "renderSubagentTerminalTab");
921
+ const subagentTerminalGroupingContext = vm.createContext({
922
+ subagentTerminalViews: new Map([
923
+ ["a-1", { id: "a-1", parentTabId: "workspace-a", parentTitle: "Workspace A", openedAt: 1 }],
924
+ ["b-1", { id: "b-1", parentTabId: "workspace-b", parentTitle: "Workspace B", openedAt: 2 }],
925
+ ["a-2", { id: "a-2", parentTabId: "workspace-a", parentTitle: "Workspace A", openedAt: 3 }],
926
+ ]),
927
+ });
928
+ vm.runInContext(`${subagentTerminalViewGroupsSource}\nthis.groupedSubagentViews = subagentTerminalViewGroups();`, subagentTerminalGroupingContext);
929
+ assert.deepEqual(JSON.parse(JSON.stringify(subagentTerminalGroupingContext.groupedSubagentViews.map((group) => ({ key: group.key, parentTabId: group.parentTabId, viewIds: group.views.map((view) => view.id) })))), [
930
+ { key: "subagents:workspace-a", parentTabId: "workspace-a", viewIds: ["a-1", "a-2"] },
931
+ { key: "subagents:workspace-b", parentTabId: "workspace-b", viewIds: ["b-1"] },
932
+ ], "dedicated subagent views should group only with siblings spawned by the same parent workspace");
933
+ assert.match(app, /function renderTabs\(\)[\s\S]*const subagentGroups = subagentTerminalViewGroups\(\)[\s\S]*group\.views\.length > 1[\s\S]*renderSubagentTerminalTabGroup\(group\)[\s\S]*renderSubagentTerminalTab\(group\.views\[0\]\)/, "the tab strip should collapse same-workspace subagent siblings while leaving a single view standalone");
934
+ const renderSubagentTerminalTabSource = appFunctionSource("renderSubagentTerminalTab", "renderSubagentTerminalTabGroup");
935
+ assert.match(renderSubagentTerminalTabSource, /groupItem = false[\s\S]*terminal-tab-group-item[\s\S]*terminal-tab-group-item-button[\s\S]*activateSubagentTerminalView\(view\.id\)/, "subagent tabs should remain individually activatable inside a workspace group menu");
936
+ const renderSubagentTerminalTabGroupSource = appFunctionSource("renderSubagentTerminalTabGroup", "openSubagentOutput");
937
+ assert.match(renderSubagentTerminalTabGroupSource, /groupViews\.filter\(subagentTerminalViewIsRunning\)[\s\S]*group\.parentTitle[\s\S]*terminal-tab-subagent-group[\s\S]*count: groupViews\.length[\s\S]*renderSubagentTerminalTab\(view, \{ groupItem: true \}\)/, "workspace subagent groups should expose their parent title, aggregate state, count, and child-view menu");
938
+ const closeSubagentTerminalGroupStart = app.indexOf("function closeSubagentTerminalGroup(");
939
+ const closeSubagentTerminalGroupEnd = app.indexOf("\nasync function copySubagentTerminalOutput(", closeSubagentTerminalGroupStart);
940
+ assert.ok(closeSubagentTerminalGroupStart >= 0 && closeSubagentTerminalGroupEnd > closeSubagentTerminalGroupStart, "closeSubagentTerminalGroup should remain a standalone frontend helper");
941
+ const closeSubagentTerminalGroupSource = app.slice(closeSubagentTerminalGroupStart, closeSubagentTerminalGroupEnd);
942
+ assert.match(closeSubagentTerminalGroupSource, /subagentTerminalViews\.delete\(view\.id\)[\s\S]*renderTabs\(\)/, "closing a workspace subagent group should remove its view tabs as one UI operation");
943
+ assert.doesNotMatch(closeSubagentTerminalGroupSource, /cancel|\/api\/subagents/, "closing a workspace subagent group must not stop its child runs");
944
+ assert.match(css, /\.subagent-tab-title \{[\s\S]*container-type: inline-size;[\s\S]*flex: 1 1 0;[\s\S]*min-width: 0;[\s\S]*\.subagent-tab-title strong \{[\s\S]*font-size: clamp\(0\.64rem, calc\(0\.5rem \+ 0\.65cqi\), 0\.78rem\);[\s\S]*\.subagent-tab-count \{[\s\S]*flex: 0 0 auto;[\s\S]*white-space: nowrap;/, "subagent titles should scale with their available inline width while summary badges stay fixed and text can still truncate");
945
+ assert.match(css, /\.subagent-agent-list \{[\s\S]*gap: 0\.16rem;[\s\S]*\.subagent-agent-row \{[\s\S]*min-height: 1\.75rem;[\s\S]*background: transparent;[\s\S]*\.subagent-agent-identity \{[\s\S]*display: flex;[\s\S]*white-space: nowrap;[\s\S]*\.subagent-agent-inline-meta \{[\s\S]*text-overflow: ellipsis;[\s\S]*white-space: nowrap;[\s\S]*\.subagent-run \{[\s\S]*grid-template-columns: minmax\(0, 1fr\) auto;[\s\S]*border: 0;/, "the inline subagent monitor should keep type, model, and effort in compact flat rows without overflow");
857
946
  assert.match(app, /function renderSubagentOverlayWidget\(\)[\s\S]*openSubagentCancelDialog\(tab, selection\.run, agent\)[\s\S]*subagent-overlay-cancel-action/, "running overlays should route cancel through the shared dialog");
858
947
  assert.match(app, /subagentTerminalCancelButton[\s\S]*openSubagentCancelDialog\(view\.tab \|\| \{ tabId: view\.parentTabId, tabTitle: view\.parentTitle \}, view\.run, view\.data\?\.agent \|\| view\.agent\)/, "running terminal headers should route cancel through the shared dialog");
859
948
  assert.match(app, /function openSubagentCancelDialog\(tab, run, agent = null\)[\s\S]*agentCount[\s\S]*The entire run will be stopped[\s\S]*subagentCancelDialog\.showModal\(\)[\s\S]*async function submitSubagentCancel\(\)[\s\S]*api\("\/api\/subagents\/cancel", \{[\s\S]*method: "POST",[\s\S]*scoped: false,[\s\S]*tab: selection\.tabId,[\s\S]*runId: selection\.runId/, "the shared cancel dialog should honestly describe and submit whole-run cancellation with optional reason/note data");
860
949
  assert.doesNotMatch(app, /body: \{\n\s+tab: selection\.tabId,\n\s+runId: selection\.runId,\n\s+\.\.\.\(selection\.agentId/, "the frontend must not imply unsupported per-agent cancellation in its request contract");
861
950
  assert.match(app, /async function dismissSubagentRun\(tab, run\)[\s\S]*api\("\/api\/subagents\/dismiss", \{[\s\S]*method: "POST",[\s\S]*scoped: false,[\s\S]*body: \{ tab: tab\.tabId, runId: run\.id \}/, "finished-run dismiss controls should call the owning tab endpoint");
862
- assert.match(app, /function materializeRetainedSubagentTerminalViews\(\)[\s\S]*restoreKey = `\$\{tab\.tabId\}\\u0000\$\{tab\.sessionFile[\s\S]*run\?\.status === "running"[\s\S]*ensureSubagentTerminalView/, "terminal mode should materialize restored retained agent views once per parent session identity without touching overlay mode");
951
+ assert.match(app, /function finishedSubagentRunSelections\(data = latestSubagents\)[\s\S]*ungatedSubagentRuns\(tab\)[\s\S]*run\.status !== "running" && run\.source !== "workflow"[\s\S]*async function clearFinishedSubagentRuns\(\)[\s\S]*for \(const selection of selections\)[\s\S]*api\("\/api\/subagents\/dismiss", \{[\s\S]*body: \{ tab: selection\.tabId, runId: selection\.runId \}[\s\S]*subagentsClearFinishedButton\.disabled = subagentsLoading \|\| subagentsClearingFinished \|\| finishedRuns\.length === 0/, "clear-finished should dismiss visible terminal ordinary runs while preserving retry-gated, active, and workflow runs");
952
+ assert.match(app, /subagentsClearFinishedButton\?\.addEventListener\("click", \(\) => \{[\s\S]*clearFinishedSubagentRuns\(\)/, "the clear-finished button should invoke the guarded bulk dismissal action");
953
+ assert.match(css, /\.subagents-status-row \{[\s\S]*display: flex;[\s\S]*\.subagents-clear-finished-button \{[\s\S]*min-height: 2rem;/, "the clear-finished control should share a compact responsive status row");
954
+ const clearFinishedSourceStart = app.indexOf("function finishedSubagentRunSelections(");
955
+ const clearFinishedSourceEnd = app.indexOf("\nfunction subagentOverlayTranscriptMessages(", clearFinishedSourceStart);
956
+ assert.ok(clearFinishedSourceStart >= 0 && clearFinishedSourceEnd > clearFinishedSourceStart, "clear-finished helpers should remain independently testable");
957
+ const clearFinishedCalls = [];
958
+ const clearFinishedEvents = [];
959
+ let clearFinishedRefreshes = 0;
960
+ const clearFinishedContext = {
961
+ latestSubagents: {
962
+ tabs: [
963
+ { tabId: "tab-a", runs: [{ id: "done-a", status: "done", source: "async" }, { id: "running-a", status: "running", source: "async" }, { id: "workflow-a", status: "done", source: "workflow" }, { id: "gated-a", status: "done", source: "async" }], gates: [{ attempts: [{ runId: "gated-a" }] }] },
964
+ { tabId: "tab-b", runs: [{ id: "failed-b", status: "failed", source: "foreground" }, { id: "cancelled-b", status: "cancelled", source: "async" }] },
965
+ ],
966
+ },
967
+ ungatedSubagentRuns(tab) {
968
+ const gatedRunIds = new Set((tab.gates || []).flatMap((gate) => (gate.attempts || []).map((attempt) => attempt.runId)));
969
+ return (tab.runs || []).filter((run) => !gatedRunIds.has(run.id));
970
+ },
971
+ subagentsClearingFinished: false,
972
+ subagentsLoading: false,
973
+ refreshSubagentsTimer: null,
974
+ clearTimeout() {},
975
+ renderSubagents() {},
976
+ async api(path, options) { clearFinishedCalls.push({ path, options }); },
977
+ async refreshSubagents() { clearFinishedRefreshes += 1; },
978
+ scheduleRefreshSubagents() {},
979
+ addEvent(message, level) { clearFinishedEvents.push({ message, level }); },
980
+ };
981
+ vm.runInNewContext(`${app.slice(clearFinishedSourceStart, clearFinishedSourceEnd)}\nthis.runClearFinishedSubagentRuns = clearFinishedSubagentRuns;`, clearFinishedContext);
982
+ await clearFinishedContext.runClearFinishedSubagentRuns();
983
+ assert.deepEqual(JSON.parse(JSON.stringify(clearFinishedCalls)), [
984
+ { path: "/api/subagents/dismiss", options: { method: "POST", scoped: false, body: { tab: "tab-a", runId: "done-a" } } },
985
+ { path: "/api/subagents/dismiss", options: { method: "POST", scoped: false, body: { tab: "tab-b", runId: "failed-b" } } },
986
+ { path: "/api/subagents/dismiss", options: { method: "POST", scoped: false, body: { tab: "tab-b", runId: "cancelled-b" } } },
987
+ ], "clear-finished should call the existing dismiss endpoint only for visible terminal ordinary runs");
988
+ assert.equal(clearFinishedRefreshes, 1, "clear-finished should refresh the overview once after all dismissals");
989
+ assert.equal(clearFinishedContext.subagentsClearingFinished, false, "clear-finished should always release its in-flight guard");
990
+ assert.deepEqual(clearFinishedEvents, [{ message: "cleared 3 finished subagent runs", level: "info" }]);
991
+ assert.match(app, /function materializeRetainedSubagentTerminalViews\(\)[\s\S]*restoreKey = `\$\{tab\.tabId\}\\u0000\$\{tab\.sessionFile[\s\S]*ungatedSubagentRuns\(tab\)[\s\S]*run\?\.status === "running"[\s\S]*ensureSubagentTerminalView/, "terminal mode should materialize only ungated restored retained agent views once per parent session identity without touching overlay mode");
863
992
  assert.match(app, /from "\.\/subagent-launch-slot-state\.mjs"[\s\S]*function renderSubagentLaunchSlots\(\)[\s\S]*function loadSubagentLaunchSlotConfig\([\s\S]*\/api\/subagents\/config/, "launch-slot configuration should have its own browser state and API loader");
864
993
  assert.match(app, /function subagentLaunchSlotThinkingForModel\(model\)[\s\S]*modelThinkingLevels/, "launch-slot thinking choices should come from the selected model metadata");
865
994
  assert.match(app, /function renderSubagentLaunchSlotCard\(role, slots\)[\s\S]*Default \/ inherit[\s\S]*"Add slot"[\s\S]*Remove/, "role cards should render independent same-role slots and inheritance controls");
@@ -867,7 +996,36 @@ assert.match(app, /async function saveSubagentLaunchSlotConfig[\s\S]*scope: suba
867
996
  assert.match(app, /const subagentLaunchSlotReloadTabs = new Set\(\)[\s\S]*subagentLaunchSlotReloadTabs\.add\(activeTabId\)[\s\S]*subagentLaunchSlotReloadTabs\.delete\(activeTabId\)/, "reload-required reminders should survive tab switches until that tab is actually reloaded");
868
997
  const subagentOverviewRefreshSource = appFunctionSource("refreshSubagents", "scheduleRefreshSubagents");
869
998
  assert.doesNotMatch(subagentOverviewRefreshSource, /subagentLaunchSlot/, "live subagent polling must not recreate or reset the launch-slot editor");
870
- assert.match(app, /function renderSubagentGateAttempt\(attempt\)[\s\S]*failureKind[\s\S]*function renderSubagentGate\(tab, gate\)[\s\S]*qualifyingSuccesses/, "frontend should render failure-classified attempts and gate quorum");
999
+ assert.match(app, /function renderSubagentGateAttempt\(tab, attempt\)[\s\S]*subagent-gate-attempt-name[\s\S]*subagent-gate-attempt-meta[\s\S]*function renderSubagentGate\(tab, gate\)[\s\S]*"Retry gate"[\s\S]*qualifyingSuccesses/, "frontend should render compact gate identity rows and a minimal quorum summary");
1000
+ const subagentGateTargetSource = appFunctionSource("subagentGateAttemptTarget", "subagentGateAttemptExecutionValues");
1001
+ const subagentGateExecutionSource = appFunctionSource("subagentGateAttemptExecutionValues", "openSubagentGateAttemptOutput");
1002
+ const subagentGateOpenSource = appFunctionSource("openSubagentGateAttemptOutput", "renderSubagentGateAttempt");
1003
+ const subagentGateAttemptSource = appFunctionSource("renderSubagentGateAttempt", "renderSubagentGate");
1004
+ assert.match(subagentGateTargetSource, /candidate\?\.id === attempt\.runId[\s\S]*candidate\?\.name === attempt\.agent[\s\S]*agents\.length === 1[\s\S]*return agent\?\.id \? \{ run, agent \} : null/, "retry-gate attempts should resolve their ordinary tracked child run and agent");
1005
+ assert.match(subagentGateExecutionSource, /SETTINGS_THINKING_OPTIONS\.includes\(suffix\)[\s\S]*model = model\.slice\(0, suffixIndex\)[\s\S]*model = `\$\{provider\}\/\$\{model\}`/, "compact gate rows should normalize provider, model, and thinking effort");
1006
+ assert.match(subagentGateAttemptSource, /const target = subagentGateAttemptTarget\(tab, attempt\)[\s\S]*subagentGateAttemptExecutionValues\(attempt\)[\s\S]*attempt\?\.status[\s\S]*retrySafety[\s\S]*subagent-gate-attempt-open/, "compact gate rows should retain title, state, provider\/model, thinking effort, type, and open affordance");
1007
+ assert.doesNotMatch(subagentGateAttemptSource, /attempt\?\.phase|failureKind|attempt\?\.error|`run \$\{attempt/, "compact gate rows should move verbose diagnostics out of the side panel");
1008
+ assert.match(subagentGateOpenSource, /openSubagentOutput\(tab, \{ \.\.\.target\.run, gateAttempt: attempt \}, target\.agent\)/, "opening a gate child should hand its detailed attempt metadata to the standard child output path");
1009
+ assert.match(app, /function subagentGateAttemptViewFacts\(attempt\)[\s\S]*gate attempt[\s\S]*phase[\s\S]*failure[\s\S]*gate error[\s\S]*function subagentOverlayStateFacts[\s\S]*subagentGateAttemptViewFacts\(subagentOverlaySelection\?\.gateAttempt\)[\s\S]*function renderSubagentTerminalView[\s\S]*subagentGateAttemptViewFacts\(view\.gateAttempt\)/, "attempt number, phase, failure class, and error should appear only inside the opened child view");
1010
+ assert.match(app, /function openSubagentOverlay\(tab, run, agent\)[\s\S]*gateAttempt: run\.gateAttempt \|\| null[\s\S]*function ensureSubagentTerminalView\(tab, run, agent\)[\s\S]*gateAttempt: run\.gateAttempt \|\| null/, "overlay and terminal child views should retain gate diagnostics");
1011
+ assert.match(app, /function renderSubagentGate\(tab, gate\)[\s\S]*renderSubagentGateAttempt\(tab, attempt\)/, "retry-gate rendering should retain the owning parent tab needed to open child output");
1012
+ assert.match(css, /button\.subagent-gate-attempt \{ cursor: pointer; \}[\s\S]*button\.subagent-gate-attempt:hover,[\s\S]*button\.subagent-gate-attempt:focus-visible[\s\S]*\.subagent-gate-attempt-open/, "openable retry-gate attempts should expose button hover, keyboard-focus, and arrow affordances");
1013
+ const subagentGateTargetContext = {};
1014
+ vm.runInNewContext(`${subagentGateTargetSource}\nthis.resolveSubagentGateAttempt = subagentGateAttemptTarget;`, subagentGateTargetContext);
1015
+ const gateTargetTab = {
1016
+ tabId: "parent-tab",
1017
+ runs: [
1018
+ { id: "review-run", agents: [{ id: "review-agent", name: "reviewer" }, { id: "scout-agent", name: "scout" }] },
1019
+ { id: "single-run", agents: [{ id: "single-agent", name: "delegate" }] },
1020
+ ],
1021
+ };
1022
+ assert.equal(subagentGateTargetContext.resolveSubagentGateAttempt(gateTargetTab, { runId: "review-run", agent: "reviewer" })?.agent?.id, "review-agent", "gate attempts should select the matching agent in their tracked run");
1023
+ assert.equal(subagentGateTargetContext.resolveSubagentGateAttempt(gateTargetTab, { runId: "single-run", agent: "reviewer" })?.agent?.id, "single-agent", "single-child gate runs should remain openable if display names differ");
1024
+ assert.equal(subagentGateTargetContext.resolveSubagentGateAttempt(gateTargetTab, { runId: "missing-run", agent: "reviewer" }), null, "a gate attempt should remain non-interactive until its tracked run is available");
1025
+ const subagentGateExecutionContext = { SETTINGS_THINKING_OPTIONS: ["off", "minimal", "low", "medium", "high", "xhigh", "max"] };
1026
+ vm.runInNewContext(`${subagentGateExecutionSource}\nthis.resolveSubagentGateExecution = subagentGateAttemptExecutionValues;`, subagentGateExecutionContext);
1027
+ assert.deepEqual(JSON.parse(JSON.stringify(subagentGateExecutionContext.resolveSubagentGateExecution({ provider: "openrouter", model: "openrouter/moonshotai/kimi-k3:high" }))), ["openrouter/moonshotai/kimi-k3", "high"], "gate rows should split a thinking suffix from a fully qualified model");
1028
+ assert.deepEqual(JSON.parse(JSON.stringify(subagentGateExecutionContext.resolveSubagentGateExecution({ provider: "openrouter", model: "moonshotai/kimi-k3:medium" }))), ["openrouter/moonshotai/kimi-k3", "medium"], "gate rows should add a separately reported provider without duplicating it");
871
1029
  assert.match(helper, /async function enrichAsyncSubagentAgent\(run, agent, statusByDir\)[\s\S]*status\.json[\s\S]*agent\.model = subagentModel\(step\.model\)[\s\S]*agent\.thinking = subagentThinking\(step\.thinking\)/, "WebUI helper should enrich async children from effective lifecycle model and reasoning metadata");
872
1030
  assert.match(helper, /SUBAGENT_GATE_UPDATE_EVENT[\s\S]*function publicSubagentGates\(\)[\s\S]*failureKind[\s\S]*gates = publicSubagentGates\(\)/, "WebUI helper should publish bounded retry-gate lifecycle data");
873
1031
  assert.match(extension, /registerSubagentGate\(pi\)[\s\S]*session_shutdown[\s\S]*subagentGate\.dispose\(\)/, "the WebUI package extension should own the retry-gate tool lifecycle without another extension package");
@@ -875,9 +1033,9 @@ assert.match(server, /function normalizeWebuiSubagentPayload\(value\)[\s\S]*mode
875
1033
  assert.match(server, /WEBUI_SUBAGENT_GATE_LIMIT[\s\S]*rawGate\.attempts[\s\S]*failureKind: normalizeWebuiSubagentText\(rawAttempt\.failureKind, 80\)[\s\S]*totalGates/, "server should bound retry gates and expose their cross-tab total");
876
1034
  assert.match(server, /function normalizeWebuiSubagentOutput\(value, selection\)[\s\S]*model: normalizeWebuiSubagentText\(rawAgent\.model, 240\)[\s\S]*thinking: normalizeWebuiSubagentText\(rawAgent\.thinking, 40\)/, "server should preserve model and reasoning metadata in selected child output");
877
1035
  assert.match(server, /function normalizeWebuiSubagentSource\(value\) \{[\s\S]*value === "foreground" \|\| value === "workflow"[\s\S]*function normalizeWebuiSubagentPayload\(value\)[\s\S]*source: normalizeWebuiSubagentSource\(rawRun\.source\)[\s\S]*function normalizeWebuiSubagentOutput\(value, selection\)[\s\S]*source: normalizeWebuiSubagentSource\(selection\.run\?\.source \|\| value\.source\)/, "server should preserve workflow source in overview and selected-output normalization");
878
- assert.match(app, /function subagentExecutionFacts\(agent = \{\}\)[\s\S]*model \$\{model \|\| "unknown"\}[\s\S]*reasoning \$\{thinking \|\| "unknown"\}/, "subagent metadata should use one honest model/reasoning formatter with unknown fallbacks");
879
- assert.match(app, /function subagentSourceLabel\(source = ""\) \{[\s\S]*source === "foreground" \|\| source === "workflow"[\s\S]*function subagentOverlayStateFacts\(data = subagentOverlayData\)[\s\S]*subagentSourceLabel\(data\?\.source \|\| run\.source\)[\s\S]*function renderSubagentTerminalView\(\)[\s\S]*subagentSourceLabel\(view\.data\?\.source \|\| view\.run\?\.source\)[\s\S]*function renderSubagentTerminalTab\(view\)[\s\S]*subagentSourceLabel\(view\.data\?\.source \|\| view\.run\?\.source\)[\s\S]*function renderSubagentAgent\(tab, run, agent\)[\s\S]*subagentSourceLabel\(run\?\.source\)/, "one source-label helper should keep workflow rows, overlays, and virtual tabs honest");
880
- assert.match(app, /function renderSubagentAgent\(tab, run, agent\)[\s\S]*\.\.\.subagentExecutionFacts\(agent\)/, "Subagents side-panel rows should show model and reasoning effort");
1036
+ assert.match(app, /function subagentExecutionValues\(agent = \{\}\)[\s\S]*model\.slice\(suffixIndex \+ 1\)\.toLowerCase\(\) === thinking\.toLowerCase\(\)[\s\S]*return \[model \|\| "unknown", thinking \|\| "unknown"\][\s\S]*function subagentExecutionFacts\(agent = \{\}\)[\s\S]*model \$\{model\}[\s\S]*reasoning \$\{thinking\}/, "subagent metadata should share honest model\/reasoning values, strip duplicate effort suffixes, and retain unknown fallbacks");
1037
+ assert.match(app, /function subagentSourceLabel\(source = ""\) \{[\s\S]*source === "foreground" \|\| source === "workflow"[\s\S]*function subagentOverlayStateFacts\(data = subagentOverlayData\)[\s\S]*subagentSourceLabel\(data\?\.source \|\| run\.source\)[\s\S]*function renderSubagentTerminalView\(\)[\s\S]*subagentSourceLabel\(view\.data\?\.source \|\| view\.run\?\.source\)[\s\S]*function renderSubagentTerminalTab\(view, \{ groupItem = false \} = \{\}\)[\s\S]*subagentSourceLabel\(view\.data\?\.source \|\| view\.run\?\.source\)/, "one source-label helper should keep overlays and virtual tabs honest after inline metadata is removed");
1038
+ assert.match(compactSubagentAgentSource, /subagentExecutionValues\(agent\)/, "Subagents side-panel rows should reuse the normalized model and reasoning values shown in selected output views");
881
1039
  assert.match(app, /function subagentOverlayStateFacts\(data = subagentOverlayData\)[\s\S]*\.\.\.subagentExecutionFacts\(agent\)/, "subagent overlays should show model and reasoning effort");
882
1040
  assert.match(app, /function renderSubagentTerminalView\(\)[\s\S]*\.\.\.subagentExecutionFacts\(agent\)/, "dedicated subagent terminal views should show model and reasoning effort");
883
1041
  assert.match(app, /SUBAGENT_OPEN_MODE_STORAGE_KEY = "pi-webui-subagent-open-mode"[\s\S]*function normalizeSubagentOpenMode\(value\)[\s\S]*function restoreSubagentOpenModeSetting\(\)/, "subagent opening mode should default safely and persist in this browser");
@@ -887,7 +1045,7 @@ assert.match(app, /function renderWidgets\(\)[\s\S]*renderAppRunnerWidget\(\)[\s
887
1045
  assert.doesNotMatch(app, /subagentOverlayDialog\.showModal|elements\.subagentOverlayDialog/, "subagent output should not open or depend on a modal dialog");
888
1046
  assert.match(app, /api\(`\/api\/subagents\/output\?\$\{query\}`, \{ scoped: false \}\)/, "subagent overlay should fetch selected live output from the owning tab");
889
1047
  assert.match(app, /function subagentRunIndicatorActivity\(agent = \{\}\)[\s\S]*currentToolArgs[\s\S]*activityState[\s\S]*function appendSubagentRunIndicator\(parent,[\s\S]*run-indicator-pulse[\s\S]*Agent is running:[\s\S]*subagent-run-indicator-elapsed[\s\S]*updateSubagentRunIndicatorElapsed\(parent, run\)/, "running child output should show the main-style pulse, current tool or activity, and separately refreshed elapsed runtime");
890
- assert.match(app, /const facts = \[[\s\S]*view\.finished \? "finished" : running \? "running"/, "retained completed child views should not keep contradictory running header metadata");
1048
+ assert.match(app, /const facts = \[[\s\S]*view\.finished \? "finished" : running \? `running\$\{elapsed/, "retained completed child views should not keep contradictory running header metadata and live views should include elapsed time");
891
1049
  assert.match(app, /function renderSubagentTerminalView\(\)[\s\S]*if \(running\) appendSubagentRunIndicator\(elements\.subagentTerminalTranscript, \{ agent, run: view\.run \}\)/, "the dedicated child tab should append a live run indicator whenever the selected child is running");
892
1050
  const subagentTerminalSignatureSource = appFunctionSource("subagentTerminalViewMeaningfulSignature", "updateSubagentTerminalRefreshState");
893
1051
  const subagentTerminalRefreshSource = appFunctionSource("refreshSubagentTerminalView", "deactivateSubagentTerminalView");
@@ -924,15 +1082,18 @@ assert.equal(unchangedSubagentTabRenderCount, 0, "an unchanged background poll s
924
1082
  assert.equal(unchangedSubagentElapsedUpdateCount, 1, "an unchanged background poll should refresh only the existing visual elapsed-time node");
925
1083
  assert.equal(unchangedSubagentView.loading, false, "an unchanged background poll should still clear its internal loading flag");
926
1084
  const subagentTerminalCloseStart = app.indexOf("function closeSubagentTerminalTab(");
927
- const subagentTerminalCloseEnd = app.indexOf("\nasync function copySubagentTerminalOutput(", subagentTerminalCloseStart);
1085
+ const subagentTerminalCloseEnd = app.indexOf("\nfunction closeSubagentTerminalGroup(", subagentTerminalCloseStart);
928
1086
  assert.ok(subagentTerminalCloseStart >= 0 && subagentTerminalCloseEnd > subagentTerminalCloseStart, "closeSubagentTerminalTab should remain a standalone frontend helper");
929
1087
  const subagentTerminalCloseSource = app.slice(subagentTerminalCloseStart, subagentTerminalCloseEnd);
930
1088
  assert.ok(subagentTerminalCloseSource.includes("subagentTerminalViews.delete(viewId)"), "closing a subagent tab should remove only its client-side view record");
931
1089
  assert.doesNotMatch(subagentTerminalCloseSource, /\bapi\(|closeTerminalTabs\(|closeSubagentOverlay\(/, "closing a subagent tab must not call backend terminal or subagent lifecycle APIs");
932
- assert.match(app, /function renderSubagentTerminalTab\(view\)[\s\S]*terminal-tab-subagent[\s\S]*subagent: true[\s\S]*closeSubagentTerminalTab\(view\.id\)/, "virtual tabs should be marked as subagents and have a view-only close action");
1090
+ assert.match(app, /function renderSubagentTerminalTab\(view, \{ groupItem = false \} = \{\}\)[\s\S]*terminal-tab-subagent[\s\S]*subagent: true[\s\S]*closeSubagentTerminalTab\(view\.id\)/, "standalone and grouped virtual tabs should be marked as subagents and retain a view-only close action");
933
1091
  assert.match(app, /function subagentTerminalViewId\(tab, run, agent\)[\s\S]*JSON\.stringify\(\[tab\?\.tabId[\s\S]*run\?\.id[\s\S]*agent\?\.id/, "virtual child tabs should be uniquely keyed by parent terminal, run, and child agent");
934
1092
  assert.match(app, /SUBAGENT_OVERLAY_REFRESH_MS = 1000/, "subagent overlay should poll selected live output at a fast cadence");
935
- assert.match(app, /function createMessageBubble\(message,[\s\S]*renderContent\(body, message\.content, \{ markdown: message\.role === "assistant" \|\| message\.role === "custom" \}\)[\s\S]*function appendMessage\(message, options = \{\}\)[\s\S]*createMessageBubble\(message, options\)/, "main transcript output should use the reusable message bubble renderer");
1093
+ const createMessageBubbleSource = appFunctionSource("createMessageBubble", "appendMessage");
1094
+ const appendMessageSource = appFunctionSource("appendMessage", "appendOptimisticUserPrompt");
1095
+ assert.match(createMessageBubbleSource, /renderContent\(body, message\.content, \{ markdown: message\.role === "assistant" \|\| message\.role === "custom" \}\)/, "the reusable message bubble renderer must retain Markdown-capable main output");
1096
+ assert.match(appendMessageSource, /reuseToolExecutionBubble[\s\S]*createMessageBubble\(message, \{ \.\.\.options, segmentId \}\)[\s\S]*appendChatMessageBubble/, "main transcript output should reuse stable tool cards before creating and appending a fresh message bubble");
936
1097
  const subagentTranscriptMessagesSource = appFunctionSource("subagentOverlayTranscriptMessages", "subagentOverlayToolArguments");
937
1098
  assert.ok(subagentTranscriptMessagesSource.includes("message.role === \"assistant\" || message.role === \"toolResult\""), "subagent overlays should retain structured assistant and tool-result entries");
938
1099
  const subagentToolArgumentsSource = appFunctionSource("subagentOverlayToolArguments", "subagentOverlayTranscriptDisplayMessages");
@@ -972,7 +1133,28 @@ assert.ok(subagentWidgetSource.includes("if (visibleFallbackText) {"), "the widg
972
1133
  assert.ok(subagentWidgetSource.includes("if (running) appendSubagentRunIndicator(output, { agent, run: selection.run });"), "running subagent widgets should append the shared live activity indicator");
973
1134
  assert.match(app, /api\("\/api\/subagents", \{ scoped: false \}\)/, "frontend should refresh the cross-tab subagent overview");
974
1135
  assert.match(app, /SUBAGENTS_ACTIVE_REFRESH_MS = 1500/, "running subagents should receive a fast live refresh cadence");
975
- assert.match(server, /url\.pathname === "\/api\/subagents" && req\.method === "GET"[\s\S]*webuiSubagentsData\(\)/, "server should expose a cross-tab running-subagent endpoint");
1136
+ assert.match(server, /url\.pathname === "\/api\/subagents" && req\.method === "GET"[\s\S]*await webuiSubagentsData\(\)/, "server should await enriched cross-tab running-subagent titles");
1137
+ assert.match(server, /async function resolveSubagentDisplayTitle\(tab\)[\s\S]*tab\.titleSource !== "auto"[\s\S]*get_messages[\s\S]*message\?\.role === "user"[\s\S]*generatedTabTitleFromPrompt\(extractSessionTextContent\(firstUserMessage\?\.content\)\)/, "existing auto-named subagent groups should recover their longer title from the first user message without relaunching children");
1138
+ assert.match(server, /const tabSummaries = await Promise\.all\([\s\S]*runs\.length \|\| gates\.length \? await resolveSubagentDisplayTitle\(tab\) : tab\.title/, "subagent title recovery should run once for visible run and retry-gate groups");
1139
+ const resolveSubagentDisplayTitleStart = server.indexOf("async function resolveSubagentDisplayTitle(");
1140
+ const resolveSubagentDisplayTitleEnd = server.indexOf("\nasync function webuiSubagentsData(", resolveSubagentDisplayTitleStart);
1141
+ assert.ok(resolveSubagentDisplayTitleStart >= 0 && resolveSubagentDisplayTitleEnd > resolveSubagentDisplayTitleStart, "subagent display-title recovery should remain independently testable");
1142
+ const recoveredSubagentTitle = "Workspace files webui files section sidepanel dynamically adjusted";
1143
+ let subagentTitleMessageReads = 0;
1144
+ const resolveSubagentDisplayTitleContext = vm.createContext({
1145
+ TAB_ACTIVITY_STATE_RECONCILE_TIMEOUT_MS: 1200,
1146
+ safeRpcResponse: async () => {
1147
+ subagentTitleMessageReads += 1;
1148
+ return { data: { messages: [{ role: "user", content: recoveredSubagentTitle }] } };
1149
+ },
1150
+ extractSessionTextContent: (content) => String(content || ""),
1151
+ generatedTabTitleFromPrompt: (message) => message,
1152
+ });
1153
+ vm.runInContext(`${server.slice(resolveSubagentDisplayTitleStart, resolveSubagentDisplayTitleEnd)}\nthis.runResolveSubagentDisplayTitle = resolveSubagentDisplayTitle;`, resolveSubagentDisplayTitleContext);
1154
+ const legacyAutoNamedTab = { title: "Workspace files webui files section sidepan…", titleSource: "auto" };
1155
+ assert.equal(await resolveSubagentDisplayTitleContext.runResolveSubagentDisplayTitle(legacyAutoNamedTab), recoveredSubagentTitle, "existing auto-named rows should recover the wider title from their parent conversation");
1156
+ assert.equal(await resolveSubagentDisplayTitleContext.runResolveSubagentDisplayTitle(legacyAutoNamedTab), recoveredSubagentTitle, "recovered titles should remain available to later panel refreshes");
1157
+ assert.equal(subagentTitleMessageReads, 1, "title recovery should read the existing parent conversation once and must not require spawning another subagent");
976
1158
  assert.match(server, /url\.pathname === "\/api\/subagents\/output" && req\.method === "GET"[\s\S]*webuiSubagentOutputData\(tab, runId, agentId\)/, "server should expose selected running subagent output only through its owning tab");
977
1159
  assert.match(server, /rememberWebuiSubagentsStatusEvent\(tab, event\)/, "server should ingest the helper's structured subagent status without forwarding internal JSON to the browser footer");
978
1160
  assert.match(server, /PI_RPC_JSONL_LINE_MAX_BYTES = 32 \* 1024 \* 1024/, "Pi RPC JSONL parsing should use an explicit line-size limit with inline-image headroom");
@@ -1288,6 +1470,8 @@ assert.match(app, /const GIT_WORKFLOW_CREATE_PR_TOOLTIP = \[[\s\S]*"Create PR wo
1288
1470
  assert.match(app, /const GIT_WORKFLOW_MANUAL_BRANCH_TOOLTIP = \[[\s\S]*"Manual PR worktree:"[\s\S]*"1\. Skip agent branch-name generation\."[\s\S]*"4\. Create or open a Git worktree for that branch instead of switching this checkout\."[\s\S]*"7\. Push and Create PR will push upstream, run \/pr, let you review, then run gh pr create\."/, "Manual worktree should have an up-to-date step-by-step tooltip");
1289
1471
  assert.match(app, /addGitWorkflowAction\("Manual worktree", \(\) => createGitPrBranchManually\(\), "", false, GIT_WORKFLOW_MANUAL_BRANCH_TOOLTIP\)/, "Manual worktree should render with its tooltip");
1290
1472
  assert.match(app, /function renderGitWorkflowManualCommitInput\(\{ appendCommitButton = true \} = \{\}\)[\s\S]*git-workflow-message-input[\s\S]*Commit input[\s\S]*commitGitWorkflow\("input", tabId\)/, "Message stage should render a manual commit message input with a Commit input action");
1473
+ assert.match(app, /function captureGitWorkflowInputFocus\(\)[\s\S]*document\.activeElement[\s\S]*gitWorkflowManualCommitMessage[\s\S]*selectionStart[\s\S]*function restoreGitWorkflowInputFocus\(state\)[\s\S]*state\.tabId !== activeTabId[\s\S]*state\.runId !== gitWorkflow\?\.runId[\s\S]*focus\(\{ preventScroll: true \}\)[\s\S]*setSelectionRange/, "guided git rerenders should restore focus and the cursor only for the same commit-message workflow");
1474
+ assert.match(app, /function renderGitWorkflow\(\) \{\n\s+const inputFocus = captureGitWorkflowInputFocus\(\);[\s\S]*gitWorkflowActions\.replaceChildren\(\);[\s\S]*restoreGitWorkflowInputFocus\(inputFocus\);\n\}/, "background guided git updates should not leave the manual commit-message input unfocused after replacing workflow actions");
1291
1475
  assert.match(app, /gitWorkflow\.step === "generate"\) \{\n\s+const commitInputButton = renderGitWorkflowManualCommitInput\(\{ appendCommitButton: false \}\);[\s\S]*addGitWorkflowAction\("Preview current message files"[\s\S]*gitWorkflowActions\.append\(commitInputButton\)/, "Message process stage should place Commit input immediately after Preview current message files");
1292
1476
  assert.match(app, /gitWorkflow\.step === "message"\) \{[\s\S]*const commitInputButton = renderGitWorkflowManualCommitInput\(\{ appendCommitButton: false \}\);[\s\S]*addGitWorkflowAction\("Regenerate"[\s\S]*gitWorkflowActions\.append\(commitInputButton\)/, "Commit choice stage should place Commit input immediately after Regenerate");
1293
1477
  assert.match(app, /async function commitGitWorkflow\(variant[\s\S]*variant === "input"[\s\S]*message: inputMessage/, "Commit input should send the typed message to the git workflow commit API");
@@ -1378,7 +1562,8 @@ assert.match(app, /const WEBUI_TOOL_RENDERERS = \{[\s\S]*?function renderSingleT
1378
1562
  assert.match(app, /appendToolRawDetails\(parent, tool\)/, "paired tool cards should keep a safe raw-data expander for debugging renderer mismatches");
1379
1563
  assert.match(app, /function toolStateMeta\(tool\)/, "tool cards should expose consistent status and elapsed metadata across built-in renderers");
1380
1564
  assert.match(app, /const TOOL_LIVE_UPDATE_THROTTLE_MS = 80/, "live tool cards should coalesce rapid partial updates before re-rendering");
1381
- assert.match(app, /function updateLiveToolCard\(bubble, message\)[\s\S]*?body\.replaceChildren\(\);[\s\S]*?renderToolExecution\(body, message\);/, "live tool card updates should re-render the existing card body in place");
1565
+ const updateLiveToolCardSource = appFunctionSource("updateLiveToolCard", "cancelQueuedLiveToolRunRender");
1566
+ assert.match(updateLiveToolCardSource, /transcriptRenderer\.ownSurface\(body[\s\S]*?transcriptRenderer\.commitTranscriptMutation\(\{[\s\S]*?kind: "reconcile"[\s\S]*?transcriptRenderer\.replaceChildren\(body\)[\s\S]*?renderToolExecution\(body, message\)/, "live tool card updates should re-render the existing semantic body through the transcript coordinator");
1382
1567
  assert.match(app, /function applyToolExecutionBubbleState\(bubble, message\)[\s\S]*?bubble\.dataset\.toolStatus !== status[\s\S]*?bubble\.classList\.add\(nextClass\)[\s\S]*?bubble\.classList\.toggle\("error"/, "tool status classes should not be removed and re-added on every live update");
1383
1568
  assert.match(app, /function toolExecutionRenderSignature\(message\)[\s\S]*?normalizeToolExecution\(message\)[\s\S]*?toolRenderSignatureReplacer\(\)/, "tool cards should derive stable render signatures from normalized tool payloads");
1384
1569
  assert.match(app, /const nextRenderSignature = toolExecutionRenderSignature\(message\)[\s\S]*?bubble\._toolRenderSignature === nextRenderSignature[\s\S]*?return true;[\s\S]*?bubble\._toolRenderSignature = nextRenderSignature/, "live tool card updates should skip identical body re-renders");
@@ -1433,7 +1618,7 @@ assert.match(app, /function scheduleStreamBubbleHide\([\s\S]*?STREAM_OUTPUT_MIN_
1433
1618
  assert.match(app, /if \(finalText\) \{[\s\S]*?renderStreamingMarkdown\(streamText, finalText\);[\s\S]*?\} else \{\n\s+scheduleStreamBubbleHide\(\);/, "empty filtered stream output should schedule hide while visible stream output renders as Markdown");
1434
1619
  assert.match(app, /scheduleStreamingAssistantTextRender\(\{ immediate: !!\(streamToolCallSeen \|\| streamBubble\) \}\);/, "live assistant text should wait briefly before showing unless it is already visible or follows a tool call");
1435
1620
  assert.match(app, /streamToolCallSeen = true;\n\s+suppressStreamingAssistantTextBeforeToolCall\(\);/, "tool-call starts should remove pending assistant text from the live transcript");
1436
- assert.match(app, /function renderStreamingToolCallCard\(\{ scroll = false \} = \{\}\)[\s\S]*?appendMessage\(message, \{ streaming: true \}\)[\s\S]*?streamToolCallText\.textContent !== displayText/, "live tool-call cards should render and update the arguments stream in place");
1621
+ assert.match(app, /function renderStreamingToolCallCard\(\{ scroll = false \} = \{\}\)[\s\S]*?appendMessage\(message, \{ streaming: true, itemKey:[\s\S]*?transcriptRenderer\.ownSurface\(streamToolCallText[\s\S]*?transcriptRenderer\.updateTextSurface\(\{[\s\S]*?text: displayText/, "live tool-call cards should render and update their stable semantic arguments surface in place");
1437
1622
  assert.match(app, /update\.type === "toolcall_delta"[\s\S]*?updateStreamingToolCallFromEvent\(event, \{ appendDelta: true \}\)[\s\S]*?Building tool call:/, "tool-call deltas should update visible streamed arguments instead of a static placeholder");
1438
1623
  assert.match(app, /case "tool_execution_start":[\s\S]*?removeStreamingToolCallCard\(\)[\s\S]*?handleToolExecutionStart\(event\)/, "the streamed tool-call argument card should be removed when the real tool execution card starts");
1439
1624
  assert.doesNotMatch(app, /Preparing tool call:/, "tool-call streaming should no longer show only the static preparing placeholder");
@@ -1453,12 +1638,15 @@ assert.match(app, /return "Agent is running: ";/, "active agent indicator should
1453
1638
  assert.doesNotMatch(app, /"agent running"/, "active agent indicator should not render a separate title/header label");
1454
1639
  assert.doesNotMatch(app, /runIndicatorTimestamp/, "active agent indicator should not render a separate live timestamp header");
1455
1640
  assert.match(app, /runIndicatorBubble = make\("article", "message runIndicator run-indicator-message streaming"\)/, "active agent indicator should use a dedicated streaming transcript card");
1456
- assert.match(app, /function resetChatOutput\(\)[\s\S]*?preservedNodes[\s\S]*?runIndicatorBubble\?\.parentElement === elements\.chat[\s\S]*?elements\.chat\.replaceChildren\(\.\.\.preservedNodes\)/, "transcript re-renders should preserve the live run indicator node instead of tearing it down");
1457
- assert.match(app, /function appendChatMessageBubble\(bubble\)[\s\S]*?insertBefore\(bubble, runIndicatorBubble\)/, "new transcript cards should insert before the active run indicator so it stays stable at the bottom");
1641
+ assert.match(app, /function standaloneLiveTranscriptBubbles\(\)[\s\S]*?streamThinkingBubble[\s\S]*?streamToolCallBubble[\s\S]*?streamBubble[\s\S]*?compactThinkingBubble[\s\S]*?compactTextBubble/, "transcript reconciliation should identify standalone live-tail bubbles that must stay mounted");
1642
+ assert.match(app, /function resetChatOutput\(\)[\s\S]*?liveBubbles = standaloneLiveTranscriptBubbles\(\)[\s\S]*?preservedNodes[\s\S]*?child === runIndicatorBubble \|\| liveBubbles\.has\(child\)[\s\S]*?transcriptRenderer\.replaceChildren\(elements\.chat, \.\.\.preservedNodes\)/, "transcript resets should reconcile through the coordinator while preserving live output and the run indicator");
1643
+ assert.match(app, /function appendChatMessageBubble\(bubble\)[\s\S]*?tailAnchor[\s\S]*?child === runIndicatorBubble \|\| liveBubbles\.has\(child\)[\s\S]*?insertBefore\(bubble, tailAnchor\)/, "reconciled history should insert before the stable live transcript tail");
1644
+ assert.match(app, /setChatScrollTopInstant\(Math\.min\(previousScrollTop, elements\.chat\.scrollHeight\)\)/, "paused-reader scroll restoration should bypass smooth scrolling to avoid a down-then-back animation");
1458
1645
  assert.match(app, /function ensureRunIndicatorBubble\(\)[\s\S]*?!runIndicatorBubble \|\| !runIndicatorText \|\| !runIndicatorMeta[\s\S]*?elements\.chat\.lastElementChild !== runIndicatorBubble/, "active agent indicator should reuse the existing bubble across transcript re-renders instead of recreating it");
1459
1646
  assert.match(app, /const headline = runIndicatorHeadline\(\);\n\s+if \(runIndicatorText\.textContent !== headline\) runIndicatorText\.textContent = headline;/, "active agent indicator should avoid redundant headline DOM writes that can flicker");
1460
1647
  assert.match(app, /const meta = runIndicatorShowsElapsed\(\) \? `\$\{detail\} · run time[\s\S]*?if \(runIndicatorMeta\.textContent !== meta\) runIndicatorMeta\.textContent = meta;/, "active agent indicator should avoid redundant metadata DOM writes except elapsed changes");
1461
1648
  assert.match(app, /runIndicatorShowsElapsed\(\) \? `\$\{detail\} · run time/, "active agent indicator should label elapsed run time instead of showing a bare counter");
1649
+ assert.match(app, /case "agent_settled":[\s\S]*?clearRunIndicatorActivity\(\{ deferRemoval: !autoFollowChat \|\| !isChatNearBottom\(\) \}\);[\s\S]*?scheduleRefreshMessages\(\)/, "settlement should keep the tail height stable for readers above the live edge until canonical messages reconcile");
1462
1650
  assert.match(app, /Abort requested/, "abort feedback should clarify that Web UI is checking stop status");
1463
1651
  assert.match(app, /const ABORT_LONG_PRESS_MS = 3000/, "Abort long-press timing should be explicit");
1464
1652
  assert.match(app, /const ABORT_LONG_PRESS_TICK_MS = 100/, "Abort hold countdown should update visibly while held");
@@ -1497,7 +1685,7 @@ assert.match(app, /setRunIndicatorActivity\("Requesting context compaction…"\)
1497
1685
  assert.match(app, /function markContextUsageUnknownAfterCompaction\(/, "compaction should have a dedicated context-usage invalidation helper");
1498
1686
  assert.match(app, /case "compaction_end":[\s\S]*?markContextUsageUnknownAfterCompaction\(event\.tabId \|\| activeTabId\)/, "finished compaction should make footer context usage unknown instead of showing stale pressure");
1499
1687
  assert.match(app, /function footerStatsContextDisplay[\s\S]*?contextUsageUnknownAfterCompaction\(\)[\s\S]*?unknownFooterContextText/, "fallback footer context should show an unknown value after compaction invalidates usage");
1500
- assert.match(app, /case "agent_settled":[\s\S]*?clearRunIndicatorActivity\(\)/, "agent settlement should remove the active agent transcript indicator");
1688
+ assert.match(app, /case "agent_settled":[\s\S]*?clearRunIndicatorActivity\(\{ deferRemoval:[^}]+\}\)/, "agent settlement should clear indicator activity while deferring tail removal for readers above the live edge");
1501
1689
  assert.match(app, /case "agent_settled":[\s\S]*?notifyAgentDone\(event\.tabId \|\| activeTabId/, "agent settlement should trigger optional done notifications");
1502
1690
  assert.doesNotMatch(app.match(/case "agent_end":[\s\S]*?case "message_start":/)?.[0] || "", /notifyAgentDone\(/, "an intermediate low-level agent end must not trigger a done notification");
1503
1691
  assert.match(app, /function getPathTrigger\(\)/, "prompt composer should detect @ file\/path reference triggers");
@@ -1562,9 +1750,15 @@ assert.match(app, /async function sendBtwPromptFromButton\(\)[\s\S]*?if \(!quest
1562
1750
  assert.match(app, /function renderBtwComposerForm\(\)[\s\S]*?form\.requestSubmit\(\)[\s\S]*?sendBtwQuestion\(question\)/, "/btw widget input should submit each message as a /btw trigger");
1563
1751
  assert.match(app, /function makeBtwTransferIcon\(\)[\s\S]*?class", "btw-transfer-icon"[\s\S]*?function transferBtwContextToMain\(button, \{ transferMode = "full" \} = \{\}\)[\s\S]*?`\/btw-transfer \$\{encoded\}`[\s\S]*?streamingBehavior: "steer"[\s\S]*?Summarize & Steer/, "/btw widget should expose full-context and summary transfer actions that send steering context during active runs");
1564
1752
  assert.match(app, /async function sendPrompt\(kind = "prompt", explicitMessage, \{ targetTabId = activeTabId, throwOnError = false, streamingBehavior \} = \{\}\)[\s\S]*?if \(targetWasBusy\) body\.streamingBehavior = streamingBehavior \|\| busyBehavior/, "prompt sending should support a per-call streaming behavior override");
1565
- assert.match(app, /function appendOptimisticUserPrompt\([\s\S]*?role: "user"[\s\S]*?transient: true/, "new prompts should be appended to the transcript optimistically before routing finishes");
1566
- assert.match(app, /if \(startsRun\) \{\n\s+promptRoutingTabs\.add\(targetTabId\);\n\s+markTabWorkingLocally\(targetTabId\);\n\s+if \(isCurrentTabContext\(tabContext\)\) \{\n\s+appendOptimisticUserPrompt\(originalMessage, attachments\.length\);\n\s+setRunIndicatorActivity\(attachments\.length \? "Preparing attachments for routing…" : "Routing prompt to the selected agent…"\);/, "new runs should show the prompt and routing progress immediately in the target tab");
1753
+ assert.match(app, /function appendOptimisticUserPrompt\([\s\S]*?transientMessages\.push\(\{[\s\S]*?role: "user"[\s\S]*?optimisticPromptId[\s\S]*?renderAllMessages\(\)/, "new prompts should enter transcript state optimistically before routing finishes");
1754
+ assert.match(app, /function reconcileOptimisticUserPrompts\([\s\S]*?persistedUserMessageCount\(messages\)[\s\S]*?message\?\.optimisticPromptId[\s\S]*?persistedUserCount <= Number\(message\.optimisticBaselineUserCount \|\| 0\)/, "optimistic prompts should remain renderable until a newer persisted user message supersedes them");
1755
+ assert.match(app, /function renderMessages\(messages\) \{\n\s+latestMessages = messages \|\| \[\];\n\s+reconcileOptimisticUserPrompts\(latestMessages\);/, "message refreshes should reconcile rather than blindly discard optimistic prompts");
1756
+ assert.match(app, /if \(startsRun\) \{\n\s+promptRoutingTabs\.add\(targetTabId\);\n\s+markTabWorkingLocally\(targetTabId\);\n\s+if \(isCurrentTabContext\(tabContext\)\) \{\n\s+optimisticPromptId = appendOptimisticUserPrompt\(originalMessage, attachments\.length\);\n\s+setRunIndicatorActivity\(attachments\.length \? "Preparing attachments for routing…" : "Routing prompt to the selected agent…"\);/, "new runs should show the prompt and routing progress immediately in the target tab");
1567
1757
  assert.match(app, /if \(startsRun && isCurrentTabContext\(tabContext\)\) setRunIndicatorActivity\("Routing complete; starting agent…"\);/, "prepared prompts should transition from routing to agent-start progress before dispatch");
1758
+ assert.doesNotMatch(app, /applyResponseTab\(response\);\n\s+if \(startsRun\) promptRoutingTabs\.delete\(targetTabId\);/, "prompt acceptance alone should not clear pending launch continuity before Pi confirms the run");
1759
+ assert.match(app, /case "agent_start":\n\s+promptRoutingTabs\.delete\(event\.tabId \|\| activeTabId\);/, "agent start should replace optimistic routing continuity with canonical streaming state");
1760
+ assert.match(app, /else if \(promptRoutingTabs\.has\(activeTabId\)\) \{\n\s+renderRunIndicator/, "idle state snapshots should not hide the run indicator while an accepted prompt still awaits agent start");
1761
+ assert.match(app, /if \(state\.isStreaming && runIndicatorActivityIsRouting\(\)\) \{\n\s+runIndicatorActivity = "Agent run confirmed; waiting for first output or action…";/, "confirmed streaming state should replace stale routing copy without overwriting newer thinking or tool activity");
1568
1762
  assert.match(app, /function runPublishWorkflow\(command\)[\s\S]*?sendPrompt\("prompt", `\/\$\{resolvedCommandName\}\$\{commandRest\}`\)/, "Publish workflows should send resolved slash commands directly without replacing the draft");
1569
1763
  assert.match(app, /async function runNativeCommandMenu\(command\)[\s\S]*?await handleNativeSlashSelectorCommand\(command\)/, "skills/tools command menu should open native selector dialogs directly");
1570
1764
  assert.match(app, /async function runNativeCommandMenu\(command\)[\s\S]*?sendPrompt\("prompt", command\)/, "generic native command menu should fall back to slash-command prompt execution");
@@ -1681,7 +1875,7 @@ assert.match(app, /function closeAllTerminalTabs\(\)[\s\S]*?closeTerminalTabs\(t
1681
1875
  assert.match(app, /WARNING: \$\{activeAgentTabs\.length\}[\s\S]*?still running or waiting for input/, "tab close confirmations should warn when agents are still running");
1682
1876
  assert.match(app, /elements\.closeAllTabsButton\.addEventListener\("click", \(\) => closeAllTerminalTabs\(\)\)/, "close-all tabs button should be wired in JS");
1683
1877
  assert.match(app, /const groups = tabCwdGroups\(\);[\s\S]*?for \(const group of groups\) \{\n\s+if \(shouldRenderTerminalTabGroup\(group, groups\.length\)\)[\s\S]*?renderTerminalTabGroup\(group, groups\.length\)[\s\S]*?for \(const tab of group\.tabs\) elements\.tabBar\.append\(renderTerminalTab\(tab\)\);/, "terminal tabs should render groups with group count and ungrouped tabs when grouping is skipped");
1684
- assert.match(app, /for \(const view of \[\.\.\.subagentTerminalViews\.values\(\)\][\s\S]*renderSubagentTerminalTab\(view\)/, "open subagent views should render as first-class virtual terminal tabs");
1878
+ assert.match(app, /const subagentGroups = subagentTerminalViewGroups\(\)[\s\S]*renderSubagentTerminalTabGroup\(group\)[\s\S]*renderSubagentTerminalTab\(group\.views\[0\]\)/, "open subagent views should render as first-class virtual tabs, grouped by parent workspace when siblings exist");
1685
1879
  assert.match(readme, /Tracked subagent output[\s\S]*dedicated \*\*Subagent\*\* terminal tab[\s\S]*view-only[\s\S]*close without stopping or interrupting/, "README should document the selectable view-only child terminal behavior");
1686
1880
  assert.match(app, /let tabSeenCompletionSerials = new Map\(\)/, "frontend should track which tab completions have been seen");
1687
1881
  assert.match(app, /let activeTabGeneration = 0/, "frontend should version active-tab UI state to reject stale async work");
@@ -1712,6 +1906,7 @@ assert.match(app, /function markTabDoneLocally\(/, "frontend should locally reco
1712
1906
  assert.match(app, /function syncActiveTabActivityFromState\(state = currentState\)/, "frontend should reconcile active-tab indicators from authoritative state snapshots");
1713
1907
  assert.match(app, /event\.command === "get_state" && event\.tabId === activeTabId[\s\S]*?syncActiveTabActivityFromState\(currentState\)/, "get_state response events should update stale active-tab activity");
1714
1908
  assert.match(app, /function applyResponseTab\(response\)/, "frontend should merge tab metadata returned by prompt responses");
1909
+ assert.match(app, /newSessionButton\.addEventListener\("click", async \(\) => \{[\s\S]*?api\("\/api\/new-session"[\s\S]*?applyResponseTab\(response\)[\s\S]*?refreshAll\(tabContext\)/, "the New button should apply returned terminal-tab metadata before the full session refresh");
1715
1910
  assert.match(app, /case "webui_tab_renamed":/, "frontend should update tab labels from backend rename events");
1716
1911
  assert.match(app, /case "webui_recovery_opened":[\s\S]*?refreshTabs\(\)[\s\S]*?switchTab\(event\.recoveryTabId\)/, "recovery events should refresh tabs and activate the new recovery session");
1717
1912
  assert.match(app, /terminalTabsToggleButton\.addEventListener\("click"/, "terminal tabs trigger should be wired in JS");
@@ -1731,7 +1926,8 @@ assert.match(app, /api\("\/api\/thinking", \{ method: "POST", body: \{ level: ne
1731
1926
  assert.match(app, /function isFooterPickerOpen\(\)[\s\S]*?footerModelPickerOpen \|\| footerThinkingPickerOpen/, "footer picker overlay state should cover model and thinking pickers");
1732
1927
  assert.doesNotMatch(app.match(/function renderMinimalFooter\(\)[\s\S]*?\n\}/)?.[0] || "", /footer-details-toggle/, "minimal default footer should not render a details toggle chip");
1733
1928
  assert.match(app, /bindMobileViewChanges\(/, "side panel state should react to mobile breakpoint changes");
1734
- assert.match(app, /function restoreSidePanelState\(\) \{\n\s+if \(isSidePanelOverlayView\(\)\)/, "mobile and narrow overlay layouts should start with side panel collapsed even if desktop state was expanded");
1929
+ // Intent preserved for legacy; v2 leaves mobile surface ownership to its reducer.
1930
+ assert.match(app, /function restoreSidePanelState\(\) \{\n\s+if \(isMobileShellV2Active\(\)\) return;\n\s+if \(isSidePanelOverlayView\(\)\)/, "legacy mobile and narrow overlay layouts should start with the side panel collapsed");
1735
1931
  assert.match(app, /case "webui_tab_reloaded":/, "frontend should handle native /reload tab restart events");
1736
1932
  assert.match(app, /addTransientMessage\(\{ role: "native", title: "\/reload"/, "native /reload should produce visible transcript output");
1737
1933
  assert.match(app, /copyText\(data\.copyText\)\.catch/, "native /copy should use the shared browser clipboard helper when available");
@@ -1746,10 +1942,14 @@ assert.ok(manifest.icons?.some((icon) => icon.src === "/apple-touch-icon.png" &&
1746
1942
  assert.ok(manifest.icons?.some((icon) => icon.src === "/icon-192.png" && icon.sizes === "192x192"), "PWA manifest should include a 192px icon");
1747
1943
  assert.ok(manifest.icons?.some((icon) => icon.src === "/icon-512.png" && icon.sizes === "512x512"), "PWA manifest should include a 512px icon");
1748
1944
  assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v\d+"/, "PWA service worker should define a versioned app-shell cache");
1749
- assert.match(serviceWorker, /fetchThenCache\(request\)\.catch\(/, "PWA service worker should serve the app shell network-first with offline cache fallback");
1945
+ assert.match(serviceWorker, /fetchThenCache\(event\)\.catch\(/, "PWA service worker should serve the app shell network-first with offline cache fallback");
1946
+ assert.match(serviceWorker, /const APP_SHELL_NETWORK_TIMEOUT_MS = 8_000;/, "PWA app-shell requests should have a bounded network timeout");
1947
+ assert.match(serviceWorker, /event\.waitUntil\([\s\S]*?cache\.put\(request, response\.clone\(\)\)/, "PWA cache writes should be tracked without blocking response delivery");
1750
1948
  assert.match(serviceWorker, /ignoreSearch: true/, "PWA service worker offline fallback should ignore ?v= cache busters");
1751
1949
  assert.match(serviceWorker, /self\.addEventListener\("notificationclick"/, "PWA service worker should focus Web UI when blocked-tab notifications are clicked");
1752
- assert.match(serviceWorker, /event\.notification\.data\?\.url/, "blocked-tab notifications should carry a URL for service-worker click handling");
1950
+ // Intent superseded: notification URLs are now generated only from validated opaque targets; invalid payloads fall back to the app root.
1951
+ assert.match(serviceWorker, /function notificationTargetUrl\(data\)[\s\S]*?if \(!target\) return `\$\{self\.location\.origin\}\/`/, "notification clicks should use a bounded root fallback instead of accepting an arbitrary URL");
1952
+ assert.doesNotMatch(serviceWorker, /data\?\.url/, "notification payloads must not inject arbitrary fallback URLs");
1753
1953
  assert.match(serviceWorker, /"\/subagent-launch-slot-state\.mjs"/, "PWA service worker should cache the launch-slot state module imported by the app shell");
1754
1954
  assert.match(serviceWorker, /"\/apple-touch-icon\.png"/, "PWA service worker should cache the apple touch icon");
1755
1955
  assert.match(serviceWorker, /"\/matrix-background\.webp"/, "PWA service worker should cache the Matrix background image");
@@ -1775,7 +1975,9 @@ assert.match(server, /OPENAI_CODEX_USAGE_ENDPOINT/, "server should query Codex u
1775
1975
  assert.match(server, /const NATIVE_SLASH_COMMANDS = nativeSlashCommandEntries\(nativeParityMatrix\)/, "server should define Pi native slash commands for autocomplete from the parity matrix");
1776
1976
  assert.match(server, /WEBUI_TUI_NATIVE_PARITY\.json/, "native command descriptions should come from the parity matrix source of truth");
1777
1977
  assert.match(server, /function parseSlashCommand\(message\)/, "server should parse native slash commands before prompt forwarding");
1778
- assert.match(server, /function generatedTabTitleFromPrompt\(message\)/, "server should derive concise automatic tab titles from first prompts");
1978
+ assert.match(server, /AUTO_TAB_TITLE_MAX_LENGTH = 44;[\s\S]*AUTO_TAB_TITLE_DISPLAY_MAX_LENGTH = 160;/, "compact terminal labels and wider subagent display titles should use separate length limits");
1979
+ assert.match(server, /function generatedTabTitleFromPrompt\(message\)[\s\S]*truncateTabTitle\(titleCaseTabTitle\(selectedWords\.join\(" "\)\), AUTO_TAB_TITLE_DISPLAY_MAX_LENGTH\)/, "server should preserve a longer automatic title before compact terminal truncation");
1980
+ assert.match(server, /function renameTab\(tab, title,[\s\S]*tab\.subagentDisplayTitle = source === "auto" \? truncateTabTitle\(title, AUTO_TAB_TITLE_DISPLAY_MAX_LENGTH\) : undefined;/, "new auto-named tabs should cache their wider subagent display title immediately");
1779
1981
  assert.match(server, /function maybeNameTabForConversation\(tab, command\)/, "server should auto-name default tabs when a conversation starts");
1780
1982
  assert.match(server, /function maybeNameTabForConversation\(tab, command\) \{[\s\S]*const shouldRename = !tab\.conversationStarted && tab\.titleSource !== "explicit";[\s\S]*tab\.conversationStarted = true;[\s\S]*if \(!shouldRename\) return false;/, "server should mark conversations as started even when an explicit title prevents auto-renaming");
1781
1983
  assert.match(server, /function createTabActivity\(/, "server should track per-tab activity for idle, working, and completed work");
@@ -1869,7 +2071,8 @@ assert.match(server, /specific Web UI action or final-output cards/, "server fee
1869
2071
  assert.match(server, /function formatActionFeedbackLearningPrompt\(items\)/, "server should convert feedback into a LEARNING prompt");
1870
2072
  assert.match(server, /url\.pathname === "\/api\/action-feedback" && req\.method === "POST"[\s\S]*?handleActionFeedback\(tab, body\)/, "POST /api/action-feedback should trigger the feedback-learning prompt");
1871
2073
  assert.match(server, /Wait for the current agent run or compaction to finish before sending feedback\./, "server should only accept post-run feedback submissions");
1872
- assert.match(server, /url\.pathname === "\/api\/prompt" && req\.method === "POST"[\s\S]*?handleNativeSlashCommand\(tab, body, req\)/, "POST /api/prompt should intercept native slash commands before normal prompt forwarding with request context");
2074
+ // Intent preserved: request deduplication wraps, but does not bypass, native slash handling.
2075
+ assert.match(server, /async function handlePromptRequest\(tab, body, req\)[\s\S]*?handleNativeSlashCommand\(tab, body, req\)[\s\S]*?url\.pathname === "\/api\/prompt" && req\.method === "POST"[\s\S]*?deduplicateBrowserPromptRequest\(tab, body, \(\) => handlePromptRequest\(tab, body, req\)\)/, "POST /api/prompt should retain native slash handling under browser request deduplication");
1873
2076
  assert.match(server, /function fastPicksStorageFile\(/, "server should define a persistent fast-picks storage file");
1874
2077
  assert.match(server, /PI_WEBUI_FAST_PICKS_FILE/, "server should allow overriding the fast-picks storage path");
1875
2078
  assert.match(server, /async function getPathSuggestionData\(tab, rawQuery\)/, "server should compute @ file\/path reference suggestions for the active tab cwd");
@@ -1930,7 +2133,8 @@ assert.match(server, /writeFile\(tmpFile, body\.content[\s\S]*?rename\(tmpFile,
1930
2133
  assert.match(server, /url\.pathname === "\/api\/themes" && req\.method === "GET"/, "server should expose GET /api/themes");
1931
2134
  assert.match(server, /readBundledThemes\(\)/, "server should read bundled theme JSON files for the browser");
1932
2135
  assert.match(server, /"apple-touch-icon\.png", "icon-192\.png"/, "server should serve the conventional apple touch icon path");
1933
- assert.match(server, /"fast-output-live\.mjs", "subagent-launch-slot-state\.mjs", "subagent-gate-visibility\.mjs", "workflow-status-stack\.mjs", "voice-conversation\.mjs"/, "server should serve browser modules imported by the app");
2136
+ // Intent preserved: the static allowlist must include every app startup module, including the Phase 1 shell state.
2137
+ assert.match(server, /"mobile-shell-state\.mjs", "issue-wizard-state\.mjs", "issue-bot-client\.mjs", "fast-output-live\.mjs"/, "server should serve browser modules imported by the app");
1934
2138
  assert.match(server, /"catppuccin-mocha-background\.png", "matrix-background\.webp", "manifest\.webmanifest", "service-worker\.js"/, "server should serve theme background images as static assets");
1935
2139
  assert.match(server, /\["\.webmanifest", "application\/manifest\+json; charset=utf-8"\]/, "server should serve manifest with the correct MIME type");
1936
2140
  assert.match(server, /\["\.png", "image\/png"\]/, "server should serve PWA PNG icons with the correct MIME type");
@@ -2030,7 +2234,8 @@ assert.ok(pkg.scripts?.check?.includes("node tests/run-all.mjs"), "check script
2030
2234
 
2031
2235
  // --- Performance: keyed transcript reconciliation (P0-1) ---
2032
2236
  assert.match(app, /let renderedTranscriptState = \{ epoch: "", entries: \[\] \};/, "transcript reconciliation should track rendered entries");
2033
- assert.match(app, /function renderAllMessages\(\{ preserveScroll = false, forceRebuild = false \} = \{\}\)[\s\S]*?if \(prefixLength === 0\) resetChatOutput\(\);[\s\S]*?removeChatBubblesAfterPrefix\(/, "renderAllMessages should reuse the unchanged transcript prefix instead of always rebuilding");
2237
+ const renderAllMessagesSource = appFunctionSource("renderAllMessages", "applyNativeSlashCommandEffects");
2238
+ assert.match(renderAllMessagesSource, /prefixLength[\s\S]*?prefixKeys[\s\S]*?transcriptRenderer\.commitTranscriptMutation\(\{[\s\S]*?kind: forceRebuild \? "authoritative" : "reconcile"[\s\S]*?if \(prefixLength === 0\)[\s\S]*?resetChatOutput\(\)[\s\S]*?removeChatBubblesAfterPrefix\(/, "renderAllMessages should reuse the unchanged keyed prefix inside one coordinator transaction instead of always rebuilding");
2034
2239
  assert.match(app, /function removeChatBubblesAfterPrefix\(keptKeys\)[\s\S]*?child === elements\.stickyUserPromptButton \|\| child === runIndicatorBubble/, "prefix removal must preserve the sticky prompt button and run indicator");
2035
2240
  assert.match(app, /function resetChatOutput\(\) \{\n liveToolCards\.clear\(\);\n renderedTranscriptState = \{ epoch: "", entries: \[\] \};/, "full chat resets must clear reconciliation state");
2036
2241
  assert.match(app, /function transcriptRenderEpoch\(\)[\s\S]*?thinkingOutputVisible/, "reconciliation epoch must include thinking visibility so toggles rebuild the transcript");
@@ -2038,7 +2243,8 @@ assert.match(app, /pruneDisconnectedLiveToolCards\(\);/, "reconciliation must pr
2038
2243
 
2039
2244
  // --- Performance: incremental streaming markdown (P0-3) ---
2040
2245
  assert.match(app, /function streamingMarkdownStableBoundary\(text\)[\s\S]*?for \(let index = 0; index < lines\.length - 1; index \+= 1\)/, "streaming markdown boundary must never treat the final partial line as stable");
2041
- assert.match(app, /function renderStreamingMarkdown\(block, text\)[\s\S]*?if \(!text\.startsWith\(state\.stableText\)\)/, "streaming markdown must fall back to a full re-render when earlier content changes");
2246
+ const renderStreamingMarkdownSource = appFunctionSource("renderStreamingMarkdown", "appendImage");
2247
+ assert.match(renderStreamingMarkdownSource, /captureChatTextSelection\(block\)[\s\S]*?transcriptRenderer\.reconcileMarkdownSurface\(\{[\s\S]*?stableBoundary: streamingMarkdownStableBoundary[\s\S]*?renderInto: renderMarkdownInto[\s\S]*?restoreChatTextSelection/, "streaming Markdown must reconcile stable committed blocks and its mutable tail through the coordinator");
2042
2248
  assert.match(app, /streamRawText = "";\n streamThinkingRawText = "";\n resetStreamDerivedTextCache\(\);\n streamMarkdownState = null;/, "resetting the stream bubble must clear incremental markdown state and derived caches");
2043
2249
 
2044
2250
  // --- Performance: delta transcript fetch (P1-1) ---
@@ -2057,6 +2263,7 @@ assert.match(app, /\(event\.ctrlKey \|\| event\.metaKey\) && !event\.altKey && !
2057
2263
  assert.match(app, /function focusChatSearchMatch\(\)[\s\S]*?details\.open = true;[\s\S]*?scrollIntoView/, "navigating to a search match should expand collapsed tool output and scroll to the bubble");
2058
2264
  assert.match(app, /autoFollowChat = false;\n lastChatProgrammaticScrollAt = performance\.now\(\);/, "search navigation must not fight chat auto-follow");
2059
2265
  assert.match(css, /\.message\.search-current \{/, "current search match should have a highlight style");
2266
+ assert.match(css, /\.chat \{[^}]*overflow:\s*auto;[^}]*overflow-anchor:\s*none;/, "the transcript should disable browser scroll anchoring because paused-reader position is controlled explicitly during live growth");
2060
2267
  assert.match(css, /\.chat-search-bar,\n\.file-viewer-search-bar \{/, "transcript search bar should be styled");
2061
2268
 
2062
2269
  console.log("mobile static checks passed");