@firstpick/pi-package-webui 0.8.2 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +9 -3
  2. package/bin/pi-webui.mjs +97 -12
  3. package/lib/git-workflow-preferences.mjs +246 -19
  4. package/lib/thinking-stream-recovery.mjs +156 -0
  5. package/lib/ui-layout-settings.mjs +254 -0
  6. package/package.json +5 -3
  7. package/public/app.js +1618 -41
  8. package/public/index.html +35 -14
  9. package/public/service-worker.js +1 -1
  10. package/public/styles.css +324 -1
  11. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  12. package/tests/browser/composer-action-grid-reorder.spec.mjs +303 -0
  13. package/tests/browser/feature-decision-output-popup.spec.mjs +156 -0
  14. package/tests/browser/interaction-continuity.spec.mjs +29 -0
  15. package/tests/browser/persistent-ui-layout.spec.mjs +744 -0
  16. package/tests/codex-fast-mode-static.test.mjs +2 -2
  17. package/tests/composer-action-grid-reorder-static.test.mjs +63 -0
  18. package/tests/fast-mode-client-static.test.mjs +2 -2
  19. package/tests/feature-decision-output-popup-static.test.mjs +172 -0
  20. package/tests/fixtures/fake-pi.mjs +51 -1
  21. package/tests/git-workflow-preferences.test.mjs +4 -2
  22. package/tests/http-endpoints-harness.test.mjs +88 -1
  23. package/tests/interaction-state-stability-static.test.mjs +3 -0
  24. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  25. package/tests/mobile-foundation-static.test.mjs +3 -3
  26. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  27. package/tests/mobile-static.test.mjs +32 -15
  28. package/tests/open-issue-wizard-static.test.mjs +1 -1
  29. package/tests/persistent-ui-layout-static.test.mjs +267 -0
  30. package/tests/questionnaire-dialog.test.mjs +511 -0
  31. package/tests/queue-edit-reorder-static.test.mjs +1 -0
  32. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  33. package/tests/side-panel-resize-static.test.mjs +1 -0
  34. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  35. package/tests/subagent-launch-slots.test.mjs +1 -1
  36. package/tests/thinking-stream-recovery.test.mjs +88 -0
  37. package/tests/ui-layout-settings.test.mjs +92 -0
  38. package/tests/webui-settings-locking.test.mjs +159 -0
@@ -175,7 +175,7 @@ assert.match(html, /id="codexUsageBox"/, "side panel should expose Codex subscri
175
175
  assert.match(html, /data-side-panel-section="codex-usage"/, "Codex usage should live in a collapsible side-panel section");
176
176
  assert.match(html, /data-side-panel-section="subagents"[\s\S]*class="side-panel-section-label">Subagents<\/span>[\s\S]*id="subagentCountBadge"[\s\S]*class="subagents-help"[\s\S]*<code>subagent<\/code>[\s\S]*<code>subagent_gate<\/code>[\s\S]*bounded retries or a success quorum[\s\S]*id="subagentsBox"/, "side panel should explain ordinary delegation and retry-gate workflows with a live count");
177
177
  assert.match(html, /id="subagentOpenModeSelect"[\s\S]*<option value="overlay">Overlay<\/option>[\s\S]*<option value="tab">Tab \/ terminal<\/option>[\s\S]*id="subagentOpenModeStatus"/, "Subagents should offer a browser-persisted overlay or terminal-tab opening choice");
178
- assert.match(html, /class="subagents-status-row"[\s\S]*id="subagentsStatus"[\s\S]*id="subagentsClearFinishedButton"[^>]*disabled[^>]*>Clear finished<\/button>/, "Subagents should expose a clear-finished control beside its live status");
178
+ assert.match(html, /class="subagents-status-row"[\s\S]*id="subagentsAutoClearButton"[^>]*aria-pressed="false"[^>]*>Auto-Clear<\/button>[\s\S]*id="subagentsStatus"[\s\S]*id="subagentsClearFinishedButton"[^>]*disabled[^>]*>Clear finished<\/button>/, "Subagents should expose selectable auto-clear and manual clear controls beside its live status");
179
179
  const subagentCancelDialogHtml = html.match(/<dialog id="subagentCancelDialog"[\s\S]*?<\/dialog>/)?.[0] || "";
180
180
  assert.match(subagentCancelDialogHtml, /id="subagentCancelDialogTitle">Cancel subagent<[\s\S]*id="subagentCancelDialogSubtitle"/, "subagent cancellation should use a titled dialog with dynamic target context");
181
181
  assert.match(subagentCancelDialogHtml, /<select id="subagentCancelReason">[\s\S]*<option value="" selected>No reason<\/option>[\s\S]*Wrong model\/provider\/thinking effort[\s\S]*Wrong agent or task[\s\S]*Taking too long[\s\S]*Wrong approach or direction[\s\S]*Output no longer needed[\s\S]*Started by mistake[\s\S]*<option value="Other">Other<\/option>/, "subagent cancellation should offer every approved optional reason");
@@ -285,7 +285,7 @@ assert.ok(html.includes('id="commandSuggest"') && html.indexOf('id="commandSugge
285
285
  assert.match(html, /id="busyPromptBehaviorTag"[\s\S]*class="composer-busy-mode-tag"[\s\S]*aria-controls="busyPromptBehaviorMenu"/, "composer should expose a clickable busy prompt behavior tag on the input frame");
286
286
  assert.doesNotMatch(html, /Busy send:/i, "busy prompt behavior tag should show only the current mode label");
287
287
  assert.match(html, /id="sessionSkillTags" class="composer-skill-tags"[\s\S]*hidden/, "composer should expose a hidden-until-used skill tag strip beside the busy mode tag");
288
- assert.match(html, /id="featureCategoryTag" class="composer-feature-category-tag"[^>]*aria-live="polite"[^>]*aria-atomic="true"[^>]*hidden/, "composer should expose a hidden-until-used accessible feature category tag");
288
+ assert.match(html, /<button id="featureCategoryTag" class="composer-feature-category-tag"[^>]*type="button"[^>]*aria-haspopup="dialog"[^>]*aria-controls="featureDecisionDialog"[^>]*aria-live="polite"[^>]*aria-atomic="true"[^>]*disabled hidden><\/button>/, "composer should expose a hidden-until-used accessible feature category button");
289
289
  assert.match(html, /id="skillEditorDialog"[\s\S]*id="skillEditorText"[\s\S]*id="skillEditorSaveButton"/, "skill tags should have an in-Web UI SKILL.md editing dialog");
290
290
  assert.match(html, /id="busyPromptBehaviorMenu"[\s\S]*data-busy-prompt-behavior="followUp"[\s\S]*data-busy-prompt-behavior="steer"/, "busy prompt behavior dropdown should expose follow-up and steer choices");
291
291
  assert.match(app, /const LONG_INPUT_ATTACHMENT_LINE_THRESHOLD = 20/, "long composer text should use a 20-line threshold before becoming an attachment");
@@ -340,7 +340,7 @@ assert.match(workflowModeButtonHtml, /data-tooltip="Workflow Mode:/, "Workflow M
340
340
  assert.doesNotMatch(workflowModeButtonHtml, /\stitle=/, "Workflow Mode should not also expose a browser-native tooltip");
341
341
  assert.match(html, /id="workflowModeChip" class="composer-workflow-mode-chip"[\s\S]*hidden>Workflow: on<\/button>/, "composer should expose a hidden-until-active Workflow Mode chip");
342
342
  assert.match(html, /id="conversationModeEndButton" class="composer-conversation-end-button"[\s\S]*hidden>End conversation<\/button>/, "composer should expose a persistent End conversation button while active");
343
- assert.match(html, /id="conversationVoiceMenu" class="composer-publish-menu composer-conversation-voice-menu" hidden>[\s\S]*id="conversationVoiceButton"[\s\S]*id="conversationVoiceMenuPanel" class="composer-publish-menu-panel[\s\S]*id="conversationModeEndButton"/, "composer should expose the conversation voice menu (publish-menu pattern) next to the End conversation button");
343
+ assert.match(html, /id="conversationVoiceMenu" class="composer-publish-menu composer-conversation-voice-menu"[^>]*hidden>[\s\S]*id="conversationVoiceButton"[\s\S]*id="conversationVoiceMenuPanel" class="composer-publish-menu-panel[\s\S]*id="conversationModeEndButton"/, "composer should expose the conversation voice menu (publish-menu pattern) next to the End conversation button");
344
344
  assert.match(app, /conversationVoiceMenuPanel: \$\("#conversationVoiceMenuPanel"\)/, "frontend should register the conversation voice menu panel");
345
345
  assert.match(app, /\/api\/conversation-voices/, "frontend should load the Piper voice list from the server");
346
346
  assert.match(app, /\/api\/conversation-voice"/, "frontend should switch voices through the conversation-voice endpoint");
@@ -453,12 +453,15 @@ assert.match(html, /id="followUpQueueTrigger"[^>]*aria-controls="followUpQueueOv
453
453
  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");
454
454
  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");
455
455
  assert.match(css, /\.message\.extension,[\s\S]*?\.message\.native/, "extension and native command output should have visible transcript styling");
456
- 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");
456
+ assert.match(app, /const FEATURE_DECISION_OUTPUT_STATUS_KEY = "feature-decision-output";\s+const FEATURE_CATEGORY_STATUS_KEY = "feature-category";[\s\S]*const featureCategoryByTab = new Map\(\);\s+const featureDecisionOutputByTab = new Map\(\)/, "feature category and exact decision output should use separate transport keys and per-tab maps");
457
457
  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");
458
- assert.match(app, /function renderFeatureCategoryTag\(tabId = activeTabId\) \{[\s\S]*featureCategoryByTab\.get\(tabId\)[\s\S]*tag\.hidden = !category[\s\S]*tag\.textContent = category/, "feature category rendering should be active-tab scoped and hidden when absent");
459
- assert.match(app, /function handleFeatureCategoryStatus\(statusText, tabId = activeTabId\) \{[\s\S]*featureCategoryByTab\.set\(tabId, category\)[\s\S]*featureCategoryByTab\.delete\(tabId\)[\s\S]*tabId === activeTabId/, "feature category status should update and clear only the addressed terminal tab");
460
- assert.match(app, /case "setStatus": \{[\s\S]*statusKey === FEATURE_CATEGORY_STATUS_KEY[\s\S]*handleFeatureCategoryStatus\(request\.statusText, request\.tabId \|\| activeTabId\);[\s\S]*return;[\s\S]*statusEntries\.set\(statusKey, request\.statusText\)/, "feature category status should be consumed before generic footer status storage");
461
- assert.match(app, /function setActiveTabId\(tabId, \{ remember = false \} = \{\}\) \{[\s\S]*renderFeatureCategoryTag\(nextTabId\)[\s\S]*function syncTabMetadata\(nextTabs = \[\]\) \{[\s\S]*featureCategoryByTab\.delete\(tabId\)/, "tab activation and cleanup should render only the active category and remove closed-tab state");
458
+ assert.match(app, /function normalizeFeatureDecisionKind\(value\) \{\s+return value === "feature_lightweight" \|\| value === "feature_complex" \? value : "";/, "feature decision kind normalization should accept only the two approved exact labels");
459
+ assert.match(app, /function parseFeatureDecisionPayload\(value\) \{[\s\S]*value\.length > FEATURE_DECISION_PAYLOAD_MAX_CHARS\) return null;[\s\S]*const legacyKind = normalizeFeatureDecisionKind\(value\);[\s\S]*JSON\.parse\(value\)[\s\S]*return kind && reason \? \{ kind, reason \} : null;/, "the decision payload parser should bound size, accept the legacy exact label, and otherwise fail closed on the structured payload");
460
+ assert.match(app, /function formatFeatureDecisionText\(decision\) \{[\s\S]*`Decision: \$\{featureDecisionKindLabel\(decision\.kind\)\} \(\$\{decision\.kind\}\)\\nReason: \$\{reason\}`/, "the popup should render a readable decision and reason instead of only the machine label");
461
+ assert.match(app, /function renderFeatureCategoryTag\(tabId = activeTabId\) \{[\s\S]*featureCategoryByTab\.get\(tabId\)[\s\S]*featureDecisionOutputForTab\(tabId\)[\s\S]*tag\.hidden = !category;\s+tag\.disabled = !output;\s+tag\.textContent = category/, "feature category rendering should preserve category text while enabling the active-tab popup only for matching exact output");
462
+ assert.match(app, /function handleFeatureCategoryStatus\(statusText, tabId = activeTabId\) \{[\s\S]*featureCategoryByTab\.set\(tabId, category\)[\s\S]*clearFeatureDecisionStateForTab\(tabId\)[\s\S]*tabId === activeTabId/, "feature category status should update only the addressed tab and defensively clear exact output when category clears");
463
+ assert.match(app, /case "setStatus": \{[\s\S]*statusKey === FEATURE_DECISION_OUTPUT_STATUS_KEY[\s\S]*handleFeatureDecisionOutputStatus\(request\.statusText, request\.tabId \|\| activeTabId\);[\s\S]*statusKey === FEATURE_CATEGORY_STATUS_KEY[\s\S]*handleFeatureCategoryStatus\(request\.statusText, request\.tabId \|\| activeTabId\);[\s\S]*statusEntries\.set\(statusKey, request\.statusText\)/, "feature output and category statuses should be consumed before generic footer status storage");
464
+ assert.match(app, /function setActiveTabId\(tabId, \{ remember = false \} = \{\}\) \{[\s\S]*closeFeatureDecisionDialog\(\{ restoreFocus: false \}\)[\s\S]*renderFeatureCategoryTag\(nextTabId\)[\s\S]*function syncTabMetadata\(nextTabs = \[\]\) \{[\s\S]*clearFeatureDecisionStateForTab\(tabId\)/, "tab activation and cleanup should close stale popup content, render only active-tab state, and remove closed-tab state");
462
465
  assert.match(app, /function remoteWebuiQrSvg\(qrLines = \[\]\)[\s\S]*?viewBox[\s\S]*?shape-rendering[\s\S]*?crispEdges/, "remote WebUI QR popup should render terminal QR output as square SVG modules");
463
466
  assert.match(app, /function showRemoteWebuiQrLoadingPopup\(message = "Opening Remote WebUI QR…"\)[\s\S]*?remote-qr-loading[\s\S]*?showModal\(\)/, "remote WebUI QR popup should show a loading state while QR generation is pending");
464
467
  assert.match(app, /function handleRemoteWebuiStatus\(statusText\)[\s\S]*?opening remote webui[\s\S]*?refreshing remote qr[\s\S]*?enabling remote pin auth[\s\S]*?showRemoteWebuiQrLoadingPopup/, "remote WebUI status updates should open the QR loading popup before widget lines arrive");
@@ -832,7 +835,7 @@ assert.match(app, /function setOptionsMenuOpen\(open\)[\s\S]*scheduleMobileDropd
832
835
  assert.match(app, /function focusPromptInput\(\{ defer = false \} = \{\}\)/, "frontend should focus the prompt composer programmatically after tab/app startup");
833
836
  assert.match(app, /async function switchTab\(tabId\)[\s\S]*?restoreActiveDraft\(\);\n\s+focusPromptInput\(\{ defer: true \}\);/, "switching to a newly opened tab should focus the prompt input immediately");
834
837
  assert.match(app, /async function initializeTabs\(\)[\s\S]*?restoreActiveDraft\(\);[\s\S]*if \(!loadedTabs\.length\)[\s\S]*focusPromptInput\(\{ defer: true \}\);/, "starting the Web UI should prompt for cwd when needed and focus active tabs");
835
- assert.match(app, /resizePromptInput\(\);\nrestoreSidePanelWidthPreference\(\);\nrestoreFileViewerWidthPreference\(\);\nfocusPromptInput\(\{ defer: true \}\);\nrestoreStoredSkillUsage\(\);\nrestoreBusyPromptBehaviorSetting\(\);\nupdateComposerModeButtons\(\);/, "startup should restore resizable panel preferences, request prompt focus, and restore skill tags before waiting for tab state refreshes");
838
+ assert.match(app, /resizePromptInput\(\);\nrestoreDurableUiLayoutPendingJournal\(\);\nrestoreSidePanelWidthPreference\(\);\nrestoreFileViewerWidthPreference\(\);\nfocusPromptInput\(\{ defer: true \}\);\nrestoreStoredSkillUsage\(\);\nrestoreBusyPromptBehaviorSetting\(\);\nupdateComposerModeButtons\(\);/, "startup should restore resizable panel preferences, request prompt focus, and restore skill tags before waiting for tab state refreshes");
836
839
  assert.match(app, /elements\.promptInput\.addEventListener\("focus", \(\) => \{\n\s+syncMobileChatToBottomForInput\(\);/, "focusing mobile input should scroll output to bottom");
837
840
  assert.match(app, /navigator\.serviceWorker\.register\("\/service-worker\.js"\)/, "PWA service worker should be registered by the app");
838
841
  assert.match(app, /function serverStartCommandText\(\)[\s\S]*return `pi-webui\$\{currentPortArg\(\)\}`/, "PWA/offline shell should build a pathless pi-webui recovery command");
@@ -888,8 +891,10 @@ assert.match(app, /const node = make\("details", "widget todo-widget"\)/, "todo-
888
891
  assert.match(app, /Optional feature detection intentionally checks loaded Pi capabilities/, "optional Web UI features should be detected through loaded capabilities, not package folders");
889
892
  assert.match(app, /function resetOptionalFeatureAvailability\(\)/, "optional feature state should reset across active-tab and reload boundaries");
890
893
  assert.match(app, /function renderOptionalFeaturePanel\(\)/, "side panel should render optional feature installed/enabled state");
891
- assert.match(app, /const OPTIONAL_FEATURE_SECTIONS = \[[\s\S]*label: "Composer & commands"[\s\S]*label: "Workflows & releases"[\s\S]*label: "Safety & access"[\s\S]*label: "UI widgets & native parity"[\s\S]*label: "Conversation"/, "optional features should be grouped into five type subsections");
894
+ assert.match(app, /const OPTIONAL_FEATURE_SECTIONS = \[[\s\S]*label: "Composer & commands"[\s\S]*label: "Workflows & releases"[\s\S]*label: "Safety & access"[\s\S]*label: "UI widgets & native parity"[\s\S]*featureIds: \[[^\]]*"questionnaire"[\s\S]*label: "Conversation"/, "optional features should be grouped into five type subsections with questionnaires under native parity");
892
895
  assert.match(app, /function renderOptionalFeatureSection\(section, features\)[\s\S]*optional-feature-section[\s\S]*optional-feature-section-title[\s\S]*optional-feature-section-list/, "optional feature panel should render subsection headers and lists");
896
+ assert.match(app, /async function refreshQuestionnaireFeatureAvailability[\s\S]*\/api\/tools\?scope=session[\s\S]*tool\?\.name === "questionnaire"/, "questionnaire availability should be detected from the active Pi tab's loaded tool capability");
897
+ assert.match(app, /detected && feature\.manageWith === "tools"[\s\S]*action\.textContent = "Tools…"[\s\S]*openNativeToolsSelector/, "loaded questionnaire access should be managed through the native Tools selector instead of a cosmetic WebUI disable toggle");
893
898
  assert.match(app, /function setSidePanelSectionCollapsed\(record, collapsed/, "side panel sections should have explicit collapse/expand behavior");
894
899
  assert.match(
895
900
  app,
@@ -948,9 +953,12 @@ assert.match(app, /subagentTerminalCancelButton[\s\S]*openSubagentCancelDialog\(
948
953
  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");
949
954
  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");
950
955
  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");
951
- assert.match(app, /function finishedSubagentRunSelections\(data = latestSubagents\)[\s\S]*ungatedSubagentRuns\(tab\)[\s\S]*run\.status !== "running" && run\.source !== "workflow"[\s\S]*async function clearFinishedSubagentRuns\(\)[\s\S]*for \(const selection of selections\)[\s\S]*api\("\/api\/subagents\/dismiss", \{[\s\S]*body: \{ tab: selection\.tabId, runId: selection\.runId \}[\s\S]*subagentsClearFinishedButton\.disabled = subagentsLoading \|\| subagentsClearingFinished \|\| finishedRuns\.length === 0/, "clear-finished should dismiss visible terminal ordinary runs while preserving retry-gated, active, and workflow runs");
956
+ assert.match(app, /function finishedSubagentRunSelections\(data = latestSubagents\)[\s\S]*ungatedSubagentRuns\(tab\)[\s\S]*run\.status !== "running" && run\.source !== "workflow"[\s\S]*async function clearFinishedSubagentRuns\(\{ automatic = false \} = \{\}\)[\s\S]*for \(const selection of selections\)[\s\S]*api\("\/api\/subagents\/dismiss", \{[\s\S]*body: \{ tab: selection\.tabId, runId: selection\.runId \}[\s\S]*subagentsClearFinishedButton\.disabled = subagentsLoading \|\| subagentsClearingFinished \|\| finishedRuns\.length === 0/, "clear-finished should dismiss visible terminal ordinary runs while preserving retry-gated, active, and workflow runs");
957
+ assert.match(app, /subagentsAutoClearButton\?\.addEventListener\("click", \(\) => \{[\s\S]*setSubagentAutoClearEnabled\(!subagentAutoClearEnabled, \{ announce: true \}\)/, "the Auto-Clear button should toggle the selected browser preference");
958
+ assert.match(app, /SUBAGENT_AUTO_CLEAR_STORAGE_KEY = "pi-webui-subagent-auto-clear"[\s\S]*function readStoredSubagentAutoClearEnabled\(\)[\s\S]*localStorage\.getItem\(SUBAGENT_AUTO_CLEAR_STORAGE_KEY\) === "1"[\s\S]*function setSubagentAutoClearEnabled[\s\S]*clearFinishedSubagentRuns\(\{ automatic: true \}\)[\s\S]*restoreSubagentAutoClearSetting\(\)/, "Auto-Clear should persist per browser and immediately clear already-finished ordinary runs when selected");
959
+ assert.match(app, /async function refreshSubagents\(\)[\s\S]*refreshed = true[\s\S]*refreshed && subagentAutoClearEnabled && finishedSubagentRunSelections\(\)\.length[\s\S]*await clearFinishedSubagentRuns\(\{ automatic: true \}\)/, "successful overview refreshes should await guarded auto-clear when terminal runs appear");
952
960
  assert.match(app, /subagentsClearFinishedButton\?\.addEventListener\("click", \(\) => \{[\s\S]*clearFinishedSubagentRuns\(\)/, "the clear-finished button should invoke the guarded bulk dismissal action");
953
- assert.match(css, /\.subagents-status-row \{[\s\S]*display: flex;[\s\S]*\.subagents-clear-finished-button \{[\s\S]*min-height: 2rem;/, "the clear-finished control should share a compact responsive status row");
961
+ assert.match(css, /\.subagents-status-row \{[\s\S]*display: flex;[\s\S]*\.subagents-auto-clear-button,[\s\S]*\.subagents-clear-finished-button \{[\s\S]*min-height: 2rem;[\s\S]*\.subagents-auto-clear-button\[aria-pressed="true"\]/, "the clear controls should share a compact row with a visible Auto-Clear selected state");
954
962
  const clearFinishedSourceStart = app.indexOf("function finishedSubagentRunSelections(");
955
963
  const clearFinishedSourceEnd = app.indexOf("\nfunction subagentOverlayTranscriptMessages(", clearFinishedSourceStart);
956
964
  assert.ok(clearFinishedSourceStart >= 0 && clearFinishedSourceEnd > clearFinishedSourceStart, "clear-finished helpers should remain independently testable");
@@ -988,6 +996,9 @@ assert.deepEqual(JSON.parse(JSON.stringify(clearFinishedCalls)), [
988
996
  assert.equal(clearFinishedRefreshes, 1, "clear-finished should refresh the overview once after all dismissals");
989
997
  assert.equal(clearFinishedContext.subagentsClearingFinished, false, "clear-finished should always release its in-flight guard");
990
998
  assert.deepEqual(clearFinishedEvents, [{ message: "cleared 3 finished subagent runs", level: "info" }]);
999
+ clearFinishedContext.latestSubagents = { tabs: [{ tabId: "tab-c", runs: [{ id: "done-c", status: "done", source: "async" }] }] };
1000
+ await clearFinishedContext.runClearFinishedSubagentRuns({ automatic: true });
1001
+ assert.deepEqual(clearFinishedEvents.at(-1), { message: "auto-cleared 1 finished subagent run", level: "info" }, "automatic clearing should identify its action without changing terminal-run selection semantics");
991
1002
  assert.match(app, /function materializeRetainedSubagentTerminalViews\(\)[\s\S]*restoreKey = `\$\{tab\.tabId\}\\u0000\$\{tab\.sessionFile[\s\S]*ungatedSubagentRuns\(tab\)[\s\S]*run\?\.status === "running"[\s\S]*ensureSubagentTerminalView/, "terminal mode should materialize only ungated restored retained agent views once per parent session identity without touching overlay mode");
992
1003
  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");
993
1004
  assert.match(app, /function subagentLaunchSlotThinkingForModel\(model\)[\s\S]*modelThinkingLevels/, "launch-slot thinking choices should come from the selected model metadata");
@@ -1327,6 +1338,7 @@ assert.match(app, /id: "safetyGuard"[\s\S]*?@firstpick\/pi-extension-safety-guar
1327
1338
  assert.match(app, /id: "tuiSkillsCommand"[\s\S]*?@firstpick\/pi-extension-setup-skills/, "optional features should include the TUI skills command companion");
1328
1339
  assert.match(app, /id: "tuiToolsCommand"[\s\S]*?@firstpick\/pi-extension-tools/, "optional features should include the TUI tools command companion");
1329
1340
  assert.match(app, /id: "remoteWebui"[\s\S]*?@firstpick\/pi-package-remote-webui/, "optional features should include the Remote WebUI companion");
1341
+ assert.match(app, /id: "questionnaire"[\s\S]*?@firstpick\/pi-package-questionnaire[\s\S]*?capabilityLabel: "questionnaire tool in \/tools"[\s\S]*?manageWith: "tools"/, "optional features should include the native questionnaire package and delegate access control to Tools");
1330
1342
  assert.match(app, /id: "naturalConversation"[\s\S]*?@firstpick\/pi-package-natural-conversation[\s\S]*?capabilityLabel: "\/talk, \/voice, or \/conversation"/, "optional features should include the capability-detected Natural Conversation shell");
1331
1343
  assert.match(app, /NATURAL_CONVERSATION_COMMAND_NAMES = \["talk", "voice", "conversation"\]/, "frontend should detect Natural Conversation only from RPC-visible command aliases");
1332
1344
  assert.match(app, /const conversationModeByTab = new Map\(\)/, "frontend should track Natural Conversation state per terminal tab");
@@ -1390,7 +1402,7 @@ const workflowTokenRenderSource = appFunctionSource("appendWorkflowScriptTokens"
1390
1402
  const workflowPreviewSource = appFunctionSource("renderWorkflowScriptPreview", "showNextDialog");
1391
1403
  const workflowDialogSource = appFunctionSource("showNextDialog", "handleInactiveTabEvent");
1392
1404
  assert.match(workflowPreviewRequestSource, /request\?\.method === "editor"[\s\S]*title\.startsWith\("Raw workflow script"\)[\s\S]*inspection only;\\s\*edits are ignored/, "workflow inspector specialization should require the editor method, raw-script title, and inspection-only wording");
1393
- assert.match(workflowDialogSource, /else if \(isWorkflowScriptPreview\) \{\s*renderWorkflowScriptPreview\(request\);\s*\} else if \(request\.method === "editor"\) \{\s*const textarea = make\("textarea", "dialog-editor"\);[\s\S]*textarea\.value = request\.prefill \|\| ""/, "workflow previews should specialize before the unchanged generic editor textarea fallback");
1405
+ assert.match(workflowDialogSource, /else if \(isWorkflowScriptPreview\) \{\s*renderWorkflowScriptPreview\(request, respondToDialog\);\s*\} else if \(request\.method === "editor"\) \{\s*const textarea = make\("textarea", "dialog-editor"\);[\s\S]*textarea\.value = request\.prefill \|\| ""/, "workflow previews should specialize before the unchanged generic editor textarea fallback and share its one-shot responder");
1394
1406
  assert.doesNotMatch(workflowPreviewSource, /\btextarea\b/, "workflow previews should not create an editable textarea");
1395
1407
  assert.match(workflowTokenRenderSource, /document\.createTextNode\(line\.slice\(start, match\.index\)\)[\s\S]*make\("span", `workflow-script-token/, "workflow syntax tokens should be built from DOM text nodes and spans");
1396
1408
  assert.doesNotMatch(workflowTokenRenderSource, /innerHTML|insertAdjacentHTML/, "workflow syntax token rendering should not inject source through HTML APIs");
@@ -1640,7 +1652,8 @@ assert.doesNotMatch(app, /runIndicatorTimestamp/, "active agent indicator should
1640
1652
  assert.match(app, /runIndicatorBubble = make\("article", "message runIndicator run-indicator-message streaming"\)/, "active agent indicator should use a dedicated streaming transcript card");
1641
1653
  assert.match(app, /function standaloneLiveTranscriptBubbles\(\)[\s\S]*?streamThinkingBubble[\s\S]*?streamToolCallBubble[\s\S]*?streamBubble[\s\S]*?compactThinkingBubble[\s\S]*?compactTextBubble/, "transcript reconciliation should identify standalone live-tail bubbles that must stay mounted");
1642
1654
  assert.match(app, /function resetChatOutput\(\)[\s\S]*?liveBubbles = standaloneLiveTranscriptBubbles\(\)[\s\S]*?preservedNodes[\s\S]*?child === runIndicatorBubble \|\| liveBubbles\.has\(child\)[\s\S]*?transcriptRenderer\.replaceChildren\(elements\.chat, \.\.\.preservedNodes\)/, "transcript resets should reconcile through the coordinator while preserving live output and the run indicator");
1643
- assert.match(app, /function appendChatMessageBubble\(bubble\)[\s\S]*?tailAnchor[\s\S]*?child === runIndicatorBubble \|\| liveBubbles\.has\(child\)[\s\S]*?insertBefore\(bubble, tailAnchor\)/, "reconciled history should insert before the stable live transcript tail");
1655
+ assert.match(app, /function appendChatMessageBubble\(bubble, \{ liveTail = false \} = \{\}\)[\s\S]*?child === runIndicatorBubble \|\| \(!liveTail && liveBubbles\.has\(child\)\)[\s\S]*?insertBefore\(bubble, tailAnchor\)/, "reconciled history should insert before the stable live transcript tail while new live output stays chronological");
1656
+ assert.match(app, /appendChatMessageBubble\(created\.bubble, \{ liveTail: streaming \|\| message\?\.live === true \}\)/, "streaming thinking, assistant text, and live tools should append after earlier live output");
1644
1657
  assert.match(app, /setChatScrollTopInstant\(Math\.min\(previousScrollTop, elements\.chat\.scrollHeight\)\)/, "paused-reader scroll restoration should bypass smooth scrolling to avoid a down-then-back animation");
1645
1658
  assert.match(app, /function ensureRunIndicatorBubble\(\)[\s\S]*?!runIndicatorBubble \|\| !runIndicatorText \|\| !runIndicatorMeta[\s\S]*?elements\.chat\.lastElementChild !== runIndicatorBubble/, "active agent indicator should reuse the existing bubble across transcript re-renders instead of recreating it");
1646
1659
  assert.match(app, /const headline = runIndicatorHeadline\(\);\n\s+if \(runIndicatorText\.textContent !== headline\) runIndicatorText\.textContent = headline;/, "active agent indicator should avoid redundant headline DOM writes that can flicker");
@@ -1882,7 +1895,7 @@ assert.match(app, /let activeTabGeneration = 0/, "frontend should version active
1882
1895
  assert.match(app, /function isCurrentTabContext\(context\)/, "frontend should identify stale active-tab refresh contexts");
1883
1896
  assert.match(app, /function connectEvents\(tabContext = activeTabContext\(\), \{ requestedMode = "auto", fallbackAttempted = false \} = \{\}\)[\s\S]*?eventSource !== source/, "frontend should ignore stale SSE messages from old active tabs");
1884
1897
  assert.match(app, /let foregroundReconcileTimer = null/, "frontend should debounce foreground resume reconciliation");
1885
- assert.match(app, /case "webui_connected":[\s\S]*?featureCategoryByTab\.delete\(connectedTabId\)[\s\S]*?renderFeatureCategoryTag\(connectedTabId\)[\s\S]*?scheduleForegroundReconcile\("event stream reconnect", 0\)/, "SSE reconnect should clear cached feature-category absence before replaying authoritative statuses and reconciling state");
1898
+ assert.match(app, /case "webui_connected":[\s\S]*?clearFeatureDecisionStateForTab\(connectedTabId, \{ render: true \}\)[\s\S]*?scheduleForegroundReconcile\("event stream reconnect", 0\)/, "SSE reconnect should close stale popup content and clear cached category/output before authoritative status replay");
1886
1899
  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");
1887
1900
  assert.match(app, /document\.addEventListener\("visibilitychange"[\s\S]*?scheduleForegroundReconcile\("visibility resume", 0\)/, "returning to a hidden mobile tab should force a server snapshot refresh");
1888
1901
  assert.match(app, /window\.addEventListener\("pageshow", \(\) => scheduleForegroundReconcile\("page show", 0\)\)/, "BFCache or PWA page resume should force a server snapshot refresh");
@@ -2102,6 +2115,7 @@ assert.match(server, /\["btwCommand", "@firstpick\/pi-extension-btw"\]/, "server
2102
2115
  assert.match(server, /\["safetyGuard", "@firstpick\/pi-extension-safety-guard"\]/, "server should allow installing the safety guard optional feature");
2103
2116
  assert.match(server, /\["tuiSkillsCommand", "@firstpick\/pi-extension-setup-skills"\]/, "server should allow installing the TUI skills optional feature");
2104
2117
  assert.match(server, /\["tuiToolsCommand", "@firstpick\/pi-extension-tools"\]/, "server should allow installing the TUI tools optional feature");
2118
+ assert.match(server, /\["questionnaire", "@firstpick\/pi-package-questionnaire"\]/, "server should allow explicitly installing the native questionnaire optional feature");
2105
2119
  assert.match(server, /\["naturalConversation", "@firstpick\/pi-package-natural-conversation"\]/, "server should know the standalone Natural Conversation package for status\/install guidance without making it WebUI-owned");
2106
2120
  assert.match(server, /const NATURAL_CONVERSATION_COMMAND_NAMES = \["talk", "voice", "conversation"\]/, "server should detect Natural Conversation from RPC-visible command aliases");
2107
2121
  assert.match(server, /function naturalConversationFeatureData\(tab[\s\S]*getCommandData\(tab, \{ annotateSkills: false \}\)[\s\S]*available[\s\S]*mode/, "server should expose a capability-based Natural Conversation feature snapshot");
@@ -2186,6 +2200,7 @@ for (const [name, range] of Object.entries(companionDependencies)) {
2186
2200
  }
2187
2201
  assert.equal(pkg.bundledDependencies, undefined, "webui optional companion packages should not be bundled into the tarball");
2188
2202
  assert.equal(pkg.optionalDependencies?.["@firstpick/pi-package-natural-conversation"], undefined, "webui package should not optionally depend on the standalone Natural Conversation package");
2203
+ assert.equal(pkg.optionalDependencies?.["@firstpick/pi-package-questionnaire"], undefined, "webui package should not install questionnaires by default before the user chooses the optional feature");
2189
2204
  assert.equal(pkg.optionalDependencies?.["@firstpick/pi-extension-aur-review"], undefined, "webui package should not reference the unpublished aur-review extension");
2190
2205
  assert.equal(lock.packages?.["node_modules/@firstpick/pi-extension-aur-review"], undefined, "package lock should not retain an unpublished aur-review tarball");
2191
2206
  assert.ok(!pkg.pi?.extensions?.some((entry) => String(entry).includes("pi-extension-aur-review")), "webui Pi manifest should not bundle the unpublished aur-review path");
@@ -2202,6 +2217,7 @@ for (const extensionPath of [
2202
2217
  "node_modules/@firstpick/pi-extension-stats/index.ts",
2203
2218
  "node_modules/@firstpick/pi-extension-todo-progress/index.ts",
2204
2219
  "node_modules/@firstpick/pi-extension-tools/index.ts",
2220
+ "node_modules/@firstpick/pi-package-questionnaire/index.ts",
2205
2221
  ]) {
2206
2222
  assert.ok(pkg.pi?.extensions?.includes(extensionPath), `webui Pi manifest should load ${extensionPath} when present`);
2207
2223
  }
@@ -2224,6 +2240,7 @@ assert.match(helper, /runner\?\.hasHandlers\?\.\("user_bash"\)[\s\S]*runner\.emi
2224
2240
  assert.match(helper, /eventResult\?\.operations[\s\S]*original\.call\(this, command, onChunk, nextOptions\)/, "Web UI RPC helper should pass extension-provided bash operations to Pi execution");
2225
2241
  assert.match(helper, /eventResult\?\.result[\s\S]*recordBashResult/, "Web UI RPC helper should preserve extension-provided bash results in session history");
2226
2242
  assert.ok(pkg.pi?.skills?.includes("node_modules/@firstpick/pi-extension-release-aur/skills"), "webui Pi manifest should load release-aur nested skills when present");
2243
+ assert.ok(pkg.pi?.skills?.includes("node_modules/@firstpick/pi-package-questionnaire/skills"), "webui Pi manifest should load questionnaire guidance only when the optional package is installed");
2227
2244
  assert.ok(!pkg.pi?.skills?.includes("../pi-extension-release-aur/skills"), "webui Pi manifest should avoid duplicate release-aur sibling skills");
2228
2245
  assert.ok(pkg.pi?.prompts?.includes("node_modules/@firstpick/pi-prompts-git-pr/prompts"), "webui Pi manifest should load guided-git nested prompts when present");
2229
2246
  assert.ok(!pkg.pi?.prompts?.includes("../pi-package-prompts-git-pr/prompts"), "webui Pi manifest should avoid duplicate guided-git sibling prompts");
@@ -69,7 +69,7 @@ assert.match(server, /"issue-bot-client\.mjs"/, "the static allowlist must serve
69
69
  assert.match(serviceWorker, /"\/issue-wizard-state\.mjs"/, "the PWA shell must keep caching the pure wizard module");
70
70
  assert.match(serviceWorker, /"\/issue-bot-client\.mjs"/, "the PWA shell must cache the browser client module");
71
71
  // Intent preserved: changing the public startup graph advances the PWA cache identity.
72
- assert.match(serviceWorker, /pi-webui-pwa-v62/, "the PWA cache name must change with browser wiring updates");
72
+ assert.match(serviceWorker, /pi-webui-pwa-v71/, "the PWA cache name must change with browser wiring updates");
73
73
  assert.match(packageJson, /node --check public\/issue-wizard-state\.mjs/, "the package check must keep syntax-checking the pure wizard module");
74
74
  assert.match(packageJson, /node --check public\/issue-bot-client\.mjs/, "the package check must syntax-check the browser client module");
75
75
 
@@ -0,0 +1,267 @@
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
+
6
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
7
+ const [html, app, serviceWorker] = await Promise.all([
8
+ readFile(join(root, "public", "index.html"), "utf8"),
9
+ readFile(join(root, "public", "app.js"), "utf8"),
10
+ readFile(join(root, "public", "service-worker.js"), "utf8"),
11
+ ]);
12
+
13
+ // --- Contract constants ----------------------------------------------------
14
+
15
+ assert.match(
16
+ app,
17
+ /const UI_LAYOUT_SCHEMA_VERSION = 1;[\s\S]*const UI_LAYOUT_ENDPOINT = "\/api\/interface-preferences";/,
18
+ "the browser controller should target the accepted version-1 layout schema on the existing interface-preferences endpoint",
19
+ );
20
+ assert.match(
21
+ app,
22
+ /const UI_LAYOUT_FIELDS = \["sidePanel", "composerActions", "footerScopedModelOrder", "terminalTabs", "fileViewerWidth"\];/,
23
+ "every approved arrangement surface should be a durable layout field",
24
+ );
25
+ for (const [constant, value] of [
26
+ ["UI_LAYOUT_ID_MAX_LENGTH", "256"],
27
+ ["UI_LAYOUT_TITLE_MAX_LENGTH", "160"],
28
+ ["UI_LAYOUT_LIST_MAX_ITEMS", "128"],
29
+ ["UI_LAYOUT_GROUP_MAX_COUNT", "32"],
30
+ ["UI_LAYOUT_GRID_MAX_COLUMNS", "24"],
31
+ ["UI_LAYOUT_GRID_MAX_SLOTS", "4096"],
32
+ ]) {
33
+ assert.match(app, new RegExp(`const ${constant} = ${value};`), `${constant} should mirror the accepted server-side bound`);
34
+ }
35
+ assert.doesNotMatch(
36
+ app,
37
+ /UI_LAYOUT_FIELDS = \[[^\]]*(selectedModel|activeTab|queue|attachment|prompt)/i,
38
+ "semantic file, queue, attachment, model, and prompt state must stay out of the durable layout schema",
39
+ );
40
+
41
+ // --- Local-first hydration and migration -----------------------------------
42
+
43
+ assert.match(
44
+ app,
45
+ /async function restoreSidePanelWidthPreference\(\)[\s\S]*readStoredSidePanelWidth\(\)[\s\S]*const layoutGenerations = new Map\(UI_LAYOUT_FIELDS\.map\(\(field\) => \[field, durableUiLayoutGeneration\(field\)\]\)\);[\s\S]*const readEpoch = \+\+durableLayoutReadEpoch;[\s\S]*await api\("\/api\/interface-preferences", \{ scoped: false \}\)[\s\S]*applyDurableUiLayoutSnapshot\(response\.data, \{ generations: layoutGenerations, readEpoch \}\)/,
46
+ "the local cache should apply first and a single non-blocking unscoped GET should hydrate both the width preference and the durable layout",
47
+ );
48
+ assert.equal(
49
+ (app.match(/api\("\/api\/interface-preferences", \{ scoped: false \}\)/g) || []).length
50
+ + (app.match(/api\(UI_LAYOUT_ENDPOINT, \{ scoped: false \}\)/g) || []).length,
51
+ 2,
52
+ "startup and reconciliation should share exactly one GET call site each instead of polling the settings endpoint",
53
+ );
54
+ assert.match(
55
+ app,
56
+ /function applyDurableUiLayoutSnapshot\(data, \{ generations = null, readEpoch = 0 \} = \{\}\)[\s\S]*readEpoch < durableLayoutAppliedReadEpoch[\s\S]*durableLayoutRevision = data\.layoutRevision/,
57
+ "the snapshot handler should reject out-of-order reads before retaining the opaque server layout revision",
58
+ );
59
+ assert.match(
60
+ app,
61
+ /function applyDurableUiLayoutSnapshot[\s\S]*const generationChanged = durableUiLayoutGeneration\(field\) !== requestedGeneration;[\s\S]*const dirtySubfields = dirtyEntry\?\.subfields/,
62
+ "a stale GET response should identify newer local generations and named dirty subfields",
63
+ );
64
+ assert.match(
65
+ app,
66
+ /function applyDurableUiLayoutSnapshot[\s\S]*!isDirty && !generationChanged && !durableUiLayoutInteractionActive\(field\)[\s\S]*applicable\[subfield\] = remote[\s\S]*applyDurableUiLayoutField\(field, applicable\)/,
67
+ "non-dirty sibling subfields should still adopt authoritative server values",
68
+ );
69
+ assert.match(
70
+ app,
71
+ /function applyDurableUiLayoutSnapshot[\s\S]*!isDirty && !durableUiLayoutValuePresent\(remote\) && durableUiLayoutValuePresent\(local\)[\s\S]*markDurableUiLayoutDirty\(field, subfield\)/,
72
+ "missing server subfields should migrate only their valid local values",
73
+ );
74
+ assert.match(
75
+ app,
76
+ /function refreshDurableUiLayoutFromServer\(\)[\s\S]*const readEpoch = \+\+durableLayoutReadEpoch[\s\S]*applyDurableUiLayoutSnapshot\(response\.data, \{ generations, readEpoch \}\)/,
77
+ "overlapping reconciliation reads should carry monotonic epochs",
78
+ );
79
+
80
+ // --- One coalescing writer, conflicts, and offline retention ---------------
81
+
82
+ assert.match(
83
+ app,
84
+ /function scheduleDurableUiLayoutSave\(delay = UI_LAYOUT_SAVE_DEBOUNCE_MS\)[\s\S]*clearTimeout\(durableLayoutSaveTimer\)[\s\S]*flushDurableUiLayoutSave\(\)/,
85
+ "saves should be coalesced through one debounced timer so drag-over movement cannot create a request storm",
86
+ );
87
+ assert.match(
88
+ app,
89
+ /function markDurableUiLayoutDirty\(field, subfield = null\)[\s\S]*durableUiLayoutGeneration\(field\) \+ 1[\s\S]*writeDurableUiLayoutPendingMutation\(field, key, value\?\.\[key\] \?\? null\)[\s\S]*subfieldMutationIds\.set\(key, nextMutationId\)[\s\S]*subfieldGenerations\.set\(key, generation\)/,
90
+ "each mutation should merge its named subfield into a reload-safe pending journal",
91
+ );
92
+ assert.match(
93
+ app,
94
+ /const UI_LAYOUT_PENDING_STORAGE_PREFIX = "pi-webui-ui-layout-pending-v3:";[\s\S]*function durableUiLayoutPendingMutationRecords\(\)[\s\S]*key\?\.startsWith\(UI_LAYOUT_PENDING_STORAGE_PREFIX\)[\s\S]*value\.version !== 3[\s\S]*function restoreDurableUiLayoutPendingJournal\(\)[\s\S]*candidate\.value[\s\S]*subfieldMutationIds[\s\S]*scheduleDurableUiLayoutSave\(\)/,
95
+ "per-writer pending layout values should survive reload without one tab replacing another tab's journal",
96
+ );
97
+ assert.match(
98
+ app,
99
+ /restoreDurableUiLayoutPendingJournal\(\);\s*\nrestoreSidePanelWidthPreference\(\);/,
100
+ "the pending journal should restore before the startup server read",
101
+ );
102
+ assert.match(
103
+ app,
104
+ /async function flushDurableUiLayoutSave\(\)[\s\S]*if \(durableLayoutSaveInFlight \|\| !durableLayoutDirtyFields\.size\) return;/,
105
+ "only one PUT may be in flight at a time",
106
+ );
107
+ assert.match(
108
+ app,
109
+ /async function flushDurableUiLayoutSave[\s\S]*durableLayoutDirtyFields\.keys\(\)[\s\S]*durableUiLayoutInteractionActive\(field\)[\s\S]*scheduleDurableUiLayoutSave\(\);\s*\n\s*return;/,
110
+ "an active interaction should defer only writes for its affected layout surface",
111
+ );
112
+ assert.match(
113
+ app,
114
+ /function durableUiLayoutInteractionActive\(field = null\)[\s\S]*sidePanelSectionPointerDrag\?\.active[\s\S]*composerActionPointerDrag\?\.active[\s\S]*footerScopedModelPointerDrag\?\.active[\s\S]*terminalTabDragId[\s\S]*fileViewerResizeState/,
115
+ "every durable reorder and resize interaction should be tracked per surface",
116
+ );
117
+ assert.match(
118
+ app,
119
+ /async function flushDurableUiLayoutSave[\s\S]*body: \{ layout: patch, expectedLayoutRevision: durableLayoutRevision \}/,
120
+ "layout writes should submit the latest known opaque revision",
121
+ );
122
+ assert.match(
123
+ app,
124
+ /async function flushDurableUiLayoutSave[\s\S]*current\.subfieldGenerations\?\.get\(subfield\) !== entry\.subfieldGenerations\?\.get\(subfield\)[\s\S]*current\.subfieldMutationIds\?\.get\(subfield\) !== entry\.subfieldMutationIds\?\.get\(subfield\)[\s\S]*clearAcknowledgedDurableUiLayoutPendingMutations\(snapshot\)/,
125
+ "acknowledgement should clear matching nested generations independently across every writer journal",
126
+ );
127
+ assert.match(
128
+ app,
129
+ /const UI_LAYOUT_MAX_CONFLICT_RETRIES = 1;[\s\S]*if \(status === 409\)[\s\S]*durableLayoutConflictAttempts \+= 1;[\s\S]*await refreshDurableUiLayoutFromServer\(\);[\s\S]*durableLayoutConflictAttempts <= UI_LAYOUT_MAX_CONFLICT_RETRIES[\s\S]*else warnDurableUiLayoutOnce/,
130
+ "a 409 should refresh once, retry within a bounded budget, and then report exactly one warning",
131
+ );
132
+ assert.match(
133
+ app,
134
+ /function warnDurableUiLayoutOnce\(message\)[\s\S]*if \(durableLayoutWarned\) return;[\s\S]*durableLayoutWarned = true;[\s\S]*addEvent\(message, "warn"\)/,
135
+ "conflict and rejection reporting should stay bounded to one warning",
136
+ );
137
+ assert.match(
138
+ app,
139
+ /async function flushDurableUiLayoutSave[\s\S]*navigator\.onLine === false\) return;/,
140
+ "offline browsers should keep the dirty layout instead of issuing doomed writes",
141
+ );
142
+ assert.match(
143
+ app,
144
+ /function reconcileDurableUiLayout\(\)[\s\S]*refreshDurableUiLayoutFromServer\(\)\.then\(\(ready\) => \{[\s\S]*durableLayoutDirtyFields\.size\) scheduleDurableUiLayoutSave\(0\)/,
145
+ "foreground reconciliation should retry retained dirty state",
146
+ );
147
+ assert.match(
148
+ app,
149
+ /window\.addEventListener\("online", \(\) => reconcileDurableUiLayout\(\)\);\s*\nwindow\.addEventListener\("pageshow", \(\) => reconcileDurableUiLayout\(\)\);\s*\ndocument\.addEventListener\("visibilitychange", \(\) => \{\s*\n\s*if \(document\.visibilityState === "visible"\) reconcileDurableUiLayout\(\);/,
150
+ "durable layout reconciliation should use dedicated online, pageshow, and foreground listeners",
151
+ );
152
+ // The pre-existing session/transcript reconciliation contracts must stay intact.
153
+ assert.match(
154
+ app,
155
+ /window\.addEventListener\("pageshow", \(\) => scheduleForegroundReconcile\("page show", 0\)\);/,
156
+ "existing foreground snapshot reconciliation must remain unchanged",
157
+ );
158
+ assert.match(
159
+ app,
160
+ /window\.addEventListener\("online", \(\) => scheduleForegroundReconcile\("network online", 0\)\);/,
161
+ "existing online snapshot reconciliation must remain unchanged",
162
+ );
163
+
164
+ // --- Every approved arrangement surface is durable -------------------------
165
+
166
+ for (const [persistFunction, field, subfield] of [
167
+ ["persistSidePanelSectionOrder", "sidePanel", "sectionOrder"],
168
+ ["persistSidePanelSectionState", "sidePanel", "collapsedSectionIds"],
169
+ ["persistSidePanelSectionVisibility", "sidePanel", "hiddenSectionIds"],
170
+ ["persistComposerActionOrder", "composerActions", null],
171
+ ["persistComposerActionSlotLayout", "composerActions", null],
172
+ ["persistTerminalTabsLayout", "terminalTabs", "layout"],
173
+ ["persistTerminalCustomGroups", "terminalTabs", "customGroups"],
174
+ ["persistFileViewerWidth", "fileViewerWidth", null],
175
+ ["writeFooterScopedModelOrder", "footerScopedModelOrder", null],
176
+ ]) {
177
+ const marker = subfield
178
+ ? `markDurableUiLayoutDirty\\("${field}", "${subfield}"\\)`
179
+ : `markDurableUiLayoutDirty\\("${field}"\\)`;
180
+ assert.match(
181
+ app,
182
+ new RegExp(`function ${persistFunction}\\([^)]*\\) \\{[\\s\\S]*?${marker};\\s*\\n\\}`),
183
+ `${persistFunction} should mark only its owned durable layout value after writing the local cache`,
184
+ );
185
+ }
186
+ assert.match(
187
+ app,
188
+ /localStorage\.setItem\(SIDE_PANEL_STORAGE_KEY, collapsed \? "1" : "0"\);[\s\S]{0,200}markDurableUiLayoutDirty\("sidePanel", "collapsed"\)/,
189
+ "Control Deck collapse state should be durable without dirtying sibling settings",
190
+ );
191
+ assert.match(
192
+ app,
193
+ /function restoreSidePanelState\(\)[\s\S]*setSidePanelCollapsed\(stored \?\? false, \{ persist: false \}\)/,
194
+ "passive Control Deck restoration must not echo stale cache back to the server",
195
+ );
196
+
197
+ // --- Composer order and grid stay one atomic logical update ----------------
198
+
199
+ assert.match(
200
+ app,
201
+ /function collectDurableComposerActionsLayout\(\)[\s\S]*return \{ order: durableLayoutStoredIdList\(COMPOSER_ACTION_ORDER_STORAGE_KEY\), grid \};/,
202
+ "composer order and sparse grid must be submitted together as one field",
203
+ );
204
+ assert.match(
205
+ app,
206
+ /function collectDurableComposerActionsLayout\(\)[\s\S]*grid = \{ version: 2, columns: stored\.columns, positions \};/,
207
+ "the persisted grid should use the accepted version-2 sparse envelope",
208
+ );
209
+ assert.match(
210
+ app,
211
+ /function applyDurableComposerActionsLayout\(value\)[\s\S]*writeDurableLayoutCache\(COMPOSER_ACTION_LAYOUT_STORAGE_KEY, JSON\.stringify\(value\.grid\)\);\s*\n\s*restoreComposerActionSlotLayout\(\)/,
212
+ "server grid slots should be cached locally and restored through the existing responsive restore pass",
213
+ );
214
+ assert.match(
215
+ app,
216
+ /function restoreComposerActionSlotLayout\(\)[\s\S]*stored\.columns === columns[\s\S]*remapComposerActionSlot[\s\S]*nearestAvailableComposerActionSlot/,
217
+ "stored slots should project into mismatched column counts without rewriting the saved source geometry",
218
+ );
219
+
220
+ // --- Cross-tab cache adoption without duplicate server writes --------------
221
+
222
+ assert.match(
223
+ app,
224
+ /window\.addEventListener\("storage"[\s\S]*event\.key === TERMINAL_CUSTOM_GROUPS_STORAGE_KEY[\s\S]*restoreTerminalCustomGroups\(\);[\s\S]*syncTerminalCustomGroupsWithTabs\(tabs, \{ persist: false \}\)/,
225
+ "another tab's terminal groups should be adopted through the existing tab-filtering restore without re-persisting",
226
+ );
227
+ assert.match(
228
+ app,
229
+ /window\.addEventListener\("storage"[\s\S]*event\.key === FOOTER_SCOPED_MODEL_ORDER_STORAGE_KEY[\s\S]*footerScopedModels = orderedFooterScopedModels\(\)/,
230
+ "another tab's footer order should be adopted locally",
231
+ );
232
+ assert.match(
233
+ app,
234
+ /window\.addEventListener\("storage"[\s\S]*event\.key === FILE_VIEWER_WIDTH_STORAGE_KEY\) restoreFileViewerWidthPreference\(\)/,
235
+ "another tab's file-viewer width should be adopted locally",
236
+ );
237
+ for (const applyFunction of [
238
+ "applyDurableSidePanelLayout",
239
+ "applyDurableComposerActionsLayout",
240
+ "applyDurableFooterScopedModelOrder",
241
+ "applyDurableTerminalTabsLayout",
242
+ "applyDurableFileViewerWidth",
243
+ ]) {
244
+ const body = new RegExp(`function ${applyFunction}\\(value\\) \\{[\\s\\S]*?\\n\\}`).exec(app)?.[0] || "";
245
+ assert.ok(body, `${applyFunction} should exist`);
246
+ assert.doesNotMatch(body, /markDurableUiLayoutDirty/, `${applyFunction} must not echo server state back as a new write`);
247
+ }
248
+
249
+ // --- Terminal groups keep the existing valid-tab filtering ------------------
250
+
251
+ assert.match(
252
+ app,
253
+ /function applyDurableTerminalTabsLayout\(value\)[\s\S]*setTerminalTabsLayout\(value\.layout, \{ persist: false \}\)/,
254
+ "an applied terminal layout should not re-persist",
255
+ );
256
+ assert.match(
257
+ app,
258
+ /function collectDurableTerminalTabsLayout\(\)[\s\S]*if \(!title \|\| tabIds\.length < 2\) continue;/,
259
+ "durable groups should honor the existing minimum-membership rule and bounded titles",
260
+ );
261
+
262
+ // --- Coherent browser asset revisions --------------------------------------
263
+
264
+ assert.match(serviceWorker, /const CACHE_NAME = "pi-webui-pwa-v71"/, "changed browser assets should advance the PWA cache identity");
265
+ assert.match(html, /data-app-src="\/app\.js\?v=112"/, "the boot loader should request the updated app module revision");
266
+
267
+ console.log("persistent-ui-layout-static.test.mjs passed");