@firstpick/pi-package-webui 0.7.8 → 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.
@@ -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");
@@ -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");
@@ -1490,7 +1512,7 @@ assert.match(app, /function renderBtwComposerForm\(\)[\s\S]*?form\.requestSubmit
1490
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");
1491
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");
1492
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");
1493
- 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");
1494
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");
1495
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");
1496
1518
  assert.match(app, /async function runNativeCommandMenu\(command\)[\s\S]*?await handleNativeSlashSelectorCommand\(command\)/, "skills/tools command menu should open native selector dialogs directly");
@@ -1575,10 +1597,6 @@ assert.match(app, /function updateStickyUserPromptButton\(/, "last user prompt h
1575
1597
  assert.match(app, /function jumpToStickyUserPrompt\(/, "last user prompt header should jump to its source message");
1576
1598
  assert.match(app, /data-user-prompt/, "user prompt messages should be marked for sticky prompt navigation");
1577
1599
  assert.match(app, /function resetChatOutput\(\)[\s\S]*?stickyUserPromptButton/, "chat rerenders should preserve the sticky user prompt control inside the transcript scroller");
1578
- assert.match(app, /function nextQueuedFollowUpPrompt\(tabId = activeTabId\)/, "sticky prompt header should derive the next queued follow-up prompt for display");
1579
- 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");
1580
- assert.match(app, /function renderQueue\(event\)[\s\S]*updateStickyUserPromptButton\(\)/, "queue updates should refresh the sticky last-user-prompt header");
1581
- 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");
1582
1600
  assert.match(app, /LAST_USER_PROMPT_STORAGE_KEY/, "last user prompt should be cached so compaction cannot remove the sticky prompt preview");
1583
1601
  assert.match(app, /function syncLastUserPromptFromMessages\(messages = latestMessages\)/, "message refresh should preserve the latest user prompt across compacted transcripts");
1584
1602
  assert.match(app, /dataset\.compacted/, "sticky prompt should expose a compacted fallback state when its source message was summarized away");
@@ -1623,7 +1641,7 @@ assert.match(app, /case "webui_connected":[\s\S]*?featureCategoryByTab\.delete\(
1623
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");
1624
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");
1625
1643
  assert.match(app, /window\.addEventListener\("pageshow", \(\) => scheduleForegroundReconcile\("page show", 0\)\)/, "BFCache or PWA page resume should force a server snapshot refresh");
1626
- 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");
1627
1645
  assert.match(app, /function tabIndicator\(tab\)/, "frontend should derive idle, working, blocked, and work-done tab indicator states");
1628
1646
  assert.match(app, /pendingBlockerCount > 0[\s\S]*?state: "blocked"/, "frontend should show blocked tabs when extension UI blockers are pending");
1629
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");
@@ -1741,10 +1759,10 @@ assert.match(server, /delete process\.env\.PI_WEBUI_RESTORE_TABS/, "server shoul
1741
1759
  assert.match(server, /if \(sessionFile && !options\.noSession\) piArgs\.push\("--session", sessionFile\)/, "restored tabs should resume previous session files");
1742
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");
1743
1761
  assert.match(server, /const closedRestorableTabs = \[\]/, "server should track recently closed tabs separately from restart restore descriptors");
1744
- 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");
1745
1763
  assert.match(server, /async function restorableTabsForRestart\(\)[\s\S]*?return mergeRestorableTabDescriptors\(liveDescriptors\)/, "server restart should restore only currently open tabs");
1746
1764
  assert.doesNotMatch(server, /return mergeRestorableTabDescriptors\(liveDescriptors,\s*closedRestorableTabs\)/, "server restart should not restore closed tabs");
1747
- 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");
1748
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");
1749
1767
  assert.match(server, /function rememberTabState\(tab, state\)/, "server should cache last-known tab state for restart-safe session restoration");
1750
1768
  assert.match(server, /sessionFile: tabRestorableSessionFile\(tab\)/, "tab metadata should expose cached session files for health/status restore descriptors");
@@ -1861,7 +1879,7 @@ assert.match(server, /writeFile\(tmpFile, body\.content[\s\S]*?rename\(tmpFile,
1861
1879
  assert.match(server, /url\.pathname === "\/api\/themes" && req\.method === "GET"/, "server should expose GET /api/themes");
1862
1880
  assert.match(server, /readBundledThemes\(\)/, "server should read bundled theme JSON files for the browser");
1863
1881
  assert.match(server, /"apple-touch-icon\.png", "icon-192\.png"/, "server should serve the conventional apple touch icon path");
1864
- 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");
1865
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");
1866
1884
  assert.match(server, /\["\.webmanifest", "application\/manifest\+json; charset=utf-8"\]/, "server should serve manifest with the correct MIME type");
1867
1885
  assert.match(server, /\["\.png", "image\/png"\]/, "server should serve PWA PNG icons with the correct MIME type");
@@ -1908,7 +1926,7 @@ for (const [name, range] of Object.entries(companionDependencies)) {
1908
1926
  assert.equal(pkg.optionalDependencies?.[name], range, `webui package should optionally depend on ${name}`);
1909
1927
  assert.equal(pkg.dependencies?.[name], undefined, `webui package should not require optional companion ${name}`);
1910
1928
  assert.equal(lock.packages?.[""]?.optionalDependencies?.[name], range, `package-lock root should optionally depend on ${name}`);
1911
- 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}`);
1912
1930
  assert.ok(lock.packages?.[`node_modules/${name}`], `package-lock should include resolved optional companion ${name}`);
1913
1931
  }
1914
1932
  assert.equal(pkg.bundledDependencies, undefined, "webui optional companion packages should not be bundled into the tarball");
@@ -1974,7 +1992,7 @@ assert.match(app, /streamRawText = "";\n streamThinkingRawText = "";\n resetSt
1974
1992
 
1975
1993
  // --- Performance: delta transcript fetch (P1-1) ---
1976
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");
1977
- 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");
1978
1996
  assert.match(app, /if \(!nextMessages\) \{[\s\S]*?api\("\/api\/messages", \{ tabId: tabContext\.tabId \}\)/, "delta failures must fall back to a full transcript fetch");
1979
1997
  assert.match(server, /function applyMessagesSinceParam\(response, url\)/, "server should slice get_messages results for \\?since= requests");
1980
1998
  assert.match(app, /const messageStaticSignatureCache = new WeakMap\(\);/, "static message signatures should be cached by object identity");
@@ -1988,6 +2006,6 @@ assert.match(app, /\(event\.ctrlKey \|\| event\.metaKey\) && !event\.altKey && !
1988
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");
1989
2007
  assert.match(app, /autoFollowChat = false;\n lastChatProgrammaticScrollAt = performance\.now\(\);/, "search navigation must not fight chat auto-follow");
1990
2008
  assert.match(css, /\.message\.search-current \{/, "current search match should have a highlight style");
1991
- 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");
1992
2010
 
1993
2011
  console.log("mobile static checks passed");
@@ -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,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");
@@ -0,0 +1,143 @@
1
+ import assert from "node:assert/strict";
2
+ import { mutatePiRuntimeFollowUpQueue } from "../lib/queue-mutation.mjs";
3
+
4
+ function queuedMessage(text, extra = {}) {
5
+ return {
6
+ role: "user",
7
+ timestamp: 1234,
8
+ metadata: { origin: "fixture" },
9
+ content: [{ type: "text", text }, { type: "image", mimeType: "image/png", data: "iVBORw0KGgo=" }],
10
+ ...extra,
11
+ };
12
+ }
13
+
14
+ function fixture({ steering = ["steer"], followUp = ["first", "second", "third"], steeringMessages, followUpMessages } = {}) {
15
+ let events = 0;
16
+ const session = {
17
+ _steeringMessages: [...steering],
18
+ _followUpMessages: [...followUp],
19
+ agent: {
20
+ steeringQueue: { messages: steeringMessages || steering.map((text) => queuedMessage(text)) },
21
+ followUpQueue: { messages: followUpMessages || followUp.map((text) => queuedMessage(text)) },
22
+ },
23
+ _emitQueueUpdate() { events += 1; },
24
+ };
25
+ return { session, eventCount: () => events };
26
+ }
27
+
28
+ function expected(session) {
29
+ return { steering: [...session._steeringMessages], followUp: [...session._followUpMessages] };
30
+ }
31
+
32
+ function editRequest(session, index, text, expectedText = session._followUpMessages[index]) {
33
+ return {
34
+ source: "pi-runtime",
35
+ kind: "followUp",
36
+ expected: expected(session),
37
+ operation: { type: "edit", index, expectedText, text },
38
+ };
39
+ }
40
+
41
+ function moveRequest(session, from, to, expectedText = session._followUpMessages[from]) {
42
+ return {
43
+ source: "pi-runtime",
44
+ kind: "followUp",
45
+ expected: expected(session),
46
+ operation: { type: "move", from, to, expectedText },
47
+ };
48
+ }
49
+
50
+ {
51
+ const { session, eventCount } = fixture();
52
+ const beforeMessage = session.agent.followUpQueue.messages[1];
53
+ const beforeImage = beforeMessage.content[1];
54
+ const result = mutatePiRuntimeFollowUpQueue(session, editRequest(session, 1, "edited"));
55
+ assert.deepEqual(result, {
56
+ mutated: true,
57
+ source: "pi-runtime",
58
+ queue: { source: "pi-runtime", steering: ["steer"], followUp: ["first", "edited", "third"] },
59
+ });
60
+ assert.deepEqual(session._followUpMessages, ["first", "edited", "third"]);
61
+ assert.equal(session.agent.followUpQueue.messages[1].role, "user", "edit preserves message role");
62
+ assert.equal(session.agent.followUpQueue.messages[1].timestamp, 1234, "edit preserves message timestamp");
63
+ assert.deepEqual(session.agent.followUpQueue.messages[1].metadata, { origin: "fixture" }, "edit preserves metadata");
64
+ assert.strictEqual(session.agent.followUpQueue.messages[1].content[1], beforeImage, "edit preserves image content exactly");
65
+ assert.equal(beforeMessage.content[0].text, "second", "edit does not mutate the original message object");
66
+ assert.equal(eventCount(), 1, "successful edit emits exactly one queue update");
67
+ }
68
+
69
+ {
70
+ const { session, eventCount } = fixture();
71
+ const firstMessage = session.agent.followUpQueue.messages[0];
72
+ const result = mutatePiRuntimeFollowUpQueue(session, moveRequest(session, 0, 2));
73
+ assert.equal(result.mutated, true);
74
+ assert.deepEqual(session._followUpMessages, ["second", "third", "first"], "move uses the final post-removal index");
75
+ assert.strictEqual(session.agent.followUpQueue.messages[2], firstMessage, "move keeps the message object paired with its tracking string");
76
+ assert.equal(eventCount(), 1, "successful move emits exactly one queue update");
77
+ }
78
+
79
+ {
80
+ const { session, eventCount } = fixture({ followUp: ["same", "same"] });
81
+ const result = mutatePiRuntimeFollowUpQueue(session, editRequest(session, 1, "changed"));
82
+ assert.equal(result.mutated, true, "duplicate text is safe when the requested index and complete snapshot match");
83
+ assert.deepEqual(session._followUpMessages, ["same", "changed"]);
84
+ assert.equal(eventCount(), 1);
85
+ }
86
+
87
+ for (const staleMutation of [
88
+ (session) => { session._followUpMessages.push("new"); session.agent.followUpQueue.messages.push(queuedMessage("new")); },
89
+ (session) => { session._followUpMessages.shift(); session.agent.followUpQueue.messages.shift(); },
90
+ (session) => { session._followUpMessages.reverse(); session.agent.followUpQueue.messages.reverse(); },
91
+ ]) {
92
+ const { session, eventCount } = fixture();
93
+ const request = editRequest(session, 1, "edited");
94
+ staleMutation(session);
95
+ const before = structuredClone({ tracking: session._followUpMessages, messages: session.agent.followUpQueue.messages });
96
+ const result = mutatePiRuntimeFollowUpQueue(session, request);
97
+ assert.equal(result.mutated, false);
98
+ assert.equal(result.reason, "queue-changed", "a stale full snapshot is rejected");
99
+ assert.deepEqual({ tracking: session._followUpMessages, messages: session.agent.followUpQueue.messages }, before, "stale mutations leave paired arrays untouched");
100
+ assert.equal(eventCount(), 0, "stale mutations emit no queue update");
101
+ }
102
+
103
+ {
104
+ const { session, eventCount } = fixture();
105
+ session.agent.followUpQueue.messages[1] = queuedMessage("different");
106
+ const before = structuredClone({ tracking: session._followUpMessages, messages: session.agent.followUpQueue.messages });
107
+ const result = mutatePiRuntimeFollowUpQueue(session, editRequest(session, 1, "edited"));
108
+ assert.equal(result.reason, "queue-desynchronized");
109
+ assert.deepEqual({ tracking: session._followUpMessages, messages: session.agent.followUpQueue.messages }, before);
110
+ assert.equal(eventCount(), 0);
111
+ }
112
+
113
+ for (const requestFor of [
114
+ (session) => ({ ...editRequest(session, 1, ""), operation: { ...editRequest(session, 1, "").operation, text: " " } }),
115
+ (session) => editRequest(session, 99, "edited"),
116
+ (session) => moveRequest(session, 0, 0),
117
+ (session) => moveRequest(session, 0, 99),
118
+ (session) => ({ ...editRequest(session, 1, "edited"), source: "webui-compaction" }),
119
+ (session) => ({ ...editRequest(session, 1, "edited"), kind: "steering" }),
120
+ ]) {
121
+ const { session, eventCount } = fixture();
122
+ const before = structuredClone({ tracking: session._followUpMessages, messages: session.agent.followUpQueue.messages });
123
+ const result = mutatePiRuntimeFollowUpQueue(session, requestFor(session));
124
+ assert.equal(result.mutated, false);
125
+ assert.equal(result.reason, "invalid-request");
126
+ assert.deepEqual({ tracking: session._followUpMessages, messages: session.agent.followUpQueue.messages }, before);
127
+ assert.equal(eventCount(), 0, "invalid mutations emit no queue update");
128
+ }
129
+
130
+ {
131
+ const { session, eventCount } = fixture();
132
+ session.agent.followUpQueue.messages[0].content.push({ type: "text", text: "unexpected" });
133
+ const result = mutatePiRuntimeFollowUpQueue(session, editRequest(session, 0, "edited"));
134
+ assert.equal(result.reason, "queue-desynchronized", "unknown message text layouts fail closed");
135
+ assert.equal(eventCount(), 0);
136
+ }
137
+
138
+ {
139
+ const result = mutatePiRuntimeFollowUpQueue({}, { source: "pi-runtime", kind: "followUp", expected: { steering: [], followUp: [] }, operation: { type: "edit", index: 0, expectedText: "x", text: "y" } });
140
+ assert.deepEqual(result, { mutated: false, reason: "queue-unsupported", queue: { source: "pi-runtime", steering: [], followUp: [] } }, "missing private Pi structures fail closed");
141
+ }
142
+
143
+ console.log("queue-mutation-contract.test.mjs passed");
@@ -0,0 +1,42 @@
1
+ import assert from "node:assert/strict";
2
+ import { resolveScopedModelsFromPatterns } from "../lib/scoped-models.mjs";
3
+
4
+ const models = [
5
+ { provider: "anthropic", id: "claude-fable-5", name: "Claude Fable 5" },
6
+ { provider: "openrouter", id: "anthropic/claude-fable-5", name: "Claude Fable 5" },
7
+ { provider: "openrouter", id: "anthropic/claude-fable-5:batch", name: "Claude Fable 5 Batch" },
8
+ { provider: "openrouter", id: "google/gemini-3.6-flash", name: "Gemini 3.6 Flash" },
9
+ { provider: "openrouter", id: "google/gemini-3.6-flash:batch", name: "Gemini 3.6 Flash Batch" },
10
+ { provider: "openrouter", id: "openrouter/auto", name: "Auto" },
11
+ { provider: "openrouter", id: "openrouter/auto-beta", name: "Auto Beta" },
12
+ ];
13
+
14
+ const exactPatterns = [
15
+ "anthropic/claude-fable-5",
16
+ "openrouter/google/gemini-3.6-flash",
17
+ "openrouter/openrouter/auto",
18
+ ];
19
+ const exact = await resolveScopedModelsFromPatterns(exactPatterns, models);
20
+ assert.deepEqual(
21
+ exact.map((model) => `${model.provider}/${model.id}`),
22
+ exactPatterns,
23
+ "exact Pi scope entries must not expand to cross-provider, batch, or similarly named models",
24
+ );
25
+
26
+ const withThinking = await resolveScopedModelsFromPatterns(["anthropic/claude-fable-5:high"], models);
27
+ assert.deepEqual(withThinking.map((model) => `${model.provider}/${model.id}`), ["anthropic/claude-fable-5"]);
28
+
29
+ const exactColonId = await resolveScopedModelsFromPatterns(["openrouter/anthropic/claude-fable-5:batch"], models);
30
+ assert.deepEqual(exactColonId.map((model) => `${model.provider}/${model.id}`), ["openrouter/anthropic/claude-fable-5:batch"]);
31
+
32
+ const glob = await resolveScopedModelsFromPatterns(["openrouter/google/gemini-3.6-flash*"], models);
33
+ assert.deepEqual(
34
+ glob.map((model) => `${model.provider}/${model.id}`),
35
+ ["openrouter/google/gemini-3.6-flash", "openrouter/google/gemini-3.6-flash:batch"],
36
+ "explicit Pi glob patterns must retain their intentional expansion behavior",
37
+ );
38
+
39
+ assert.deepEqual(await resolveScopedModelsFromPatterns([null, ""], models), []);
40
+ assert.deepEqual(await resolveScopedModelsFromPatterns(exactPatterns, null), []);
41
+
42
+ console.log("scoped-models.test.mjs passed");