@firstpick/pi-package-webui 0.7.7 → 0.7.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +23 -0
  2. package/bin/pi-webui-rpc-supervisor.mjs +115 -21
  3. package/bin/pi-webui.mjs +447 -88
  4. package/lib/queue-mutation.mjs +109 -0
  5. package/lib/rpc-supervisor-client.mjs +18 -2
  6. package/lib/rpc-supervisor-protocol.mjs +11 -2
  7. package/lib/scoped-models.mjs +19 -0
  8. package/lib/webui-workspaces.mjs +265 -0
  9. package/package.json +4 -4
  10. package/public/app.js +2227 -195
  11. package/public/index.html +143 -2
  12. package/public/issue-bot-client.mjs +344 -0
  13. package/public/issue-wizard-state.mjs +443 -0
  14. package/public/service-worker.js +3 -1
  15. package/public/styles.css +787 -56
  16. package/public/voice-conversation.mjs +1 -1
  17. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  18. package/tests/compaction-mutation-contract.test.mjs +166 -0
  19. package/tests/compaction-resume-harness.test.mjs +113 -2
  20. package/tests/compaction-static.test.mjs +5 -0
  21. package/tests/completion-signal-contract.test.mjs +156 -0
  22. package/tests/cwd-footer-reliability-static.test.mjs +112 -0
  23. package/tests/durable-rpc-supervisor-harness.test.mjs +25 -2
  24. package/tests/fast-mode-client-static.test.mjs +1 -1
  25. package/tests/file-selection-overlay-static.test.mjs +21 -0
  26. package/tests/file-viewer-search-static.test.mjs +65 -0
  27. package/tests/fixtures/compacting-pi.mjs +0 -0
  28. package/tests/fixtures/fake-pi.mjs +186 -49
  29. package/tests/footer-context-contrast-static.test.mjs +10 -0
  30. package/tests/git-panel-file-preview-static.test.mjs +20 -5
  31. package/tests/git-panel-render-stability-static.test.mjs +11 -1
  32. package/tests/http-endpoints-harness.test.mjs +160 -1
  33. package/tests/issue-bot-client.test.mjs +135 -0
  34. package/tests/issue-wizard-state.test.mjs +126 -0
  35. package/tests/mobile-static.test.mjs +61 -42
  36. package/tests/native-parity.test.mjs +3 -3
  37. package/tests/open-issue-wizard-static.test.mjs +75 -0
  38. package/tests/prompt-routing-tab-status.test.mjs +5 -0
  39. package/tests/queue-edit-reorder-static.test.mjs +101 -0
  40. package/tests/queue-mutation-contract.test.mjs +143 -0
  41. package/tests/rpc-supervisor-host.test.mjs +135 -2
  42. package/tests/rpc-supervisor-protocol.test.mjs +26 -0
  43. package/tests/scoped-models.test.mjs +42 -0
  44. package/tests/streaming-ui-coupling.test.mjs +3 -2
  45. package/tests/subagents-helper.test.mjs +216 -3
  46. package/tests/terminal-tab-workspace-static.test.mjs +101 -0
  47. package/tests/webui-workspaces-harness.test.mjs +223 -0
  48. package/tests/webui-workspaces.test.mjs +106 -0
  49. package/tests/workspace-save-load-static.test.mjs +69 -0
  50. package/webui-rpc-helper.mjs +300 -41
@@ -36,21 +36,21 @@ function appFunctionSource(name, nextName) {
36
36
  }
37
37
  const nativeExportPayload = await readFile(join(root, "lib", "native-export-payload.mjs"), "utf8");
38
38
  const companionDependencies = {
39
- "@firstpick/pi-extension-bang-command-autocomplete": "^0.2.1",
40
- "@firstpick/pi-extension-btw": "^0.1.3",
41
- "@firstpick/pi-extension-fish-user-bash": "^0.2.1",
42
- "@firstpick/pi-extension-git-footer-status": "^0.4.1",
43
- "@firstpick/pi-extension-release-aur": "^0.1.7",
44
- "@firstpick/pi-extension-release-npm": "^0.4.3",
45
- "@firstpick/pi-extension-safety-guard": "^0.2.5",
46
- "@firstpick/pi-extension-setup-skills": "^0.1.8",
47
- "@firstpick/pi-extension-stats": "^0.2.8",
48
- "@firstpick/pi-extension-todo-progress": "^0.2.8",
49
- "@firstpick/pi-extension-tools": "^0.1.6",
50
- "@firstpick/pi-extension-workflows": "^0.1.4",
51
- "@firstpick/pi-package-remote-webui": "^0.1.6",
52
- "@firstpick/pi-prompts-git-pr": "^0.1.4",
53
- "@firstpick/pi-themes-bundle": "^0.1.4",
39
+ "@firstpick/pi-extension-bang-command-autocomplete": "^0.2.2",
40
+ "@firstpick/pi-extension-btw": "^0.1.4",
41
+ "@firstpick/pi-extension-fish-user-bash": "^0.2.2",
42
+ "@firstpick/pi-extension-git-footer-status": "^0.4.3",
43
+ "@firstpick/pi-extension-release-aur": "^0.1.8",
44
+ "@firstpick/pi-extension-release-npm": "^0.4.4",
45
+ "@firstpick/pi-extension-safety-guard": "^0.2.6",
46
+ "@firstpick/pi-extension-setup-skills": "^0.1.9",
47
+ "@firstpick/pi-extension-stats": "^0.2.9",
48
+ "@firstpick/pi-extension-todo-progress": "^0.2.9",
49
+ "@firstpick/pi-extension-tools": "^0.1.7",
50
+ "@firstpick/pi-extension-workflows": "^0.1.7",
51
+ "@firstpick/pi-package-remote-webui": "^0.1.8",
52
+ "@firstpick/pi-prompts-git-pr": "^0.1.5",
53
+ "@firstpick/pi-themes-bundle": "^0.1.5",
54
54
  };
55
55
 
56
56
  assert.match(html, /viewport-fit=cover/, "viewport should opt into safe-area-aware full-screen layout");
@@ -175,10 +175,18 @@ 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
+ const subagentCancelDialogHtml = html.match(/<dialog id="subagentCancelDialog"[\s\S]*?<\/dialog>/)?.[0] || "";
179
+ assert.match(subagentCancelDialogHtml, /id="subagentCancelDialogTitle">Cancel subagent<[\s\S]*id="subagentCancelDialogSubtitle"/, "subagent cancellation should use a titled dialog with dynamic target context");
180
+ 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");
181
+ assert.match(subagentCancelDialogHtml, /<textarea id="subagentCancelNote"[^>]*placeholder="Optional note for the parent agent"/, "subagent cancellation should offer the optional parent note field");
182
+ assert.doesNotMatch(subagentCancelDialogHtml, /<(?:select|textarea) id="subagentCancel(?:Reason|Note)"[^>]*\brequired\b/, "subagent cancellation reason and note must remain optional");
183
+ assert.match(subagentCancelDialogHtml, /id="subagentCancelSubmitButton" class="danger" type="submit">Cancel subagent<\/button>[\s\S]*id="subagentCancelKeepRunningButton"|id="subagentCancelKeepRunningButton"[\s\S]*id="subagentCancelSubmitButton" class="danger" type="submit">Cancel subagent/, "subagent cancellation should expose danger submit and keep-running controls");
184
+ assert.match(html, /id="subagentTerminalView"[\s\S]*id="subagentTerminalCancelButton" class="danger"[^>]*hidden>Cancel…<\/button>/, "subagent terminal headers should include a hidden-until-running cancel control");
178
185
  assert.match(html, /id="subagentLaunchSlots"[\s\S]*id="subagentLaunchSlotsTitle">Agent models<[\s\S]*id="subagentLaunchSlotScope"[\s\S]*<option value="user">User default<\/option>[\s\S]*<option value="project">This project<\/option>[\s\S]*id="subagentLaunchSlotRoles"[\s\S]*id="subagentLaunchSlotsSave"[\s\S]*Save agent models[\s\S]*id="subagentLaunchSlotsReload"[\s\S]*Reload active tab/, "Subagents should expose a separate scoped Agent models editor before the live monitor");
179
186
  assert.match(html, /id="subagentLaunchSlotsInherit"[^>]*hidden[^>]*>Use user defaults<\/button>/, "project launch-slot overrides should expose an explicit inheritance reset");
180
187
  assert.match(html, /id="subagentLaunchSlotScope"[^>]*aria-describedby="subagentLaunchSlotScopeStatus"/, "scope selection should use stable scope help rather than dynamic live status as its accessible description");
181
188
  assert.match(html, /id="subagentLaunchSlotsAnnouncer"[^>]*aria-live="polite"[^>]*aria-atomic="true"/, "launch-slot additions and removals should have a dedicated live announcement");
189
+ 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");
182
190
  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");
183
191
  assert.doesNotMatch(html, /id="subagentOverlayDialog"/, "subagent output should not use a blocking modal dialog");
184
192
  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");
@@ -383,6 +391,9 @@ assert.match(css, /\.file-viewer-editor \{[\s\S]*?overflow-x:\s*hidden;[\s\S]*?o
383
391
  assert.match(css, /\.composer-busy-mode-menu \{[\s\S]*?bottom:\s*calc\(100% \+ 0\.22rem\);[\s\S]*?background:\s*var\(--ctp-crust\)/, "busy prompt behavior dropdown should expand above the tag with an opaque background");
384
392
  assert.match(css, /\.sticky-user-prompt-button \{[\s\S]*?grid-template-columns:\s*auto minmax\(0, 1fr\) auto/, "last-user-prompt jump control should render as a fixed transcript header");
385
393
  assert.match(css, /@media \(max-width: 720px\), \(max-device-width: 720px\), \(pointer: coarse\) and \(hover: none\)[\s\S]*?\.sticky-user-prompt-button \{\n\s+grid-template-columns:\s*minmax\(0, 1fr\) auto;\n\s+min-height:\s*36px;[\s\S]*?\.sticky-user-prompt-text \{[\s\S]*?font-size:\s*var\(--text-xs\)/, "mobile last-user-prompt card should preserve compact height while respecting the text floor");
394
+ assert.match(html, /id="followUpQueueTrigger"[^>]*aria-controls="followUpQueueOverlay"[\s\S]*id="followUpQueueOverlay"[\s\S]*id="followUpQueueStatus"[^>]*aria-live="polite"/, "mobile composer should expose the accessible queued follow-up trigger and overlay");
395
+ assert.match(css, /\.follow-up-queue-overlay \{[\s\S]*bottom:\s*calc\(100% \+ 0\.42rem\)[\s\S]*var\(--visual-viewport-height, 100dvh\)[\s\S]*body\.mobile-keyboard-open \.follow-up-queue-trigger:not\(\[hidden\]\) \{ display: inline-flex; \}/, "mobile queue overlay should float above the composer, fit the visual viewport, and keep its trigger usable with the keyboard open");
396
+ assert.doesNotMatch(app, /nextQueuedFollowUpPrompt|sticky-user-follow-up-prompt|Next follow-up prompt:/, "the mobile sticky prompt control should not duplicate a queued follow-up preview");
386
397
  assert.match(css, /\.message\.extension,[\s\S]*?\.message\.native/, "extension and native command output should have visible transcript styling");
387
398
  assert.match(app, /const FEATURE_CATEGORY_STATUS_KEY = "feature-category";[\s\S]*const featureCategoryByTab = new Map\(\)/, "feature category status should use a dedicated per-tab transport key and state map");
388
399
  assert.match(app, /function normalizeFeatureCategory\(value\) \{\s+return value === "lightweight-feature" \|\| value === "complex-feature" \? value : "";/, "feature category normalization should accept only the two approved exact labels");
@@ -530,16 +541,17 @@ assert.match(css, /@media \(max-width: 720px\) \{[\s\S]*?\.command-palette-dialo
530
541
  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");
531
542
  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");
532
543
  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");
533
- assert.match(html, /class="terminal-sidebar-actions"[^>]*aria-label="Tab and workspace actions"[\s\S]*id="splitTabButton"[\s\S]*>Split<\/span>[\s\S]*id="commandPaletteButton"[\s\S]*>Commands<\/span>[\s\S]*id="workspaceDashboardToggleButton"[\s\S]*>Overview<\/span>/, "tab, command, and workspace actions should share one labeled sidebar toolbar");
534
- assert.match(css, /body\.terminal-tabs-left \.terminal-sidebar-actions \{[\s\S]*?display:\s*grid;[\s\S]*?grid-template-columns:\s*repeat\(3, 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 three-button toolbar with readable touch targets");
535
- 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-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\(300% \+ 0\.84rem\);/, "left-sidebar command and overview tooltips should render above the full toolbar without clipping");
536
- assert.match(css, /terminal-command-palette-button\[data-tooltip\]::after \{\s+left:\s*calc\(-100% - 0\.42rem\);[\s\S]*?terminal-dashboard-button\[data-tooltip\]::after \{\s+left:\s*calc\(-200% - 0\.84rem\);/, "left-sidebar tooltips should align to the toolbar edges from their individual buttons");
544
+ 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");
545
+ 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");
546
+ 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");
547
+ 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");
537
548
  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");
538
549
  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");
539
550
  assert.match(css, /body\.terminal-tabs-left \.terminal-tabs \{[\s\S]*?flex-direction:\s*column/, "terminal tabs left layout should stack tabs vertically");
540
551
  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");
541
552
  assert.match(css, /body\.terminal-tabs-left \.terminal-new-tab-menu \.composer-publish-menu-panel \{[\s\S]*?inset:\s*0 auto auto 100%;[\s\S]*?padding-left:\s*var\(--terminal-left-dropdown-bridge\)/, "left-sidebar new-tab dropdown should include a hover bridge so it does not vanish between button and dropdown");
542
553
  assert.match(css, /\.terminal-new-tab-menu \.composer-publish-menu-panel \{[\s\S]*?inset:\s*100% 0 auto auto;[\s\S]*?padding-top:\s*0\.38rem/, "new-tab dropdown should reuse the shared composer panel and open below the tab bar");
554
+ assert.match(css, /\.terminal-tabs > \.terminal-new-tab-menu:only-child \.composer-publish-menu-panel \{\s*inset:\s*100% auto auto 0;/, "zero-tab new-tab dropdown should align to the left edge instead of extending off-screen");
543
555
  assert.match(css, /\.terminal-new-tab-menu \.composer-publish-menu-item \{[\s\S]*?color:\s*var\(--ctp-pink\)/, "new-tab dropdown items should reuse shared composer menu items with a tab-specific color");
544
556
  assert.match(css, /\.terminal-close-all-button \{[\s\S]*?color:\s*var\(--ctp-red\)/, "close-all tabs action should render as a top-right destructive tab action");
545
557
  assert.match(css, /\.terminal-tabs\.terminal-tabs-dense \{[\s\S]*?flex-wrap:\s*wrap/, "large terminal tab sets should wrap into a readable dense tab strip");
@@ -603,7 +615,7 @@ assert.match(app, /async function loadMissingGitUntrackedContent\(entry[\s\S]*?\
603
615
  assert.match(app, /function updateGitChangesCurrentFileHeader\(\)[\s\S]*?querySelectorAll\("\.git-diff-file\[data-git-diff-file\]"\)/, "git changes modal should derive the sticky current-file header from visible file cards");
604
616
  assert.match(app, /function renderGitChangesFileList\(parsedSections, untracked\)[\s\S]*dataset\.gitChangesJumpFile = item\.path[\s\S]*git-changes-file-jump-meta/, "git changes modal should render jump buttons for each changed file");
605
617
  assert.match(app, /gitChangesBody\?\.addEventListener\("click"[\s\S]*data-git-changes-jump-file[\s\S]*scrollIntoView\(\{ block: "start", behavior: "smooth" \}\)/, "git changes file jump buttons should scroll to their diff cards");
606
- assert.match(server, /async function readGitUntrackedEntry\(root, file\)[\s\S]*?content: binary \? "" : buffer\.toString\("utf8"\)/, "server should include complete text contents for untracked files");
618
+ assert.match(server, /async function readGitUntrackedEntry\(root, file, \{ maxBytes = Number\.POSITIVE_INFINITY \} = \{\}\)[\s\S]*?content: binary \? "" : buffer\.toString\("utf8"\)/, "server should include complete text contents for untracked files");
607
619
  assert.match(server, /url\.pathname === "\/api\/git-changes\/untracked-file" && req\.method === "GET"/, "server should expose a focused untracked-file content endpoint for stale path-only payload fallbacks");
608
620
  assert.match(server, /async function readGitChanges\(cwd\)[\s\S]*?const diffArgs = \["diff", "--no-ext-diff"[\s\S]*?"--unified=0"[\s\S]*?\["diff", "--cached"/, "server should collect compact staged and unstaged git diffs for the changes modal");
609
621
  assert.match(server, /\["status", "--porcelain=2", "--branch", "--untracked-files=all"\][\s\S]*?summarizeGitPorcelainStatus\(porcelainStatusText\)/, "server should derive behind/ahead from locale-independent porcelain status so the Pull button activates after fetch");
@@ -762,7 +774,8 @@ assert.match(app, /resizePromptInput\(\);\nrestoreSidePanelWidthPreference\(\);\
762
774
  assert.match(app, /elements\.promptInput\.addEventListener\("focus", \(\) => \{\n\s+syncMobileChatToBottomForInput\(\);/, "focusing mobile input should scroll output to bottom");
763
775
  assert.match(app, /navigator\.serviceWorker\.register\("\/service-worker\.js"\)/, "PWA service worker should be registered by the app");
764
776
  assert.match(app, /function serverStartCommandText\(\)[\s\S]*return `pi-webui\$\{currentPortArg\(\)\}`/, "PWA/offline shell should build a pathless pi-webui recovery command");
765
- assert.match(app, /async function createFirstTerminalTabFromChosenDirectory\(\)/, "frontend should prompt for the first terminal cwd when no tabs exist");
777
+ assert.match(app, /async function createFirstTerminalTabFromChosenDirectory\(\)/, "frontend should define the first-terminal cwd prompt");
778
+ assert.match(app, /async function initializeTabs\(\)[\s\S]*?if \(!saved\.length\) await createFirstTerminalTabFromChosenDirectory\(\)/, "frontend should still prompt for the first terminal cwd when no saved workspace can be loaded");
766
779
  assert.match(app, /Choose CWD for first terminal/, "frontend should title the first-terminal cwd picker clearly");
767
780
  assert.match(app, /Pi Web UI server is offline/, "PWA/offline shell should clearly report backend-down state");
768
781
  assert.match(app, /navigator\.clipboard\.writeText\(text\)/, "backend-offline recovery panel should copy the start command when possible");
@@ -832,6 +845,15 @@ assert.match(
832
845
  );
833
846
  assert.match(app, /function renderCodexUsage\(\)/, "frontend should render Codex usage buckets in the side panel");
834
847
  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");
848
+ 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");
849
+ 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");
850
+ 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");
851
+ 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");
852
+ 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");
853
+ 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");
854
+ 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");
855
+ 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");
856
+ 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");
835
857
  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");
836
858
  assert.match(app, /function subagentLaunchSlotThinkingForModel\(model\)[\s\S]*modelThinkingLevels/, "launch-slot thinking choices should come from the selected model metadata");
837
859
  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");
@@ -848,7 +870,7 @@ assert.match(server, /WEBUI_SUBAGENT_GATE_LIMIT[\s\S]*rawGate\.attempts[\s\S]*fa
848
870
  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");
849
871
  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");
850
872
  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");
851
- assert.match(app, /function subagentSourceLabel\(source = ""\) \{[\s\S]*source === "foreground" \|\| source === "workflow"[\s\S]*function subagentOverlayStateFacts\(data = subagentOverlayData\)[\s\S]*subagentSourceLabel\(data\?\.source \|\| subagentOverlaySelection\?\.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");
873
+ 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");
852
874
  assert.match(app, /function renderSubagentAgent\(tab, run, agent\)[\s\S]*\.\.\.subagentExecutionFacts\(agent\)/, "Subagents side-panel rows should show model and reasoning effort");
853
875
  assert.match(app, /function subagentOverlayStateFacts\(data = subagentOverlayData\)[\s\S]*\.\.\.subagentExecutionFacts\(agent\)/, "subagent overlays should show model and reasoning effort");
854
876
  assert.match(app, /function renderSubagentTerminalView\(\)[\s\S]*\.\.\.subagentExecutionFacts\(agent\)/, "dedicated subagent terminal views should show model and reasoning effort");
@@ -904,7 +926,7 @@ assert.doesNotMatch(subagentTerminalCloseSource, /\bapi\(|closeTerminalTabs\(|cl
904
926
  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");
905
927
  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");
906
928
  assert.match(app, /SUBAGENT_OVERLAY_REFRESH_MS = 1000/, "subagent overlay should poll selected live output at a fast cadence");
907
- assert.match(app, /function createMessageBubble\(message,[\s\S]*renderContent\(body, message\.content, \{ markdown: message\.role === "assistant" \}\)[\s\S]*function appendMessage\(message, options = \{\}\)[\s\S]*createMessageBubble\(message, options\)/, "main transcript output should use the reusable message bubble renderer");
929
+ 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");
908
930
  const subagentTranscriptMessagesSource = appFunctionSource("subagentOverlayTranscriptMessages", "subagentOverlayToolArguments");
909
931
  assert.ok(subagentTranscriptMessagesSource.includes("message.role === \"assistant\" || message.role === \"toolResult\""), "subagent overlays should retain structured assistant and tool-result entries");
910
932
  const subagentToolArgumentsSource = appFunctionSource("subagentOverlayToolArguments", "subagentOverlayTranscriptDisplayMessages");
@@ -1178,7 +1200,7 @@ assert.match(app, /async function startVoiceConversationLoop\(tabId = activeTabI
1178
1200
  assert.match(app, /function isLocalhostWebui\(\)[\s\S]*127\.0\.0\.1/, "remote-consent detection should treat localhost as implicitly consented");
1179
1201
  assert.match(app, /function latestAssistantSpokenText\(\)[\s\S]*assistantDisplayMessages\(message\)\.find\(\(item\) => item\?\.title === "final output"\)/, "spoken text must come from final output only, never thinking or tool payloads");
1180
1202
  assert.match(app, /function speakableTextFromMarkdown\(text\)[\s\S]*Code block omitted/, "spoken text should strip code blocks and markdown syntax");
1181
- assert.match(app, /case "agent_end":[\s\S]*handleVoiceConversationTurnEnd\(tabContext\)/, "agent_end should hand the finished turn to the voice loop");
1203
+ assert.match(app, /case "agent_settled":[\s\S]*handleVoiceConversationTurnEnd\(tabContext\)/, "agent_settled should hand the fully finished turn to the voice loop");
1182
1204
  assert.match(app, /case "tool_execution_start":[\s\S]*setAssistantActivity\(\{ toolRunning: true \}\)/, "tool execution start should mark the voice loop tool phase");
1183
1205
  assert.match(app, /case "tool_execution_end":[\s\S]*setAssistantActivity\(\{ toolRunning: false \}\)/, "tool execution end should clear the voice loop tool phase");
1184
1206
  assert.match(html, /id="remoteMicStreamingConsentButton"[^>]*disabled>Allow remote microphone streaming</, "remote mic consent button should exist, start disabled, and use action-specific copy");
@@ -1200,7 +1222,7 @@ assert.match(app, /if \(key === "pi-remote-webui"\) return "remoteWebui"/, "opti
1200
1222
  assert.match(app, /REMOTE_WEBUI_CONTROLS_PAYLOAD_TYPE = "firstpick\.pi-package-remote-webui\.controls"/, "Remote WebUI package should announce browser controls through a package-owned status payload");
1201
1223
  assert.match(app, /function combineIdenticalDuplicateCommands\(commands\)[\s\S]*duplicateGroups[\s\S]*duplicateCount: group\.length/, "identical duplicate RPC commands should be combined into one visible command entry");
1202
1224
  assert.match(app, /if \(kind === "prompt" && attachments\.length === 0\) message = resolveRpcSlashCommandMessage\(message, \{ tabId: targetTabId \}\)/, "manual targeted slash prompts should resolve combined duplicate command aliases from their captured target tab before reaching Pi RPC");
1203
- assert.match(app, /if \(!isOptionalFeatureEnabled\("todoProgressWidget"\)\) return String\(text \|\| ""\)/, "todo progress line stripping should only run when the todo feature is detected and enabled");
1225
+ assert.match(app, /if \(!isOptionalFeatureDetected\("todoProgressWidget"\)\) return String\(text \|\| ""\)/, "todo progress line stripping should keep transport filtering active whenever the todo feature is detected");
1204
1226
  assert.match(app, /const releasePrompt = detectedReleasePrompt && isOptionalFeatureEnabled\(detectedReleasePrompt\.featureId\) \? detectedReleasePrompt : null/, "release confirmation dialogs should use specialized rendering only when their release optional feature is enabled");
1205
1227
  assert.match(app, /case "webui_tab_reloaded":[\s\S]*resetOptionalFeatureAvailability\(\)/, "optional feature state should reset when the RPC tab reloads resources");
1206
1228
  assert.match(app, /function runPublishWorkflow\(command\)[\s\S]*resolveAvailableCommandName\(commandName, \{ rpcOnly: true \}\)/, "publish workflow launch should guard on loaded slash commands, including duplicate-suffixed RPC command names");
@@ -1301,7 +1323,7 @@ assert.match(app, /const ACTION_FEEDBACK_REACTIONS = \{/, "frontend should defin
1301
1323
  assert.match(app, /message\?\.role === "assistant" \|\| message\?\.role === "toolExecution" \|\| message\?\.role === "toolResult" \|\| message\?\.role === "bashExecution"/, "frontend should allow reactions on final assistant output as well as actions");
1302
1324
  assert.match(app, /function renderActionFeedbackControls\(/, "frontend should render per-message reaction controls");
1303
1325
  assert.match(app, /function toolResultPreviewText\(message, lineLimit = 10\)/, "tool results should derive a ten-line collapsed preview");
1304
- assert.match(app, /function renderToolExecution\(parent, message\)[\s\S]*?WEBUI_TOOL_RENDERERS/, "paired tool cards should use the browser-side built-in tool renderer registry");
1326
+ assert.match(app, /const WEBUI_TOOL_RENDERERS = \{[\s\S]*?function renderSingleToolExecution\(parent, message\)[\s\S]*?WEBUI_TOOL_RENDERERS[\s\S]*?function renderToolExecution\(parent, message\)[\s\S]*?renderSingleToolExecution\(parent, message\)/, "paired tool cards should use the browser-side built-in tool renderer registry");
1305
1327
  assert.match(app, /appendToolRawDetails\(parent, tool\)/, "paired tool cards should keep a safe raw-data expander for debugging renderer mismatches");
1306
1328
  assert.match(app, /function toolStateMeta\(tool\)/, "tool cards should expose consistent status and elapsed metadata across built-in renderers");
1307
1329
  assert.match(app, /const TOOL_LIVE_UPDATE_THROTTLE_MS = 80/, "live tool cards should coalesce rapid partial updates before re-rendering");
@@ -1367,7 +1389,7 @@ assert.doesNotMatch(app, /Preparing tool call:/, "tool-call streaming should no
1367
1389
  assert.match(app, /const created = appendMessage\(\{ role: "assistant", title: "final output"/, "live Assistant cards should be created only for final output text without a noisy Assistant label");
1368
1390
  assert.match(app, /function renderMarkdownInto\(parent, text\)/, "assistant output should have a browser-native Markdown renderer");
1369
1391
  assert.match(app, /safeMarkdownLinkHref\(url\)/, "Markdown links should be sanitized before rendering");
1370
- assert.match(app, /renderContent\(body, message\.content, \{ markdown: message\.role === "assistant" \}\)/, "final assistant output should render through the Markdown path");
1392
+ assert.match(app, /renderContent\(body, message\.content, \{ markdown: message\.role === "assistant" \|\| message\.role === "custom" \}\)/, "final assistant output should render through the Markdown path");
1371
1393
  assert.match(app, /const hideMessageHeader = message\.role === "assistant" && !isCollapsibleOutput/, "assistant final-output cards should hide the redundant role header");
1372
1394
  assert.match(app, /api\("\/api\/action-feedback", \{ method: "POST"/, "queued action feedback should post to the server after the run is idle");
1373
1395
  assert.match(app, /function postQueuedFeedback\(tabId, items, tabContext = activeTabContext\(tabId\)\)/, "queued feedback should have a backward-compatible submit path");
@@ -1418,14 +1440,15 @@ assert.match(app, /case "tool_execution_update":[\s\S]*?handleToolExecutionUpdat
1418
1440
  assert.match(app, /case "auto_retry_start":[\s\S]*?addTransientMessage\(\{ role: "warn", title: "auto retry"/, "auto-retry starts should be transcript-visible warnings");
1419
1441
  assert.match(app, /function trackAutoRetryStateFromEvent\(event\)[\s\S]*?event\.type === "auto_retry_start"[\s\S]*?autoRetryingTabs\.add\(tabId\)[\s\S]*?suppressPendingAgentDoneNotificationsForTab\(tabId\)[\s\S]*?markTabWorkingLocally\(tabId\)/, "auto-retry starts should suppress misleading done notifications and keep the tab working");
1420
1442
  assert.match(app, /function notifyAgentDone[\s\S]*?agentDoneNotificationKeys\.add\(key\);\n\s+if \(isAutoRetryingTab\(tabId\)\) return;/, "agent-done notifications should be ignored while a tab is auto-retrying");
1421
- assert.match(app, /function queueAgentDoneBrowserNotification[\s\S]*?setTimeout\([\s\S]*?if \(isAutoRetryingTab\(tabId\)\) return;[\s\S]*?AGENT_DONE_NOTIFICATION_RETRY_GRACE_MS/, "agent-done notifications should wait briefly so imminent auto-retry events can cancel them");
1443
+ assert.match(app, /function queueAgentDoneBrowserNotification[\s\S]*?setTimeout\([\s\S]*?isAutoRetryingTab\(tabId\)[\s\S]*?promptRoutingTabs\.has\(tabId\)[\s\S]*?activityForTab\(tab\)\.isWorking[\s\S]*?AGENT_DONE_NOTIFICATION_RETRY_GRACE_MS/, "agent-done notifications should wait briefly and suppress stale alerts when retry or new work starts");
1422
1444
  assert.match(app, /case "extension_error":[\s\S]*?addTransientMessage\(\{ role: "error", title: "extension error"/, "extension errors should be transcript-visible error cards");
1423
1445
  assert.match(app, /setRunIndicatorActivity\("Requesting context compaction…"\);\n\s+scrollChatToBottom\(\{ force: true \}\);/, "manual compaction should force-follow the transcript to the bottom status card");
1424
1446
  assert.match(app, /function markContextUsageUnknownAfterCompaction\(/, "compaction should have a dedicated context-usage invalidation helper");
1425
1447
  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");
1426
1448
  assert.match(app, /function footerStatsContextDisplay[\s\S]*?contextUsageUnknownAfterCompaction\(\)[\s\S]*?unknownFooterContextText/, "fallback footer context should show an unknown value after compaction invalidates usage");
1427
- assert.match(app, /case "agent_end":[\s\S]*?clearRunIndicatorActivity\(\)/, "agent completion should remove the active agent transcript indicator");
1428
- assert.match(app, /case "agent_end":[\s\S]*?notifyAgentDone\(event\.tabId \|\| activeTabId/, "agent completion should trigger optional done notifications");
1449
+ assert.match(app, /case "agent_settled":[\s\S]*?clearRunIndicatorActivity\(\)/, "agent settlement should remove the active agent transcript indicator");
1450
+ assert.match(app, /case "agent_settled":[\s\S]*?notifyAgentDone\(event\.tabId \|\| activeTabId/, "agent settlement should trigger optional done notifications");
1451
+ 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");
1429
1452
  assert.match(app, /function getPathTrigger\(\)/, "prompt composer should detect @ file\/path reference triggers");
1430
1453
  assert.match(app, /api\(`\/api\/path-suggestions\?query=\$\{encodeURIComponent\(trigger\.query\)\}`/, "@ reference suggestions should load from the server as the user types");
1431
1454
  assert.match(app, /async function api\([\s\S]*?if \(signal\?\.aborted \|\| error\?\.name === "AbortError"\) throw error;[\s\S]*?setBackendOffline\(true, offlineError\)/, "cancelled @ autocomplete requests should not mark the server offline");
@@ -1489,7 +1512,7 @@ assert.match(app, /function renderBtwComposerForm\(\)[\s\S]*?form\.requestSubmit
1489
1512
  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");
1490
1513
  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");
1491
1514
  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");
1492
- assert.match(app, /if \(startsRun\) \{\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");
1515
+ 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");
1493
1516
  assert.match(app, /if \(startsRun && isCurrentTabContext\(tabContext\)\) setRunIndicatorActivity\("Routing complete; starting agent…"\);/, "prepared prompts should transition from routing to agent-start progress before dispatch");
1494
1517
  assert.match(app, /function runPublishWorkflow\(command\)[\s\S]*?sendPrompt\("prompt", `\/\$\{resolvedCommandName\}\$\{commandRest\}`\)/, "Publish workflows should send resolved slash commands directly without replacing the draft");
1495
1518
  assert.match(app, /async function runNativeCommandMenu\(command\)[\s\S]*?await handleNativeSlashSelectorCommand\(command\)/, "skills/tools command menu should open native selector dialogs directly");
@@ -1574,10 +1597,6 @@ assert.match(app, /function updateStickyUserPromptButton\(/, "last user prompt h
1574
1597
  assert.match(app, /function jumpToStickyUserPrompt\(/, "last user prompt header should jump to its source message");
1575
1598
  assert.match(app, /data-user-prompt/, "user prompt messages should be marked for sticky prompt navigation");
1576
1599
  assert.match(app, /function resetChatOutput\(\)[\s\S]*?stickyUserPromptButton/, "chat rerenders should preserve the sticky user prompt control inside the transcript scroller");
1577
- assert.match(app, /function nextQueuedFollowUpPrompt\(tabId = activeTabId\)/, "sticky prompt header should derive the next queued follow-up prompt for display");
1578
- assert.match(app, /sticky-user-follow-up-prompt[\s\S]*Next follow-up/, "sticky prompt header should render the next follow-up under the last user prompt");
1579
- assert.match(app, /function renderQueue\(event\)[\s\S]*updateStickyUserPromptButton\(\)/, "queue updates should refresh the sticky last-user-prompt header");
1580
- assert.match(css, /\.sticky-user-follow-up-prompt \{[\s\S]*?grid-column:\s*1 \/ -1/, "next follow-up should render below the sticky last-user-prompt row");
1581
1600
  assert.match(app, /LAST_USER_PROMPT_STORAGE_KEY/, "last user prompt should be cached so compaction cannot remove the sticky prompt preview");
1582
1601
  assert.match(app, /function syncLastUserPromptFromMessages\(messages = latestMessages\)/, "message refresh should preserve the latest user prompt across compacted transcripts");
1583
1602
  assert.match(app, /dataset\.compacted/, "sticky prompt should expose a compacted fallback state when its source message was summarized away");
@@ -1622,7 +1641,7 @@ assert.match(app, /case "webui_connected":[\s\S]*?featureCategoryByTab\.delete\(
1622
1641
  assert.match(app, /async function reconcileForegroundState\(reason = "resume"\)[\s\S]*?refreshTabs\(\)[\s\S]*?ensureActiveEventStream\(tabContext\)[\s\S]*?refreshAll\(tabContext\)/, "foreground reconciliation should refresh tabs plus active transcript after mobile backgrounding");
1623
1642
  assert.match(app, /document\.addEventListener\("visibilitychange"[\s\S]*?scheduleForegroundReconcile\("visibility resume", 0\)/, "returning to a hidden mobile tab should force a server snapshot refresh");
1624
1643
  assert.match(app, /window\.addEventListener\("pageshow", \(\) => scheduleForegroundReconcile\("page show", 0\)\)/, "BFCache or PWA page resume should force a server snapshot refresh");
1625
- assert.match(app, /async function refreshMessages\(tabContext = activeTabContext\(\)\)[\s\S]*?if \(!isCurrentTabContext\(tabContext\)\) return;/, "message refreshes should not render after the user switches tabs");
1644
+ assert.match(app, /async function refreshMessages\(tabContext = activeTabContext\(\), \{ authoritative = false \} = \{\}\)[\s\S]*?if \(!isCurrentTabContext\(tabContext\)\) return;/, "message refreshes should not render after the user switches tabs");
1626
1645
  assert.match(app, /function tabIndicator\(tab\)/, "frontend should derive idle, working, blocked, and work-done tab indicator states");
1627
1646
  assert.match(app, /pendingBlockerCount > 0[\s\S]*?state: "blocked"/, "frontend should show blocked tabs when extension UI blockers are pending");
1628
1647
  assert.match(app, /const EXTENSION_UI_BLOCKING_METHODS = new Set\(\["select", "confirm", "input", "editor"\]\)/, "frontend should share blocking extension UI method detection for dialogs and notifications");
@@ -1740,10 +1759,10 @@ assert.match(server, /delete process\.env\.PI_WEBUI_RESTORE_TABS/, "server shoul
1740
1759
  assert.match(server, /if \(sessionFile && !options\.noSession\) piArgs\.push\("--session", sessionFile\)/, "restored tabs should resume previous session files");
1741
1760
  assert.doesNotMatch(server, /args\.push\("--name"/, "Web UI tab titles should not be forwarded as Pi CLI --name flags because older bundled Pi CLIs reject them");
1742
1761
  assert.match(server, /const closedRestorableTabs = \[\]/, "server should track recently closed tabs separately from restart restore descriptors");
1743
- assert.match(server, /async function closeTab\(id\)[\s\S]*?rememberClosedRestorableTab\(tab, restorableState\)/, "closing a tab should capture its session before stopping RPC for detailed closed-tab status");
1762
+ assert.match(server, /async function closeTab\(id, \{ allowLast = false \} = \{\}\)[\s\S]*?rememberClosedRestorableTab\(tab, restorableState\)/, "closing a tab should capture its session before stopping RPC for detailed closed-tab status");
1744
1763
  assert.match(server, /async function restorableTabsForRestart\(\)[\s\S]*?return mergeRestorableTabDescriptors\(liveDescriptors\)/, "server restart should restore only currently open tabs");
1745
1764
  assert.doesNotMatch(server, /return mergeRestorableTabDescriptors\(liveDescriptors,\s*closedRestorableTabs\)/, "server restart should not restore closed tabs");
1746
- assert.match(server, /async function closeTabs\(ids\)[\s\S]*?if \(targetTabs\.length >= tabs\.size\) \{\n\s+await createTab/, "bulk tab close should create a replacement before closing every current tab");
1765
+ assert.match(server, /async function closeTabs\(ids, \{ allowEmpty = false \} = \{\}\)[\s\S]*?if \(!allowEmpty && targetTabs\.length >= tabs\.size\) \{\n\s+await createTab/, "bulk tab close should preserve replacement-tab behavior unless an explicit close-all requests the workspace-load empty state");
1747
1766
  assert.match(server, /url\.pathname === "\/api\/tabs\/close" && req\.method === "POST"[\s\S]*?closedIds: closed\.map\(\(tab\) => tab\.id\)/, "server should expose a bulk close-tabs endpoint");
1748
1767
  assert.match(server, /function rememberTabState\(tab, state\)/, "server should cache last-known tab state for restart-safe session restoration");
1749
1768
  assert.match(server, /sessionFile: tabRestorableSessionFile\(tab\)/, "tab metadata should expose cached session files for health/status restore descriptors");
@@ -1860,7 +1879,7 @@ assert.match(server, /writeFile\(tmpFile, body\.content[\s\S]*?rename\(tmpFile,
1860
1879
  assert.match(server, /url\.pathname === "\/api\/themes" && req\.method === "GET"/, "server should expose GET /api/themes");
1861
1880
  assert.match(server, /readBundledThemes\(\)/, "server should read bundled theme JSON files for the browser");
1862
1881
  assert.match(server, /"apple-touch-icon\.png", "icon-192\.png"/, "server should serve the conventional apple touch icon path");
1863
- assert.match(server, /"fast-output-live\.mjs", "subagent-launch-slot-state\.mjs", "voice-conversation\.mjs"/, "server should serve the launch-slot state module imported by the browser app");
1882
+ 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");
1864
1883
  assert.match(server, /"catppuccin-mocha-background\.png", "matrix-background\.webp", "manifest\.webmanifest", "service-worker\.js"/, "server should serve theme background images as static assets");
1865
1884
  assert.match(server, /\["\.webmanifest", "application\/manifest\+json; charset=utf-8"\]/, "server should serve manifest with the correct MIME type");
1866
1885
  assert.match(server, /\["\.png", "image\/png"\]/, "server should serve PWA PNG icons with the correct MIME type");
@@ -1907,7 +1926,7 @@ for (const [name, range] of Object.entries(companionDependencies)) {
1907
1926
  assert.equal(pkg.optionalDependencies?.[name], range, `webui package should optionally depend on ${name}`);
1908
1927
  assert.equal(pkg.dependencies?.[name], undefined, `webui package should not require optional companion ${name}`);
1909
1928
  assert.equal(lock.packages?.[""]?.optionalDependencies?.[name], range, `package-lock root should optionally depend on ${name}`);
1910
- assert.equal(lock.packages?.[""]?.dependencies?.[name], undefined, `package-lock root should not require optional companion ${name}`);
1929
+ assert.equal(lock.packages?.[""]?.dependencies?.[name], range, `package-lock root should record the installed optional companion ${name}`);
1911
1930
  assert.ok(lock.packages?.[`node_modules/${name}`], `package-lock should include resolved optional companion ${name}`);
1912
1931
  }
1913
1932
  assert.equal(pkg.bundledDependencies, undefined, "webui optional companion packages should not be bundled into the tarball");
@@ -1973,7 +1992,7 @@ assert.match(app, /streamRawText = "";\n streamThinkingRawText = "";\n resetSt
1973
1992
 
1974
1993
  // --- Performance: delta transcript fetch (P1-1) ---
1975
1994
  assert.match(app, /function mergeMessagesDelta\(previous, data\)[\s\S]*?messagesLookEqual\(previous\[since\], data\.messages\[0\]\)/, "delta merges must verify the one-message overlap before applying");
1976
- assert.match(app, /async function refreshMessages\(tabContext = activeTabContext\(\)\)[\s\S]*?\/api\/messages\?since=/, "message refreshes should request transcript deltas");
1995
+ assert.match(app, /async function refreshMessages\(tabContext = activeTabContext\(\), \{ authoritative = false \} = \{\}\)[\s\S]*?\/api\/messages\?since=/, "message refreshes should request transcript deltas");
1977
1996
  assert.match(app, /if \(!nextMessages\) \{[\s\S]*?api\("\/api\/messages", \{ tabId: tabContext\.tabId \}\)/, "delta failures must fall back to a full transcript fetch");
1978
1997
  assert.match(server, /function applyMessagesSinceParam\(response, url\)/, "server should slice get_messages results for \\?since= requests");
1979
1998
  assert.match(app, /const messageStaticSignatureCache = new WeakMap\(\);/, "static message signatures should be cached by object identity");
@@ -1987,6 +2006,6 @@ assert.match(app, /\(event\.ctrlKey \|\| event\.metaKey\) && !event\.altKey && !
1987
2006
  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");
1988
2007
  assert.match(app, /autoFollowChat = false;\n lastChatProgrammaticScrollAt = performance\.now\(\);/, "search navigation must not fight chat auto-follow");
1989
2008
  assert.match(css, /\.message\.search-current \{/, "current search match should have a highlight style");
1990
- assert.match(css, /\.chat-search-bar \{/, "transcript search bar should be styled");
2009
+ assert.match(css, /\.chat-search-bar,\n\.file-viewer-search-bar \{/, "transcript search bar should be styled");
1991
2010
 
1992
2011
  console.log("mobile static checks passed");
@@ -172,9 +172,9 @@ assert.match(server, /nativeExportDownloadPayload\(\{[\s\S]*localRequest: isLoca
172
172
  assert.match(server, /openUrl: record\.contentType === MIME_TYPES\.get\("\.html"\)/, "HTML native downloads should expose a browser-open URL");
173
173
  assert.match(server, /url\.searchParams\.get\("disposition"\) === "inline"/, "native download endpoint should support inline HTML rendering");
174
174
  assert.match(server, /copyFile\(sessionFile, targetPath\)/, "explicit .jsonl /export should copy the active session file");
175
- assert.match(app, /function triggerNativeDownload\(download\)/, "frontend should know how to trigger native command downloads");
175
+ assert.match(app, /function triggerNativeDownload\(download\)[\s\S]*try \{[\s\S]*anchor\.click\(\)[\s\S]*finally \{[\s\S]*anchor\.remove\(\)/, "frontend should clean up download anchors even when browser opening throws");
176
176
  assert.match(app, /function applyNativeSlashCommandEffects\(response, message, tabContext/, "frontend should apply centralized native slash-command adapter effects");
177
- assert.match(app, /data\.download && handleNativeDownloadResponse\(data\.download, data\.command, data\.serverPath\)/, "frontend should route native downloads and their saved path through command-specific handling");
177
+ assert.match(app, /if \(data\.download\) \{[\s\S]*handleNativeDownloadResponse\(data\.download, data\.command, data\.serverPath\)[\s\S]*could not open \$\{data\.command === "export" \? "HTML export" : "download"\}/, "frontend should catch and surface native HTML/download open failures");
178
178
  assert.match(app, /function openNativeExportDownloadPrompt\(download, serverPath = ""\)[\s\S]*Saved to:\\n[\s\S]*Copy path[\s\S]*copyText\(savedPath\)[\s\S]*Open in browser/, "frontend should show and copy the saved /export HTML path before offering browser open");
179
179
  assert.match(app, /function alternateLoopbackBrowserUrl\(value\)[\s\S]*hostname === "localhost"[\s\S]*127\.0\.0\.1/, "PWA export opens should escape same-origin app scope via alternate loopback host");
180
180
  assert.match(app, /for \(const warning of response\.warnings/, "frontend should surface remote bash trust warnings");
@@ -189,7 +189,7 @@ assert.match(server, /async function cycleTabModel\(tab, direction = "forward"\)
189
189
  assert.match(server, /url\.pathname === "\/api\/model-cycle" && req\.method === "POST"/, "server should expose model-cycle endpoint for shortcuts");
190
190
  assert.match(server, /case "\/api\/thinking-cycle":[\s\S]*?type: "cycle_thinking_level"/, "server should expose thinking-cycle endpoint for shortcuts");
191
191
  assert.match(server, /async function setThinkingLevelForTab\(tab, level, \{ allowPending = true \} = \{\}\)[\s\S]*?stateIsBusyForSettings\(stateResult\.data\)[\s\S]*?tab\.pendingThinkingLevel = level/, "server should queue side-panel thinking changes while a tab is running");
192
- assert.match(server, /function eventForTabClients\(tab, event\)[\s\S]*?responseWithPendingThinking\(tab, event\)[\s\S]*?tabId: tab\.id/, "server should decorate SSE state responses with pending thinking before broadcasting to clients");
192
+ assert.match(server, /function eventForTabClients\(tab, event\)[\s\S]*?const decorated = event\?\.type === "queue_update"[\s\S]*?responseWithPendingThinking\(tab, decorated\)[\s\S]*?tabId: tab\.id/, "server should apply pending-thinking decoration to the source-decorated SSE event and retain its tab id");
193
193
  assert.match(server, /tab\.pendingThinkingLevel = level;\n\s+broadcastPendingThinkingState\(tab, stateResult\.data\)/, "server should broadcast queued thinking state after assigning the pending level");
194
194
  assert.match(server, /const pendingThinkingResponse = await applyPendingThinkingBeforePrompt\(tab\)/, "server should apply queued thinking level before the next prompt");
195
195
  assert.match(app, /pendingThinkingLevel[\s\S]*?next prompt/, "frontend should show queued thinking changes as applying on the next prompt");
@@ -0,0 +1,75 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+
4
+ const [app, html, css, stateModule, botClient, server, serviceWorker, packageJson] = await Promise.all([
5
+ readFile(new URL("../public/app.js", import.meta.url), "utf8"),
6
+ readFile(new URL("../public/index.html", import.meta.url), "utf8"),
7
+ readFile(new URL("../public/styles.css", import.meta.url), "utf8"),
8
+ readFile(new URL("../public/issue-wizard-state.mjs", import.meta.url), "utf8"),
9
+ readFile(new URL("../public/issue-bot-client.mjs", import.meta.url), "utf8"),
10
+ readFile(new URL("../bin/pi-webui.mjs", import.meta.url), "utf8"),
11
+ readFile(new URL("../public/service-worker.js", import.meta.url), "utf8"),
12
+ readFile(new URL("../package.json", import.meta.url), "utf8"),
13
+ ]);
14
+
15
+ assert.match(app, /from "\.\/issue-wizard-state\.mjs"/, "the browser controller must import the approved pure wizard module");
16
+ assert.match(app, /from "\.\/issue-bot-client\.mjs"/, "network behavior must live in a separate issue-bot client module");
17
+ assert.match(app, /createIssueWizardCatalog\(OPTIONAL_FEATURES\.map\(\(feature\) => feature\.label\)\)/, "optional feature labels must come from the existing catalog");
18
+ assert.match(app, /page\.hidden = step !== issueWizardState\.step/, "the controller must expose exactly one wizard page at a time");
19
+ assert.match(app, /action === "select-template"[\s\S]*item\.fields\.map\(\(field\) => field\.label\)/, "template choices must preview structured fields");
20
+ assert.match(app, /function focusIssueWizardChoice\([\s\S]*target\?\.focus/, "rerendered selections must preserve keyboard focus");
21
+ assert.match(app, /button\.setAttribute\("aria-pressed", selected \? "true" : "false"\)/, "selection buttons must keep toggle semantics");
22
+ assert.doesNotMatch(app, /setAttribute\("role", "radio(?:group)?"\)/, "the wizard must not advertise unimplemented radio keyboard semantics");
23
+ assert.match(app, /structuredIssueWizardState\(\)[\s\S]*?categoryId:[\s\S]*?fields:/, "the adapter must submit structured wizard state");
24
+ assert.match(app, /buildIssuePayload\(issueWizardState, issueWizardCatalog\)[\s\S]*?never send title\/body to the gateway/, "the canonical builder remains the review authority without becoming a network payload");
25
+ assert.doesNotMatch(app.match(/function structuredIssueWizardState\(\)[\s\S]*?\n}/)?.[0] || "", /\btitle\b|\bbody\b/, "structured submission must not add editable title/body fields");
26
+ assert.match(app, /new AbortController\(\)/, "submission and refresh calls must support cancellation");
27
+ assert.match(app, /issueWizardDialog\.addEventListener\("close", \(\) => clearIssueBotSubmission\(\{ abort: true \}\)\)/, "closing the dialog must abort the active request");
28
+ assert.match(app, /issueBotRequestActive/, "the wizard must prevent duplicate in-flight submissions");
29
+ assert.match(app, /issueBotSubmissionHandle\.refresh/, "bounded polling must retain an in-memory manual refresh path");
30
+ assert.match(app, /reasonCode === "sensitive_content"/, "sensitive outcomes must route to private guidance without reading submitted prose");
31
+ assert.doesNotMatch(app, /submitIssueToGithubBot/, "the old unavailable state-module seam must not handle browser network submission");
32
+ assert.match(stateModule, /export async function submitIssueToGithubBot[\s\S]*?status: "unavailable"/, "the pure state-module fallback remains offline by default");
33
+ assert.match(stateModule, /description: "[^"]+"[\s\S]*?fields:/, "template definitions must retain preview descriptions");
34
+ assert.match(app, /issueClipboardText\(payload\)/, "copy must include the complete title and body payload");
35
+ assert.doesNotMatch(stateModule.match(/export async function submitIssueToGithubBot[\s\S]*?\n}/)?.[0] || "", /\bfetch\s*\(/, "the pure fallback must perform no network I/O");
36
+
37
+ assert.match(botClient, /ISSUE_BOT_DEFAULT_RUNTIME_CONFIG[\s\S]*?enabled: false/, "public runtime configuration must be disabled by default");
38
+ assert.match(botClient, /schemaVersion: 1, idempotencyKey, turnstileToken, issue/, "admission must use the exact versioned structured envelope");
39
+ assert.match(botClient, /credentials: "omit"/, "browser requests must not send ambient credentials");
40
+ assert.match(botClient, /authorization: `Bearer \$\{statusToken\}`/, "only the status capability may authorize polling");
41
+ assert.match(botClient, /maxPollDurationMs = DEFAULT_MAX_POLL_DURATION_MS/, "polling must have a documented bounded duration");
42
+ assert.match(botClient, /Math\.min\(MAX_POLL_AFTER_MS, Math\.max\(delayMs \* 2/, "polling must apply bounded exponential backoff");
43
+ assert.match(botClient, /STATUS_TOKEN/, "the capability token must be shape-validated before use");
44
+ assert.doesNotMatch(botClient, /localStorage|sessionStorage|document\.cookie/, "the client must not persist drafts or capability tokens");
45
+ assert.doesNotMatch(botClient, /OPENAI_API_KEY|GITHUB_APP_|PRIVATE_KEY/, "the browser client must not contain service credentials");
46
+
47
+ assert.match(html, /__PI_WEBUI_ISSUE_BOT_CONFIG__[\s\S]*?enabled: false/, "the page must expose only disabled-by-default public runtime configuration");
48
+ assert.match(html, /id="openIssueButton"[\s\S]*?aria-controls="issueWizardDialog"/, "the persistent Control Deck action must target the dialog");
49
+ assert.match(html, /<footer class="side-panel-footer">[\s\S]*?id="openIssueButton"/, "the action must stay outside scrolling Control Deck content");
50
+ assert.match(html, /<dialog id="issueWizardDialog"[\s\S]*?aria-labelledby="issueWizardTitle"[\s\S]*?aria-describedby="issueWizardDescription"/, "the dialog must have an accessible name and description");
51
+ for (const step of [1, 2, 3, 4, 5]) assert.match(html, new RegExp(`data-issue-wizard-page="${step}"`), `step ${step} markup must exist`);
52
+ assert.match(html, /id="issueWizardStatus"[^>]*role="status"[^>]*aria-live="polite"/, "wizard progress must retain its accessible live region");
53
+ assert.doesNotMatch(html, /id="issueWizardProgress"[^>]*aria-live/, "the progress label must not duplicate live announcements");
54
+ assert.match(html, /id="issueWizardSubmissionStatus"[^>]*role="status"[^>]*aria-live="polite"/, "submission state needs a persistent dialog live region");
55
+ assert.match(html, /id="issueWizardSubmissionLink"[^>]*target="_blank"[^>]*rel="noopener noreferrer"/, "confirmed issue links must prevent opener access");
56
+ assert.match(html, /id="issueWizardSecurityLink"[^>]*target="_blank"[^>]*rel="noopener noreferrer"/, "private security guidance links must be safe");
57
+ assert.match(html, /id="issueWizardBotButton"[^>]*disabled[^>]*>Send</, "the bot control must be disabled until safe runtime configuration enables it");
58
+ assert.match(html, /id="issueWizardCopyButton"[^>]*>Copy complete issue</, "copy fallback must remain available");
59
+
60
+ assert.match(css, /\.side-panel-footer\s*\{[\s\S]*justify-content:\s*flex-end/, "the Control Deck action must anchor at the footer's right edge");
61
+ assert.match(css, /\.issue-wizard-dialog\s*\{[\s\S]*max-height:/, "the dialog must bound its height");
62
+ assert.match(css, /\.issue-wizard-pages\s*\{[\s\S]*overflow:\s*auto/, "wizard page content must remain scrollable");
63
+ assert.match(css, /\.issue-wizard-choice-description,[\s\S]*\.issue-wizard-choice-preview/, "template descriptions and field previews need dedicated styling");
64
+ assert.match(css, /\.issue-wizard-submission-status\s*\{/, "persistent bot status needs dedicated styling");
65
+ assert.match(css, /@media \(max-width: 720px\)[\s\S]*\.issue-wizard-choice-grid/, "wizard choices must adapt for mobile");
66
+
67
+ assert.match(server, /"issue-wizard-state\.mjs"/, "the static allowlist must continue serving the pure wizard module");
68
+ assert.match(server, /"issue-bot-client\.mjs"/, "the static allowlist must serve the browser client module");
69
+ assert.match(serviceWorker, /"\/issue-wizard-state\.mjs"/, "the PWA shell must keep caching the pure wizard module");
70
+ assert.match(serviceWorker, /"\/issue-bot-client\.mjs"/, "the PWA shell must cache the browser client module");
71
+ assert.match(serviceWorker, /pi-webui-pwa-v48/, "the PWA cache name must change with the new static module");
72
+ assert.match(packageJson, /node --check public\/issue-wizard-state\.mjs/, "the package check must keep syntax-checking the pure wizard module");
73
+ assert.match(packageJson, /node --check public\/issue-bot-client\.mjs/, "the package check must syntax-check the browser client module");
74
+
75
+ console.log("open-issue-wizard-static.test.mjs passed");
@@ -32,12 +32,14 @@ vm.runInContext(`
32
32
  const promptRoutingTabs = new Set();
33
33
  let tabSeenCompletionSerials = new Map();
34
34
  function scheduleTabsRender() {}
35
+ function suppressPendingAgentDoneNotificationsForTab() {}
35
36
 
36
37
  ${functionSource("normalizeTabActivity")}
37
38
  ${functionSource("tabActivityStateChanged")}
38
39
  ${functionSource("setTabActivity")}
39
40
  ${functionSource("activityForTab")}
40
41
  ${functionSource("markTabWorkingLocally")}
42
+ ${functionSource("markTabIdleLocally")}
41
43
  ${functionSource("markTabDoneLocally")}
42
44
 
43
45
  globalThis.activityApi = {
@@ -86,6 +88,9 @@ assert.equal(api.markDone(), false, "idle state reconciliation must not synthesi
86
88
  assert.equal(api.current().completionSerial, 2, "routing must not create a false completion serial");
87
89
 
88
90
  api.finishRouting();
91
+ assert.equal(api.markDone(), true, "idle reconciliation should leave a submitted-but-never-started prompt idle");
92
+ assert.equal(api.current().status, "idle");
93
+ assert.equal(api.current().completionSerial, 2, "a prompt that never emitted agent_start must not synthesize completion");
89
94
  assert.equal(api.ingest(staleDone).status, "done", "authoritative completion remains accepted after routing finishes");
90
95
 
91
96
  const sendSource = functionSource("sendPrompt");
@@ -0,0 +1,101 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import vm from "node:vm";
6
+
7
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
8
+ const [html, css, app] = await Promise.all([
9
+ readFile(join(root, "public", "index.html"), "utf8"),
10
+ readFile(join(root, "public", "styles.css"), "utf8"),
11
+ readFile(join(root, "public", "app.js"), "utf8"),
12
+ ]);
13
+
14
+ assert.match(
15
+ html,
16
+ /id="followUpQueueTrigger"[^>]*aria-controls="followUpQueueOverlay"[^>]*aria-expanded="false"[\s\S]*id="followUpQueueTriggerCount"[\s\S]*id="followUpQueueOverlay"[^>]*aria-label="Queued follow-ups"[\s\S]*id="followUpQueueRows"[\s\S]*id="followUpQueueStatus"[^>]*role="status"[^>]*aria-live="polite"/,
17
+ "the composer should expose a count trigger and accessible non-modal follow-up queue overlay",
18
+ );
19
+ assert.match(css, /\.follow-up-queue-overlay \{[\s\S]*position:\s*absolute;[\s\S]*bottom:\s*calc\(100% \+ 0\.42rem\);[\s\S]*max-height:\s*min\(32rem, calc\(var\(--visual-viewport-height, 100dvh\) - 2rem\)\)/, "the queue overlay should float upward without changing composer layout and be bounded by the visual viewport");
20
+ assert.match(css, /body\.mobile-keyboard-open \.follow-up-queue-trigger:not\(\[hidden\]\) \{ display: inline-flex; \}/, "the queue trigger should remain usable while the mobile keyboard is open");
21
+ assert.match(css, /@media \(prefers-reduced-motion: reduce\) \{[\s\S]*\.follow-up-queue-overlay,[\s\S]*\.follow-up-queue-row \{ transition: none; \}/, "the queue overlay should suppress motion for reduced-motion users");
22
+
23
+ const normalizeStart = app.indexOf("function normalizeQueuedMessages(event) {");
24
+ const normalizeEnd = app.indexOf("\nfunction queuedSnapshotForTab", normalizeStart);
25
+ assert.ok(normalizeStart >= 0 && normalizeEnd > normalizeStart, "queue normalization should remain independently testable");
26
+ const normalizeSource = app.slice(normalizeStart, normalizeEnd);
27
+ const compactionSnapshot = JSON.parse(vm.runInNewContext(`${normalizeSource}\nJSON.stringify(normalizeQueuedMessages({ source: "webui-compaction", revision: 7, draining: true, steering: ["steer"], followUp: ["first", "second"] }))`));
28
+ assert.deepEqual(compactionSnapshot, {
29
+ source: "webui-compaction",
30
+ revision: 7,
31
+ draining: true,
32
+ steering: ["steer"],
33
+ followUp: ["first", "second"],
34
+ }, "frontend queue normalization should retain compaction source, revision, draining state, and both queue arrays");
35
+
36
+ const mutationBodyStart = app.indexOf("function queueMutationBody(snapshot, operation) {");
37
+ const mutationBodyEnd = app.indexOf("\nfunction applyAuthoritativeQueuedSnapshot", mutationBodyStart);
38
+ assert.ok(mutationBodyStart >= 0 && mutationBodyEnd > mutationBodyStart, "queue mutation request construction should remain independently testable");
39
+ const mutationBodySource = app.slice(mutationBodyStart, mutationBodyEnd);
40
+ const compactionMutation = JSON.parse(vm.runInNewContext(`${mutationBodySource}\nJSON.stringify(queueMutationBody({ source: "webui-compaction", revision: 3, steering: ["steer"], followUp: ["one", "two"] }, { type: "move", from: 1, to: 0, expectedText: "two" }))`));
41
+ assert.deepEqual(compactionMutation, {
42
+ source: "webui-compaction",
43
+ kind: "followUp",
44
+ revision: 3,
45
+ expected: { steering: ["steer"], followUp: ["one", "two"] },
46
+ operation: { type: "move", from: 1, to: 0, expectedText: "two" },
47
+ }, "compaction moves should use the B1 source-aware, revisioned full-snapshot mutation contract");
48
+ const runtimeMutation = JSON.parse(vm.runInNewContext(`${mutationBodySource}\nJSON.stringify(queueMutationBody({ source: "pi-runtime", steering: [], followUp: ["old"] }, { type: "edit", index: 0, expectedText: "old", text: "new" }))`));
49
+ assert.equal(Object.hasOwn(runtimeMutation, "revision"), false, "Pi-runtime mutations must omit the compaction-only revision field");
50
+ assert.deepEqual(runtimeMutation.expected, { steering: [], followUp: ["old"] }, "Pi-runtime mutations should send the complete B1 expected snapshot");
51
+
52
+ const draftHelperStart = app.indexOf("function preservedFocusedFollowUpQueueDraft(draft, followUps) {");
53
+ const draftHelperEnd = app.indexOf("\nfunction focusedFollowUpQueueDraft", draftHelperStart);
54
+ assert.ok(draftHelperStart >= 0 && draftHelperEnd > draftHelperStart, "queue draft preservation should remain independently testable");
55
+ const draftHelperSource = app.slice(draftHelperStart, draftHelperEnd);
56
+ const draftDecisions = JSON.parse(vm.runInNewContext(`${draftHelperSource}
57
+ JSON.stringify({
58
+ preserve: preservedFocusedFollowUpQueueDraft({ index: 1, authoritativeText: "second", value: "unsaved second", selectionStart: 3, selectionEnd: 10 }, ["first", "second"]),
59
+ targetChanged: preservedFocusedFollowUpQueueDraft({ index: 1, authoritativeText: "second", value: "unsaved second", selectionStart: 3, selectionEnd: 10 }, ["first", "server replacement"]),
60
+ indexChanged: preservedFocusedFollowUpQueueDraft({ index: 1, authoritativeText: "second", value: "unsaved second" }, ["second", "first"]),
61
+ clean: preservedFocusedFollowUpQueueDraft({ index: 1, authoritativeText: "second", value: "second" }, ["first", "second"]),
62
+ })`));
63
+ assert.deepEqual(draftDecisions.preserve, { index: 1, value: "unsaved second", selectionStart: 3, selectionEnd: 10 }, "an SSE queue update should preserve the focused dirty draft only when its same authoritative item remains at its index");
64
+ assert.equal(draftDecisions.targetChanged, null, "an authoritative replacement at the focused index must discard the old draft instead of carrying it across a conflict");
65
+ assert.equal(draftDecisions.indexChanged, null, "a reordered target must not retain a dirty draft at the old index");
66
+ assert.equal(draftDecisions.clean, null, "unchanged focused text should not be treated as a dirty draft");
67
+
68
+ const renderTargetStart = app.indexOf("function queuedSnapshotTargetsCurrentTab(tabContext, currentTabId = activeTabId, currentTabs = tabs) {");
69
+ const renderTargetEnd = app.indexOf("\nfunction setFollowUpQueueOpen", renderTargetStart);
70
+ assert.ok(renderTargetStart >= 0 && renderTargetEnd > renderTargetStart, "late queue response targeting should remain independently testable");
71
+ const renderTargetSource = app.slice(renderTargetStart, renderTargetEnd);
72
+ const renderTargets = JSON.parse(vm.runInNewContext(`${renderTargetSource}
73
+ JSON.stringify({
74
+ returnedToOrigin: queuedSnapshotTargetsCurrentTab({ tabId: "A", generation: 4, sessionFile: "/sessions/a.jsonl", startedAt: "start-a" }, "A", [{ id: "A", sessionFile: "/sessions/a.jsonl", startedAt: "start-a" }]),
75
+ anotherTabActive: queuedSnapshotTargetsCurrentTab({ tabId: "A", generation: 4, sessionFile: "/sessions/a.jsonl", startedAt: "start-a" }, "B", [{ id: "A", sessionFile: "/sessions/a.jsonl", startedAt: "start-a" }, { id: "B" }]),
76
+ originClosed: queuedSnapshotTargetsCurrentTab({ tabId: "A", generation: 4 }, "A", []),
77
+ sessionReplaced: queuedSnapshotTargetsCurrentTab({ tabId: "A", generation: 4, sessionFile: "/sessions/a.jsonl", startedAt: "start-a" }, "A", [{ id: "A", sessionFile: "/sessions/replacement.jsonl", startedAt: "start-replacement" }]),
78
+ })`));
79
+ assert.equal(renderTargets.returnedToOrigin, true, "a late A mutation response should render after A→B→A when A is active again");
80
+ assert.equal(renderTargets.anotherTabActive, false, "a late A mutation response must not repaint active tab B");
81
+ assert.equal(renderTargets.originClosed, false, "a late response must not render after its originating tab closes");
82
+ assert.equal(renderTargets.sessionReplaced, false, "a late response must not render after the authoritative tab session changes");
83
+
84
+ assert.match(app, /async function mutateQueuedFollowUp\([\s\S]*const tabContext = queueTabContext\(tabId\)[\s\S]*api\("\/api\/queue\/mutate", \{ method: "POST", body: queueMutationBody\(snapshot, operation\), tabId \}\)[\s\S]*if \(result\.queue\) applyAuthoritativeQueuedSnapshot\(tabContext, result\.queue\)[\s\S]*error\?\.statusCode === 409[\s\S]*refreshed the authoritative queue/, "queue mutations should use the single B1 endpoint and refresh the authoritative snapshot after conflicts");
85
+ assert.match(app, /function applyAuthoritativeQueuedSnapshot\([\s\S]*latestQueuedMessagesByTab\.set\(tabContext\.tabId, snapshot\)[\s\S]*if \(queuedSnapshotTargetsCurrentTab\(tabContext\)\) renderQueue/, "late mutation responses should render only their active originating tab while caching every authoritative result");
86
+ assert.match(app, /function renderQueue\(event\)[\s\S]*latestQueuedMessagesByTab\.set\(tabId, snapshot\)[\s\S]*if \(tabId && tabId !== activeTabId\) return;/, "deferred queue rendering must cache but never repaint an unrelated active tab");
87
+ assert.match(app, /const followUpQueueMutationsInFlightByTab = new Set\(\)[\s\S]*function syncFollowUpQueueMutationControls\([\s\S]*textarea\.disabled = locked \|\| draining[\s\S]*control\.disabled = locked \|\| draining[\s\S]*function setFollowUpQueueMutationInFlight/, "in-flight and draining states should lock editable queue controls per tab");
88
+
89
+ assert.match(app, /const textarea = make\("textarea", "follow-up-queue-textarea"\)[\s\S]*textarea\.dataset\.followUpQueueAuthoritativeText = item[\s\S]*textarea\.addEventListener\("blur", \(\) => \{[\s\S]*followUpQueueSuppressBlurFor[\s\S]*saveQueuedFollowUpText\(index, item, textarea\.value\)[\s\S]*\(event\.ctrlKey \|\| event\.metaKey\)[\s\S]*event\.key === "Enter"[\s\S]*event\.key !== "Escape"[\s\S]*textarea\.value = item/, "queue rows should be editable by default and avoid blur-saving the focused draft during an authoritative rerender");
90
+ assert.match(app, /row\.draggable = false;[\s\S]*dragHandle\.draggable = !unavailable;[\s\S]*row\.addEventListener\("dragstart", \(event\) => \{[\s\S]*event\.target\?\.closest\?\.\("\.follow-up-queue-drag-handle"\) !== dragHandle[\s\S]*application\/x-pi-webui-follow-up[\s\S]*row\.addEventListener\("dragover"[\s\S]*event\.stopPropagation\(\)[\s\S]*row\.addEventListener\("drop"[\s\S]*type: "move", from: drag\.index, to: index/, "native drag/drop should begin only from its visible handle, persist the final-index permutation, and isolate row drag events");
91
+ assert.match(app, /function handleComposerDragOver\(event\) \{\n\s*if \(event\.target\?\.closest\?\.\("#followUpQueueOverlay"\) \|\| !isFileDrag\(event\)\) return;[\s\S]*function handleComposerDrop\(event\) \{\n\s*if \(event\.target\?\.closest\?\.\("#followUpQueueOverlay"\) \|\| !isFileDrag\(event\)\) return;/, "composer attachment drops should ignore queue-row drag events");
92
+ assert.match(app, /Moved queued follow-up \$\{operation\.from \+ 1\} to position \$\{operation\.to \+ 1\}[\s\S]*Move queued follow-up \$\{index \+ 1\} up[\s\S]*Move queued follow-up \$\{index \+ 1\} down/, "move controls should provide labelled keyboard/touch parity and live reorder announcements");
93
+ assert.match(app, /setFollowUpQueueOpen\(false, \{ restoreFocus: true \}\)/, "outside close and Escape should request queue-focus restoration");
94
+ assert.match(app, /function setFollowUpQueueOpen\([\s\S]*followUpQueueRestoreFocus[\s\S]*requestAnimationFrame\(\(\) => focusTarget\?\.focus\(\{ preventScroll: true \}\)\)/, "queue close should restore focus to the saved trigger context");
95
+ assert.match(app, /function setFollowUpQueueOpen[\s\S]*setComposerActionsOpen\(false\)[\s\S]*setPublishMenuOpen\(false\)[\s\S]*setNativeCommandMenuOpen\(false\)[\s\S]*setAppRunnerMenuOpen\(false\)[\s\S]*setOptionsMenuOpen\(false\)[\s\S]*setConversationVoiceMenuOpen\(false\)[\s\S]*setBusyPromptBehaviorMenuOpen\(false\)[\s\S]*setNewTabMenuOpen\(false\)/, "opening the queue should close competing dropdown surfaces");
96
+ assert.match(app, /function renderFollowUpQueueOverlay\(\) \{\n\s*if \(deferUiRenderDuringPointerActivation\("follow-up-queue", renderFollowUpQueueOverlay\)\) return;/, "queue rendering should defer during pointer activation");
97
+ assert.match(app, /function switchTab\(tabId\)[\s\S]*setFollowUpQueueOpen\(false\)[\s\S]*setFollowUpQueueStatus\(""\)/, "switching tabs should close queue UI and clear its tab-local status before the new context renders");
98
+ assert.match(app, /renderQueueGroup\("Follow-up", followUp, "follow-up", \{ removable: snapshot\.source === "pi-runtime", tabId \}\)/, "Control Deck removal must stay gated to Pi-runtime snapshots");
99
+ assert.doesNotMatch(app, /nextQueuedFollowUpPrompt|sticky-user-follow-up-prompt|Next follow-up prompt:/, "the sticky last/current prompt control must no longer expose queued follow-up preview content");
100
+
101
+ console.log("queue edit/reorder static tests passed");