@firstpick/pi-package-webui 0.8.2 → 0.8.4

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 (52) hide show
  1. package/README.md +76 -19
  2. package/bin/pi-webui.mjs +864 -140
  3. package/lib/WEBUI_TUI_NATIVE_PARITY.json +26 -0
  4. package/lib/git-workflow-preferences.mjs +246 -19
  5. package/lib/optional-feature-catalog.mjs +29 -0
  6. package/lib/optional-feature-migration.mjs +410 -0
  7. package/lib/session-summary-core.mjs +320 -0
  8. package/lib/session-summary-preferences.mjs +267 -0
  9. package/lib/thinking-stream-recovery.mjs +156 -0
  10. package/lib/ui-layout-settings.mjs +254 -0
  11. package/package.json +5 -40
  12. package/public/app.js +2898 -92
  13. package/public/index.html +77 -14
  14. package/public/service-worker.js +1 -1
  15. package/public/styles.css +669 -2
  16. package/session-summary.ts +403 -0
  17. package/tests/aur-review-widget-static.test.mjs +3 -2
  18. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  19. package/tests/browser/composer-action-grid-reorder.spec.mjs +303 -0
  20. package/tests/browser/feature-decision-output-popup.spec.mjs +156 -0
  21. package/tests/browser/interaction-continuity.spec.mjs +29 -0
  22. package/tests/browser/persistent-ui-layout.spec.mjs +744 -0
  23. package/tests/browser/session-summary.spec.mjs +271 -0
  24. package/tests/codex-fast-mode-static.test.mjs +10 -9
  25. package/tests/composer-action-grid-reorder-static.test.mjs +63 -0
  26. package/tests/fast-mode-client-static.test.mjs +2 -2
  27. package/tests/feature-decision-output-popup-static.test.mjs +172 -0
  28. package/tests/fixtures/fake-pi.mjs +51 -1
  29. package/tests/git-workflow-preferences.test.mjs +4 -2
  30. package/tests/http-endpoints-harness.test.mjs +507 -4
  31. package/tests/interaction-state-stability-static.test.mjs +3 -0
  32. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  33. package/tests/mobile-foundation-static.test.mjs +3 -3
  34. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  35. package/tests/mobile-static.test.mjs +118 -103
  36. package/tests/native-parity-harness.test.mjs +9 -1
  37. package/tests/native-parity.test.mjs +23 -1
  38. package/tests/open-issue-wizard-static.test.mjs +1 -1
  39. package/tests/optional-feature-migration-frontend.test.mjs +72 -0
  40. package/tests/optional-feature-migration.test.mjs +142 -0
  41. package/tests/persistent-ui-layout-static.test.mjs +267 -0
  42. package/tests/questionnaire-dialog.test.mjs +511 -0
  43. package/tests/queue-edit-reorder-static.test.mjs +1 -0
  44. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  45. package/tests/session-summary-core.test.mjs +491 -0
  46. package/tests/session-summary-preferences.test.mjs +103 -0
  47. package/tests/side-panel-resize-static.test.mjs +1 -0
  48. package/tests/side-panel-section-reorder-static.test.mjs +3 -3
  49. package/tests/subagent-launch-slots.test.mjs +1 -1
  50. package/tests/thinking-stream-recovery.test.mjs +88 -0
  51. package/tests/ui-layout-settings.test.mjs +92 -0
  52. package/tests/webui-settings-locking.test.mjs +159 -0
package/public/app.js CHANGED
@@ -20,6 +20,7 @@ const elements = {
20
20
  terminalTabsToggleButton: $("#terminalTabsToggleButton"),
21
21
  splitTabButton: $("#splitTabButton"),
22
22
  workspaceSaveButton: $("#workspaceSaveButton"),
23
+ summaryHeaderButton: $("#summaryHeaderButton"),
23
24
  newTabMenu: $("#newTabMenu"),
24
25
  newTabButton: $("#newTabButton"),
25
26
  newTabMenuPanel: $("#newTabMenuPanel"),
@@ -91,6 +92,8 @@ const elements = {
91
92
  composerRow: $(".composer-row"),
92
93
  composerActionsButton: $("#composerActionsButton"),
93
94
  composerActionsPanel: $("#composerActionsPanel"),
95
+ composerActionGridGuide: $("#composerActionGridGuide"),
96
+ composerActionOrderStatus: $("#composerActionOrderStatus"),
94
97
  promptInput: $("#promptInput"),
95
98
  mobileFailedSendRecovery: $("#mobileFailedSendRecovery"),
96
99
  mobileFailedSendRetryButton: $("#mobileFailedSendRetryButton"),
@@ -106,6 +109,9 @@ const elements = {
106
109
  busyPromptBehaviorMenu: $("#busyPromptBehaviorMenu"),
107
110
  sessionSkillTags: $("#sessionSkillTags"),
108
111
  featureCategoryTag: $("#featureCategoryTag"),
112
+ featureDecisionDialog: $("#featureDecisionDialog"),
113
+ featureDecisionDialogOutput: $("#featureDecisionDialogOutput"),
114
+ featureDecisionDialogCloseButton: $("#featureDecisionDialogCloseButton"),
109
115
  conversationModeChip: $("#conversationModeChip"),
110
116
  workflowModeChip: $("#workflowModeChip"),
111
117
  skillEditorDialog: $("#skillEditorDialog"),
@@ -134,6 +140,7 @@ const elements = {
134
140
  remoteMicStreamingConsentButton: $("#remoteMicStreamingConsentButton"),
135
141
  newSessionButton: $("#newSessionButton"),
136
142
  compactButton: $("#compactButton"),
143
+ summaryActionButton: $("#summaryActionButton"),
137
144
  workflowModeControls: $("#workflowModeControls"),
138
145
  workflowModeButton: $("#workflowModeButton"),
139
146
  workflowOverlayOpenButton: $("#workflowOverlayOpenButton"),
@@ -160,6 +167,7 @@ const elements = {
160
167
  optionsNameButton: $("#optionsNameButton"),
161
168
  optionsCloneButton: $("#optionsCloneButton"),
162
169
  optionsSettingsButton: $("#optionsSettingsButton"),
170
+ optionsSummarySetupButton: $("#optionsSummarySetupButton"),
163
171
  optionsWorkflowSetupButton: $("#optionsWorkflowSetupButton"),
164
172
  optionsSafetyGuardSetupButton: $("#optionsSafetyGuardSetupButton"),
165
173
  optionsGitWorkflowSetupButton: $("#optionsGitWorkflowSetupButton"),
@@ -233,6 +241,17 @@ const elements = {
233
241
  agentDoneNotificationsToggle: $("#agentDoneNotificationsToggle"),
234
242
  agentDoneNotificationsStatus: $("#agentDoneNotificationsStatus"),
235
243
  optionalFeaturesBox: $("#optionalFeaturesBox"),
244
+ optionalFeatureMigrationSurface: $("#optionalFeatureMigrationSurface"),
245
+ optionalFeatureMigrationDialog: $("#optionalFeatureMigrationDialog"),
246
+ optionalFeatureMigrationDialogTitle: $("#optionalFeatureMigrationDialogTitle"),
247
+ optionalFeatureMigrationDialogMessage: $("#optionalFeatureMigrationDialogMessage"),
248
+ optionalFeatureMigrationDialogSummary: $("#optionalFeatureMigrationDialogSummary"),
249
+ optionalFeatureMigrationChooseDetails: $("#optionalFeatureMigrationChooseDetails"),
250
+ optionalFeatureMigrationChoices: $("#optionalFeatureMigrationChoices"),
251
+ optionalFeatureMigrationDialogError: $("#optionalFeatureMigrationDialogError"),
252
+ optionalFeatureMigrationCancelButton: $("#optionalFeatureMigrationCancelButton"),
253
+ optionalFeatureMigrationLaterButton: $("#optionalFeatureMigrationLaterButton"),
254
+ optionalFeatureMigrationConfirmButton: $("#optionalFeatureMigrationConfirmButton"),
236
255
  codexUsageBox: $("#codexUsageBox"),
237
256
  refreshCodexUsageButton: $("#refreshCodexUsageButton"),
238
257
  codexFastModeSelect: $("#codexFastModeSelect"),
@@ -302,6 +321,7 @@ const elements = {
302
321
  issueWizardBotHint: $("#issueWizardBotHint"),
303
322
  stateDetails: $("#stateDetails"),
304
323
  subagentsStatus: $("#subagentsStatus"),
324
+ subagentsAutoClearButton: $("#subagentsAutoClearButton"),
305
325
  subagentsClearFinishedButton: $("#subagentsClearFinishedButton"),
306
326
  subagentsBox: $("#subagentsBox"),
307
327
  subagentCountBadge: $("#subagentCountBadge"),
@@ -348,6 +368,14 @@ const elements = {
348
368
  attachmentTextStatus: $("#attachmentTextStatus"),
349
369
  attachmentTextCancelButton: $("#attachmentTextCancelButton"),
350
370
  attachmentTextSaveButton: $("#attachmentTextSaveButton"),
371
+ sessionSummaryOverlay: $("#sessionSummaryOverlay"),
372
+ sessionSummaryOverlayTitle: $("#sessionSummaryOverlayTitle"),
373
+ sessionSummaryOverlayMeta: $("#sessionSummaryOverlayMeta"),
374
+ sessionSummaryOverlayStatus: $("#sessionSummaryOverlayStatus"),
375
+ sessionSummaryOverlayBody: $("#sessionSummaryOverlayBody"),
376
+ sessionSummaryOverlayCloseButton: $("#sessionSummaryOverlayCloseButton"),
377
+ sessionSummaryOverlayCopyButton: $("#sessionSummaryOverlayCopyButton"),
378
+ sessionSummaryOverlayRefreshButton: $("#sessionSummaryOverlayRefreshButton"),
351
379
  commandSearchInput: $("#commandSearchInput"),
352
380
  commandsBox: $("#commandsBox"),
353
381
  eventLog: $("#eventLog"),
@@ -493,6 +521,12 @@ let sidePanelContextMenuState = null;
493
521
  let sidePanelSectionPointerDrag = null;
494
522
  let sidePanelSectionLastDragOverKey = "";
495
523
  let sidePanelSectionSuppressClickUntil = 0;
524
+ let composerActionPointerDrag = null;
525
+ let composerActionLastDragOverKey = "";
526
+ let composerActionSuppressClickUntil = 0;
527
+ let composerActionSlotLayout = new Map();
528
+ let composerActionLayoutColumns = 0;
529
+ let composerActionLayoutRestoreFrame = null;
496
530
  let fileTreeDragState = null;
497
531
  let fileViewerResizeState = null;
498
532
  let sidePanelResizeState = null;
@@ -560,6 +594,7 @@ const supervisorGapWarnings = new Set();
560
594
  const supervisorContinuityRefreshes = new Map();
561
595
  const supervisorEnvelopeWarnings = new Set();
562
596
  let activeDialog = null;
597
+ let activeDialogCancel = null;
563
598
  let activeConfirmationResolve = null;
564
599
  let activeWorkspaceReplacementResolve = null;
565
600
  let workspaceLoadPickerFocusReturn = null;
@@ -587,6 +622,9 @@ let gitChangesRequestSerial = 0;
587
622
  const gitChangesUntrackedContentRequests = new Set();
588
623
  let nativeCommandTabId = null;
589
624
  let nativeSettingsDirty = false;
625
+ let sessionSummaryOverlayTabId = null;
626
+ let sessionSummaryOverlayFocusReturn = null;
627
+ const sessionSummaryByTab = new Map();
590
628
  let pathPickerState = null;
591
629
  let firstTerminalCwdPromptShown = false;
592
630
  let pathFastPicks = [];
@@ -667,6 +705,7 @@ let latestSubagents = null;
667
705
  let subagentsError = null;
668
706
  let subagentsLoading = false;
669
707
  let subagentsClearingFinished = false;
708
+ let subagentAutoClearEnabled = false;
670
709
  let refreshSubagentsTimer = null;
671
710
  const dismissedSubagentGateKeys = new Set();
672
711
  let subagentOverlaySelection = null;
@@ -809,6 +848,9 @@ const SIDE_PANEL_SECTION_STORAGE_KEY = "pi-webui-side-panel-sections-collapsed";
809
848
  const SIDE_PANEL_SECTION_VISIBILITY_STORAGE_KEY = "pi-webui-side-panel-sections-hidden";
810
849
  const SIDE_PANEL_SECTION_ORDER_STORAGE_KEY = "pi-webui-side-panel-section-order-v1";
811
850
  const SIDE_PANEL_SECTION_POINTER_DRAG_THRESHOLD_PX = 6;
851
+ const COMPOSER_ACTION_ORDER_STORAGE_KEY = "pi-webui-composer-action-order-v1";
852
+ const COMPOSER_ACTION_LAYOUT_STORAGE_KEY = "pi-webui-composer-action-layout-v2";
853
+ const COMPOSER_ACTION_POINTER_DRAG_THRESHOLD_PX = 6;
812
854
  const TAB_STORAGE_KEY = "pi-webui-active-tab";
813
855
  const PATH_FAST_PICKS_STORAGE_KEY = "pi-webui-path-fast-picks";
814
856
  const AGENT_DONE_NOTIFICATIONS_STORAGE_KEY = "pi-webui-agent-done-notifications";
@@ -824,6 +866,7 @@ const BUSY_PROMPT_BEHAVIOR_STORAGE_KEY = "pi-webui-busy-prompt-behavior";
824
866
  const SKILL_USAGE_STORAGE_KEY = "pi-webui-skill-usage-v1";
825
867
  const TERMINAL_TABS_LAYOUT_STORAGE_KEY = "pi-webui-terminal-tabs-layout";
826
868
  const SUBAGENT_OPEN_MODE_STORAGE_KEY = "pi-webui-subagent-open-mode";
869
+ const SUBAGENT_AUTO_CLEAR_STORAGE_KEY = "pi-webui-subagent-auto-clear";
827
870
  const TERMINAL_CUSTOM_GROUPS_STORAGE_KEY = "pi-webui-terminal-custom-groups-v1";
828
871
  const TERMINAL_TAB_DRAG_MIME = "application/x-pi-terminal-tab-id";
829
872
  const FOOTER_SCOPED_MODEL_ORDER_STORAGE_KEY = "pi-webui-footer-scoped-model-order-v1";
@@ -921,7 +964,10 @@ const WORKFLOW_INSPECTOR_PAYLOAD_PREFIX = "WORKFLOW_RPC_PAYLOAD ";
921
964
  const WORKFLOW_INSPECTOR_PAYLOAD_TYPE = "firstpick.pi-extension-workflows.inspector";
922
965
  const WORKFLOW_INSPECTOR_PAYLOAD_VERSION = 1;
923
966
  const WORKFLOW_MODE_STATUS_KEY = "workflow-mode";
967
+ const FEATURE_DECISION_OUTPUT_STATUS_KEY = "feature-decision-output";
924
968
  const FEATURE_CATEGORY_STATUS_KEY = "feature-category";
969
+ const FEATURE_DECISION_PAYLOAD_MAX_CHARS = 4096;
970
+ const FEATURE_DECISION_REASON_MAX_CHARS = 500;
925
971
  const WORKFLOW_MODE_RPC_WIDGET_KEY = "workflow-mode:rpc";
926
972
  const WORKFLOW_MODE_RPC_PAYLOAD_PREFIX = "WORKFLOW_MODE_RPC_PAYLOAD ";
927
973
  const WORKFLOW_MODE_RPC_PAYLOAD_TYPE = "firstpick.pi-extension-workflows.mode";
@@ -2134,6 +2180,8 @@ function receiveMobileNavigationTarget(value) {
2134
2180
  syncMobileShellRoot();
2135
2181
  const statusEntries = new Map();
2136
2182
  const featureCategoryByTab = new Map();
2183
+ const featureDecisionOutputByTab = new Map();
2184
+ let featureDecisionDialogTabId = null;
2137
2185
  const widgets = new Map();
2138
2186
  const widgetsByTab = new Map();
2139
2187
  const todoProgressWidgetExpandedByTab = new Map();
@@ -2177,6 +2225,7 @@ const optionalFeatureAvailability = {
2177
2225
  todoProgressWidget: false,
2178
2226
  tuiToolsCommand: false,
2179
2227
  remoteWebui: false,
2228
+ questionnaire: false,
2180
2229
  naturalConversation: false,
2181
2230
  codexFastMode: false,
2182
2231
  themeBundle: false,
@@ -2276,6 +2325,14 @@ const OPTIONAL_FEATURES = [
2276
2325
  capabilityLabel: "/remote",
2277
2326
  description: "Trusted-LAN QR helper for opening the Web UI from mobile browsers.",
2278
2327
  },
2328
+ {
2329
+ id: "questionnaire",
2330
+ label: "Native questionnaires",
2331
+ packageName: "@firstpick/pi-package-questionnaire",
2332
+ capabilityLabel: "questionnaire tool in /tools",
2333
+ description: "Native TUI and WebUI single- or multi-select question series with Other answers and resumable clarification.",
2334
+ manageWith: "tools",
2335
+ },
2279
2336
  {
2280
2337
  id: "naturalConversation",
2281
2338
  label: "Natural Conversation",
@@ -2724,7 +2781,7 @@ const OPTIONAL_FEATURE_SECTIONS = [
2724
2781
  id: "widgets-native-parity",
2725
2782
  label: "UI widgets & native parity",
2726
2783
  description: "Status widgets, dashboards, themes, and browser access to terminal-native controls.",
2727
- featureIds: ["tuiSkillsCommand", "todoProgressWidget", "tuiToolsCommand", "gitFooterStatus", "statsCommand", "themeBundle"],
2784
+ featureIds: ["tuiSkillsCommand", "todoProgressWidget", "tuiToolsCommand", "questionnaire", "gitFooterStatus", "statsCommand", "themeBundle"],
2728
2785
  },
2729
2786
  {
2730
2787
  id: "conversation",
@@ -2767,7 +2824,11 @@ const HIDDEN_COMMAND_NAMES = new Set(["webui-tree-navigate", "webui-helper"]);
2767
2824
  HIDDEN_COMMAND_NAMES.add("stats-webui");
2768
2825
  HIDDEN_COMMAND_NAMES.add("btw-status");
2769
2826
  HIDDEN_COMMAND_NAMES.add("btw-transfer");
2770
- const NATIVE_SELECTOR_COMMANDS = new Set(["model", "settings", "workflow-setup", "safety-guard-setup", "git-workflow-setup", "theme", "fork", "clone", "name", "resume", "tree", "login", "logout", "scoped-models", "tools", "skills"]);
2827
+ const SESSION_SUMMARY_PROTOCOL_VERSION = 1;
2828
+ const SESSION_SUMMARY_MARKDOWN_MAX_CHARS = 16 * 1024;
2829
+ const SESSION_SUMMARY_PROMPT_MAX_CHARS = 8 * 1024;
2830
+ const SESSION_SUMMARY_REQUEST_TIMEOUT_MS = 110 * 1000;
2831
+ const NATIVE_SELECTOR_COMMANDS = new Set(["model", "settings", "summary", "summary-setup", "workflow-setup", "safety-guard-setup", "git-workflow-setup", "theme", "fork", "clone", "name", "resume", "tree", "login", "logout", "scoped-models", "tools", "skills"]);
2771
2832
  const SETTINGS_THINKING_OPTIONS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
2772
2833
  const SETTINGS_TRANSPORT_OPTIONS = ["sse", "websocket", "websocket-cached", "auto"];
2773
2834
  const SETTINGS_HTTP_IDLE_TIMEOUT_OPTIONS = [
@@ -2795,6 +2856,25 @@ const optionalFeaturePackageStatuses = new Map();
2795
2856
  const optionalFeatureInstallMessages = new Map();
2796
2857
  const optionalFeatureInstallStates = new Map();
2797
2858
  const optionalFeatureInstallProgressTimers = new Map();
2859
+ const optionalFeatureMigrationResultEvents = new Set();
2860
+ let optionalFeatureBatchState = null;
2861
+ let optionalFeatureMigrationSnapshot = {
2862
+ phase: "checking",
2863
+ revision: "pending",
2864
+ installKind: "unknown",
2865
+ summary: { ready: 0, migratable: 0, missing: 0, conflicts: 0, disabled: 0, unknown: 0 },
2866
+ features: [],
2867
+ progress: null,
2868
+ completedAt: null,
2869
+ diagnostic: null,
2870
+ };
2871
+ let optionalFeatureMigrationCheckingStartedAt = Date.now();
2872
+ let optionalFeatureMigrationRenderTimer = null;
2873
+ let optionalFeatureMigrationDialogState = null;
2874
+ let optionalFeatureMigrationLastPhase = "";
2875
+ let optionalFeatureMigrationCompletionFocusKey = "";
2876
+ let optionalFeatureRestartNotice = null;
2877
+ let optionalFeaturePackageStatusesLoaded = false;
2798
2878
  let optionalFeaturePackageStatusError = "";
2799
2879
  const gitFooterPayloadRefreshInFlightByTab = new Set();
2800
2880
  const gitFooterPayloadStateByTab = new Map();
@@ -3415,6 +3495,7 @@ function persistSidePanelSectionOrder() {
3415
3495
  } catch {
3416
3496
  // Ignore storage failures; ordering should still work for this page load.
3417
3497
  }
3498
+ markDurableUiLayoutDirty("sidePanel", "sectionOrder");
3418
3499
  }
3419
3500
 
3420
3501
  function restoreSidePanelSectionOrder() {
@@ -3545,6 +3626,7 @@ function persistSidePanelSectionState() {
3545
3626
  } catch {
3546
3627
  // Ignore storage failures; section toggles should still work for this page load.
3547
3628
  }
3629
+ markDurableUiLayoutDirty("sidePanel", "collapsedSectionIds");
3548
3630
  }
3549
3631
 
3550
3632
  function readStoredSidePanelSectionHiddenIds() {
@@ -3567,6 +3649,7 @@ function persistSidePanelSectionVisibility() {
3567
3649
  } catch {
3568
3650
  // Ignore storage failures; visibility toggles should still work for this page load.
3569
3651
  }
3652
+ markDurableUiLayoutDirty("sidePanel", "hiddenSectionIds");
3570
3653
  }
3571
3654
 
3572
3655
  function setSidePanelSectionVisible(record, visible, { persist = true } = {}) {
@@ -3695,6 +3778,481 @@ function bindSidePanelSectionToggles() {
3695
3778
  }
3696
3779
  }
3697
3780
 
3781
+ function composerActionRecords() {
3782
+ return Array.from(elements.composerRow?.querySelectorAll("[data-composer-action-id]") || [])
3783
+ .map((root, domIndex) => {
3784
+ const id = root.dataset.composerActionId || "";
3785
+ const focusTarget = root.matches("button") ? root : root.querySelector("button");
3786
+ const rawStoredOrder = root.style.getPropertyValue("--composer-action-order");
3787
+ const storedOrder = Number(rawStoredOrder);
3788
+ const order = rawStoredOrder !== "" && Number.isFinite(storedOrder) ? storedOrder : domIndex;
3789
+ const span = Number(root.dataset.composerActionSpan) === 2 ? 2 : 1;
3790
+ return { id, root, focusTarget, domIndex, order, span };
3791
+ })
3792
+ .filter((record) => record.id && record.focusTarget);
3793
+ }
3794
+
3795
+ function orderedComposerActionRecords({ visibleOnly = false } = {}) {
3796
+ return composerActionRecords()
3797
+ .filter(({ root }) => !visibleOnly || (!root.hidden && root.getClientRects().length > 0))
3798
+ .sort((a, b) => a.order - b.order || a.domIndex - b.domIndex);
3799
+ }
3800
+
3801
+ function readStoredComposerActionOrder() {
3802
+ try {
3803
+ const parsed = JSON.parse(localStorage.getItem(COMPOSER_ACTION_ORDER_STORAGE_KEY) || "[]");
3804
+ return Array.isArray(parsed) ? [...new Set(parsed.filter((id) => typeof id === "string" && id.trim()))] : [];
3805
+ } catch {
3806
+ return [];
3807
+ }
3808
+ }
3809
+
3810
+ function applyComposerActionOrder(orderIds) {
3811
+ const records = composerActionRecords();
3812
+ const knownIds = new Set(records.map(({ id }) => id));
3813
+ const completeOrder = [
3814
+ ...new Set(orderIds.filter((id) => knownIds.has(id))),
3815
+ ...records.map(({ id }) => id).filter((id) => !orderIds.includes(id)),
3816
+ ];
3817
+ const rank = new Map(completeOrder.map((id, index) => [id, index]));
3818
+ for (const record of records) record.root.style.setProperty("--composer-action-order", String(rank.get(record.id)));
3819
+ return completeOrder;
3820
+ }
3821
+
3822
+ function restoreComposerActionOrder() {
3823
+ if (composerActionPointerDrag?.active) return;
3824
+ applyComposerActionOrder(readStoredComposerActionOrder());
3825
+ }
3826
+
3827
+ function persistComposerActionOrder() {
3828
+ try {
3829
+ localStorage.setItem(COMPOSER_ACTION_ORDER_STORAGE_KEY, JSON.stringify(orderedComposerActionRecords().map(({ id }) => id)));
3830
+ } catch {
3831
+ // Ignore storage failures; ordering should still work for this page load.
3832
+ }
3833
+ markDurableUiLayoutDirty("composerActions");
3834
+ }
3835
+
3836
+ function composerActionGridColumnCount() {
3837
+ const row = elements.composerRow;
3838
+ const style = getComputedStyle(row);
3839
+ const rawMinWidth = style.getPropertyValue("--composer-action-cell-min-width").trim();
3840
+ const numericMinWidth = Number.parseFloat(rawMinWidth);
3841
+ const rootFontSize = Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
3842
+ const rowFontSize = Number.parseFloat(style.fontSize) || rootFontSize;
3843
+ const minWidth = rawMinWidth.endsWith("rem")
3844
+ ? numericMinWidth * rootFontSize
3845
+ : rawMinWidth.endsWith("em")
3846
+ ? numericMinWidth * rowFontSize
3847
+ : numericMinWidth;
3848
+ const gap = Number.parseFloat(style.columnGap || style.gap) || 0;
3849
+ const availableWidth = row.clientWidth || row.getBoundingClientRect().width;
3850
+ if (!Number.isFinite(minWidth) || minWidth <= 0 || !Number.isFinite(availableWidth) || availableWidth <= 0) return 1;
3851
+ return Math.max(1, Math.floor((availableWidth + gap) / (minWidth + gap)));
3852
+ }
3853
+
3854
+ function readStoredComposerActionLayout() {
3855
+ try {
3856
+ const parsed = JSON.parse(localStorage.getItem(COMPOSER_ACTION_LAYOUT_STORAGE_KEY) || "null");
3857
+ if (!parsed || parsed.version !== 2 || !Number.isInteger(parsed.columns) || parsed.columns < 1 || !parsed.positions || typeof parsed.positions !== "object") return null;
3858
+ const positions = new Map();
3859
+ for (const [id, slot] of Object.entries(parsed.positions)) {
3860
+ if (typeof id === "string" && id && Number.isInteger(slot) && slot >= 0) positions.set(id, slot);
3861
+ }
3862
+ return { columns: parsed.columns, positions };
3863
+ } catch {
3864
+ return null;
3865
+ }
3866
+ }
3867
+
3868
+ function composerActionSlotCanFit(record, slot, layout = composerActionSlotLayout, columns = composerActionLayoutColumns) {
3869
+ if (!record || !Number.isInteger(slot) || slot < 0 || columns < 1) return false;
3870
+ const column = slot % columns;
3871
+ if (column + record.span > columns) return false;
3872
+ const row = Math.floor(slot / columns);
3873
+ for (const [otherId, otherSlot] of layout) {
3874
+ if (otherId === record.id) continue;
3875
+ const other = composerActionRecords().find(({ id, root }) => id === otherId && !root.hidden && root.getClientRects().length > 0);
3876
+ if (!other || Math.floor(otherSlot / columns) !== row) continue;
3877
+ const otherColumn = otherSlot % columns;
3878
+ if (column < otherColumn + other.span && otherColumn < column + record.span) return false;
3879
+ }
3880
+ return true;
3881
+ }
3882
+
3883
+ function applyComposerActionSlotLayout() {
3884
+ for (const record of composerActionRecords()) {
3885
+ const slot = composerActionSlotLayout.get(record.id);
3886
+ if (!Number.isInteger(slot) || composerActionLayoutColumns < 1 || record.root.hidden) {
3887
+ record.root.style.removeProperty("--composer-action-grid-column");
3888
+ record.root.style.removeProperty("--composer-action-grid-row");
3889
+ continue;
3890
+ }
3891
+ record.root.style.setProperty("--composer-action-grid-column", String((slot % composerActionLayoutColumns) + 1));
3892
+ record.root.style.setProperty("--composer-action-grid-row", String(Math.floor(slot / composerActionLayoutColumns) + 1));
3893
+ }
3894
+ }
3895
+
3896
+ function persistComposerActionSlotLayout() {
3897
+ if (composerActionLayoutColumns < 1 || !composerActionSlotLayout.size) return;
3898
+ try {
3899
+ localStorage.setItem(COMPOSER_ACTION_LAYOUT_STORAGE_KEY, JSON.stringify({
3900
+ version: 2,
3901
+ columns: composerActionLayoutColumns,
3902
+ positions: Object.fromEntries(composerActionSlotLayout),
3903
+ }));
3904
+ } catch {
3905
+ // Ignore storage failures; sparse placement should still work for this page load.
3906
+ }
3907
+ markDurableUiLayoutDirty("composerActions");
3908
+ }
3909
+
3910
+ function remapComposerActionSlot(record, slot, sourceColumns, targetColumns) {
3911
+ const sourceRow = Math.floor(slot / sourceColumns);
3912
+ const sourceColumn = slot % sourceColumns;
3913
+ const sourceMaxColumn = Math.max(0, sourceColumns - record.span);
3914
+ const targetMaxColumn = Math.max(0, targetColumns - record.span);
3915
+ const relativeColumn = sourceMaxColumn > 0 ? Math.min(sourceColumn, sourceMaxColumn) / sourceMaxColumn : 0;
3916
+ return sourceRow * targetColumns + Math.round(relativeColumn * targetMaxColumn);
3917
+ }
3918
+
3919
+ function nearestAvailableComposerActionSlot(record, preferredSlot, layout, columns) {
3920
+ if (record.span > columns) return null;
3921
+ const preferredRow = Math.floor(preferredSlot / columns);
3922
+ const preferredColumn = preferredSlot % columns;
3923
+ const maxColumn = columns - record.span;
3924
+ const columnsByDistance = Array.from({ length: maxColumn + 1 }, (_, column) => column)
3925
+ .sort((a, b) => Math.abs(a - preferredColumn) - Math.abs(b - preferredColumn) || a - b);
3926
+ const maxRow = preferredRow + composerActionRecords().length;
3927
+ for (let row = preferredRow; row <= maxRow; row += 1) {
3928
+ for (const column of columnsByDistance) {
3929
+ const candidate = row * columns + column;
3930
+ if (composerActionSlotCanFit(record, candidate, layout, columns)) return candidate;
3931
+ }
3932
+ }
3933
+ return null;
3934
+ }
3935
+
3936
+ function restoreComposerActionSlotLayout() {
3937
+ if (isMobileView()) return;
3938
+ const stored = readStoredComposerActionLayout();
3939
+ const columns = composerActionGridColumnCount();
3940
+ composerActionSlotLayout = new Map();
3941
+ composerActionLayoutColumns = columns;
3942
+ if (!stored) {
3943
+ applyComposerActionSlotLayout();
3944
+ return;
3945
+ }
3946
+ const records = new Map(composerActionRecords().map((record) => [record.id, record]));
3947
+ for (const [id, storedSlot] of [...stored.positions].sort((a, b) => a[1] - b[1])) {
3948
+ const record = records.get(id);
3949
+ if (!record || record.root.hidden || !record.root.getClientRects().length) continue;
3950
+ const preferredSlot = stored.columns === columns
3951
+ ? storedSlot
3952
+ : remapComposerActionSlot(record, storedSlot, stored.columns, columns);
3953
+ const slot = nearestAvailableComposerActionSlot(record, preferredSlot, composerActionSlotLayout, columns);
3954
+ if (slot !== null) composerActionSlotLayout.set(id, slot);
3955
+ }
3956
+ applyComposerActionSlotLayout();
3957
+ }
3958
+
3959
+ function scheduleComposerActionSlotLayoutRestore() {
3960
+ if (composerActionPointerDrag?.active || composerActionLayoutRestoreFrame !== null) return;
3961
+ const restore = () => {
3962
+ composerActionLayoutRestoreFrame = null;
3963
+ if (!composerActionPointerDrag?.active) restoreComposerActionSlotLayout();
3964
+ };
3965
+ composerActionLayoutRestoreFrame = typeof requestAnimationFrame === "function"
3966
+ ? requestAnimationFrame(restore)
3967
+ : setTimeout(restore, 0);
3968
+ }
3969
+
3970
+ function captureComposerActionSlotLayout() {
3971
+ const cells = Array.from(elements.composerActionGridGuide?.children || []);
3972
+ if (!cells.length) return;
3973
+ composerActionLayoutColumns = composerActionGridColumnCount();
3974
+ const nextLayout = new Map();
3975
+ for (const record of orderedComposerActionRecords({ visibleOnly: true })) {
3976
+ const actionRect = record.root.getBoundingClientRect();
3977
+ const slot = cells.findIndex((cell) => {
3978
+ const rect = cell.getBoundingClientRect();
3979
+ const centerX = rect.left + rect.width / 2;
3980
+ const centerY = rect.top + rect.height / 2;
3981
+ return centerX >= actionRect.left - 1 && centerX <= actionRect.right + 1 && centerY >= actionRect.top - 1 && centerY <= actionRect.bottom + 1;
3982
+ });
3983
+ if (slot >= 0) nextLayout.set(record.id, slot);
3984
+ }
3985
+ composerActionSlotLayout = nextLayout;
3986
+ applyComposerActionSlotLayout();
3987
+ }
3988
+
3989
+ function repackComposerActionSlotLayout() {
3990
+ if (composerActionLayoutColumns < 1) return;
3991
+ const nextLayout = new Map();
3992
+ let slot = 0;
3993
+ for (const record of orderedComposerActionRecords({ visibleOnly: true })) {
3994
+ const column = slot % composerActionLayoutColumns;
3995
+ if (column + record.span > composerActionLayoutColumns) slot += composerActionLayoutColumns - column;
3996
+ nextLayout.set(record.id, slot);
3997
+ slot += record.span;
3998
+ }
3999
+ composerActionSlotLayout = nextLayout;
4000
+ applyComposerActionSlotLayout();
4001
+ persistComposerActionSlotLayout();
4002
+ }
4003
+
4004
+ function syncComposerActionOrderFromSlots() {
4005
+ const visibleIds = orderedComposerActionRecords({ visibleOnly: true })
4006
+ .filter(({ id }) => composerActionSlotLayout.has(id))
4007
+ .sort((a, b) => composerActionSlotLayout.get(a.id) - composerActionSlotLayout.get(b.id))
4008
+ .map(({ id }) => id);
4009
+ const completeOrder = [
4010
+ ...visibleIds,
4011
+ ...orderedComposerActionRecords().map(({ id }) => id).filter((id) => !visibleIds.includes(id)),
4012
+ ];
4013
+ applyComposerActionOrder(completeOrder);
4014
+ persistComposerActionOrder();
4015
+ }
4016
+
4017
+ function moveComposerActionToGridCell(actionId, cell) {
4018
+ const record = composerActionRecords().find(({ id }) => id === actionId);
4019
+ const slot = Number(cell?.dataset.composerActionGridCell);
4020
+ if (!record || !Number.isInteger(slot)) return false;
4021
+ const nextLayout = new Map(composerActionSlotLayout);
4022
+ nextLayout.delete(actionId);
4023
+ if (!composerActionSlotCanFit(record, slot, nextLayout)) return false;
4024
+ nextLayout.set(actionId, slot);
4025
+ composerActionSlotLayout = nextLayout;
4026
+ applyComposerActionSlotLayout();
4027
+ syncComposerActionOrderFromSlots();
4028
+ clearComposerActionDragMarkers();
4029
+ cell.classList.add("composer-action-grid-cell-target");
4030
+ composerActionLastDragOverKey = `cell:${slot}`;
4031
+ persistComposerActionSlotLayout();
4032
+ return true;
4033
+ }
4034
+
4035
+ function clearComposerActionDragMarkers() {
4036
+ for (const { root } of composerActionRecords()) {
4037
+ root.classList.remove("composer-action-drag-before", "composer-action-drag-after");
4038
+ }
4039
+ for (const cell of elements.composerActionGridGuide?.children || []) {
4040
+ cell.classList.remove("composer-action-grid-cell-target");
4041
+ }
4042
+ }
4043
+
4044
+ function showComposerActionGridGuide() {
4045
+ const row = elements.composerRow;
4046
+ const guide = elements.composerActionGridGuide;
4047
+ if (!row || !guide) return;
4048
+ const columnCount = composerActionGridColumnCount();
4049
+ const rowTops = orderedComposerActionRecords({ visibleOnly: true })
4050
+ .map(({ root }) => root.getBoundingClientRect().top)
4051
+ .sort((a, b) => a - b)
4052
+ .reduce((groups, top) => {
4053
+ if (!groups.length || top - groups.at(-1) > 4) groups.push(top);
4054
+ return groups;
4055
+ }, []);
4056
+ const rowCount = Math.max(1, rowTops.length);
4057
+ const fragment = document.createDocumentFragment();
4058
+ for (let index = 0; index < columnCount * rowCount; index += 1) {
4059
+ const cell = document.createElement("span");
4060
+ cell.className = "composer-action-grid-cell";
4061
+ cell.dataset.composerActionGridCell = String(index);
4062
+ fragment.append(cell);
4063
+ }
4064
+ guide.style.setProperty("--composer-action-grid-rows", String(rowCount));
4065
+ guide.replaceChildren(fragment);
4066
+ guide.hidden = false;
4067
+ document.body.classList.add("composer-action-drag-active");
4068
+ }
4069
+
4070
+ function hideComposerActionGridGuide() {
4071
+ document.body.classList.remove("composer-action-drag-active");
4072
+ if (elements.composerActionGridGuide) elements.composerActionGridGuide.hidden = true;
4073
+ }
4074
+
4075
+ function composerActionGridCellFromPoint(clientX, clientY) {
4076
+ for (const cell of elements.composerActionGridGuide?.children || []) {
4077
+ const rect = cell.getBoundingClientRect();
4078
+ if (clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom) return cell;
4079
+ }
4080
+ return null;
4081
+ }
4082
+
4083
+ function moveComposerActionRelative(fromId, targetId, insertBefore) {
4084
+ if (!fromId || !targetId || fromId === targetId) return false;
4085
+ const order = orderedComposerActionRecords().map(({ id }) => id).filter((id) => id !== fromId);
4086
+ const targetIndex = order.indexOf(targetId);
4087
+ if (targetIndex < 0) return false;
4088
+ order.splice(targetIndex + (insertBefore ? 0 : 1), 0, fromId);
4089
+ applyComposerActionOrder(order);
4090
+ if (composerActionSlotLayout.size) repackComposerActionSlotLayout();
4091
+ clearComposerActionDragMarkers();
4092
+ const targetRecord = composerActionRecords().find(({ id }) => id === targetId);
4093
+ targetRecord?.root.classList.add(insertBefore ? "composer-action-drag-before" : "composer-action-drag-after");
4094
+ composerActionLastDragOverKey = `${targetId}:${insertBefore ? "before" : "after"}`;
4095
+ persistComposerActionOrder();
4096
+ return true;
4097
+ }
4098
+
4099
+ function composerActionLabel(record) {
4100
+ return record?.focusTarget?.getAttribute("aria-label")
4101
+ || record?.focusTarget?.textContent?.trim()
4102
+ || record?.focusTarget?.getAttribute("title")
4103
+ || record?.id
4104
+ || "Action";
4105
+ }
4106
+
4107
+ function announceComposerActionPosition(actionId) {
4108
+ if (!elements.composerActionOrderStatus) return;
4109
+ const records = orderedComposerActionRecords({ visibleOnly: true });
4110
+ const index = records.findIndex(({ id }) => id === actionId);
4111
+ const record = records[index];
4112
+ if (!record || index < 0) return;
4113
+ elements.composerActionOrderStatus.textContent = `${composerActionLabel(record)} moved to position ${index + 1} of ${records.length}.`;
4114
+ }
4115
+
4116
+ function moveComposerActionByOffset(actionId, offset) {
4117
+ const records = orderedComposerActionRecords({ visibleOnly: true });
4118
+ const fromIndex = records.findIndex(({ id }) => id === actionId);
4119
+ const toIndex = fromIndex + offset;
4120
+ if (fromIndex < 0 || toIndex < 0 || toIndex >= records.length) return false;
4121
+ const moved = moveComposerActionRelative(actionId, records[toIndex].id, offset < 0);
4122
+ clearComposerActionDragMarkers();
4123
+ if (moved) {
4124
+ announceComposerActionPosition(actionId);
4125
+ queueMicrotask(() => composerActionRecords().find(({ id }) => id === actionId)?.focusTarget.focus({ preventScroll: true }));
4126
+ }
4127
+ return moved;
4128
+ }
4129
+
4130
+ function composerActionRootFromPoint(clientX, clientY) {
4131
+ return document.elementFromPoint(clientX, clientY)?.closest?.("[data-composer-action-id]") || null;
4132
+ }
4133
+
4134
+ function beginComposerActionPointerDrag(event, actionId) {
4135
+ if (event.button !== 0 || isMobileView() || !actionId || composerActionPointerDrag) return;
4136
+ if (event.target?.closest?.(".composer-publish-menu-panel, input, select, textarea, a")) return;
4137
+ composerActionPointerDrag = { actionId, pointerId: event.pointerId, startX: event.clientX, startY: event.clientY, active: false };
4138
+ window.addEventListener("pointermove", updateComposerActionPointerDrag, { capture: true });
4139
+ window.addEventListener("pointerup", endComposerActionPointerDrag, { capture: true });
4140
+ window.addEventListener("pointercancel", endComposerActionPointerDrag, { capture: true });
4141
+ }
4142
+
4143
+ function updateComposerActionPointerDrag(event) {
4144
+ const drag = composerActionPointerDrag;
4145
+ if (!drag || drag.pointerId !== event.pointerId) return;
4146
+ const distance = Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY);
4147
+ if (!drag.active && distance < COMPOSER_ACTION_POINTER_DRAG_THRESHOLD_PX) return;
4148
+ event.preventDefault();
4149
+ if (!drag.active) {
4150
+ drag.active = true;
4151
+ composerActionLastDragOverKey = "";
4152
+ clearTimeout(pointerActivationTimeout);
4153
+ pointerActivationTimeout = null;
4154
+ activePointerActivation = null;
4155
+ composerActionRecords().find(({ id }) => id === drag.actionId)?.root.classList.add("composer-action-dragging");
4156
+ showComposerActionGridGuide();
4157
+ captureComposerActionSlotLayout();
4158
+ }
4159
+ const targetRoot = composerActionRootFromPoint(event.clientX, event.clientY);
4160
+ const targetRecord = targetRoot
4161
+ ? composerActionRecords().find(({ root }) => root === targetRoot)
4162
+ : null;
4163
+ if (targetRecord?.id === drag.actionId) {
4164
+ drag.pendingRelative = null;
4165
+ if (!composerActionLastDragOverKey.startsWith("cell:")) {
4166
+ clearComposerActionDragMarkers();
4167
+ composerActionLastDragOverKey = "";
4168
+ }
4169
+ return;
4170
+ }
4171
+ if (targetRecord && !targetRecord.root.hidden) {
4172
+ const rect = targetRoot.getBoundingClientRect();
4173
+ const insertBefore = event.clientX < rect.left + rect.width / 2;
4174
+ const markerKey = `${targetRecord.id}:${insertBefore ? "before" : "after"}`;
4175
+ if (markerKey === composerActionLastDragOverKey) return;
4176
+ clearComposerActionDragMarkers();
4177
+ targetRecord.root.classList.add(insertBefore ? "composer-action-drag-before" : "composer-action-drag-after");
4178
+ composerActionLastDragOverKey = markerKey;
4179
+ drag.pendingRelative = { targetId: targetRecord.id, insertBefore };
4180
+ return;
4181
+ }
4182
+ const gridCell = composerActionGridCellFromPoint(event.clientX, event.clientY);
4183
+ if (!gridCell) return;
4184
+ const markerKey = `cell:${gridCell.dataset.composerActionGridCell}`;
4185
+ if (markerKey === composerActionLastDragOverKey) return;
4186
+ drag.pendingRelative = null;
4187
+ moveComposerActionToGridCell(drag.actionId, gridCell);
4188
+ }
4189
+
4190
+ function endComposerActionPointerDrag(event) {
4191
+ const drag = composerActionPointerDrag;
4192
+ if (!drag || drag.pointerId !== event.pointerId) return;
4193
+ window.removeEventListener("pointermove", updateComposerActionPointerDrag, { capture: true });
4194
+ window.removeEventListener("pointerup", endComposerActionPointerDrag, { capture: true });
4195
+ window.removeEventListener("pointercancel", endComposerActionPointerDrag, { capture: true });
4196
+ const sourceRecord = composerActionRecords().find(({ id }) => id === drag.actionId);
4197
+ if (drag.active && event.type === "pointerup" && drag.pendingRelative) {
4198
+ moveComposerActionRelative(drag.actionId, drag.pendingRelative.targetId, drag.pendingRelative.insertBefore);
4199
+ }
4200
+ composerActionPointerDrag = null;
4201
+ composerActionLastDragOverKey = "";
4202
+ clearComposerActionDragMarkers();
4203
+ sourceRecord?.root.classList.remove("composer-action-dragging");
4204
+ hideComposerActionGridGuide();
4205
+ if (drag.active) {
4206
+ composerActionSuppressClickUntil = Date.now() + 250;
4207
+ event.preventDefault();
4208
+ persistComposerActionOrder();
4209
+ persistComposerActionSlotLayout();
4210
+ announceComposerActionPosition(drag.actionId);
4211
+ queueMicrotask(() => sourceRecord?.focusTarget.focus({ preventScroll: true }));
4212
+ }
4213
+ }
4214
+
4215
+ function syncComposerActionGridAvailability() {
4216
+ document.body.classList.toggle("composer-action-grid-enabled", !isMobileView());
4217
+ }
4218
+
4219
+ function initializeComposerActionOrdering() {
4220
+ syncComposerActionGridAvailability();
4221
+ restoreComposerActionOrder();
4222
+ restoreComposerActionSlotLayout();
4223
+ const layoutObserver = new MutationObserver((mutations) => {
4224
+ if (mutations.some((mutation) => mutation.type === "childList" || mutation.target.matches?.("[data-composer-action-id]"))) {
4225
+ scheduleComposerActionSlotLayoutRestore();
4226
+ }
4227
+ });
4228
+ layoutObserver.observe(elements.composerRow, { childList: true, subtree: true, attributes: true, attributeFilter: ["hidden"] });
4229
+ if (typeof ResizeObserver === "function") {
4230
+ let observedRowWidth = elements.composerRow.getBoundingClientRect().width;
4231
+ const rowResizeObserver = new ResizeObserver(([entry]) => {
4232
+ const nextWidth = entry?.contentRect?.width ?? elements.composerRow.getBoundingClientRect().width;
4233
+ if (Math.abs(nextWidth - observedRowWidth) < 0.5) return;
4234
+ observedRowWidth = nextWidth;
4235
+ scheduleComposerActionSlotLayoutRestore();
4236
+ });
4237
+ rowResizeObserver.observe(elements.composerRow);
4238
+ }
4239
+ window.addEventListener("resize", scheduleComposerActionSlotLayoutRestore);
4240
+ for (const record of composerActionRecords()) {
4241
+ record.focusTarget.setAttribute("aria-keyshortcuts", "Alt+ArrowLeft Alt+ArrowRight Alt+ArrowUp Alt+ArrowDown");
4242
+ record.focusTarget.addEventListener("keydown", (event) => {
4243
+ if (isMobileView() || !event.altKey || !["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) return;
4244
+ event.preventDefault();
4245
+ moveComposerActionByOffset(record.id, ["ArrowLeft", "ArrowUp"].includes(event.key) ? -1 : 1);
4246
+ });
4247
+ record.root.addEventListener("pointerdown", (event) => beginComposerActionPointerDrag(event, record.id));
4248
+ record.root.addEventListener("click", (event) => {
4249
+ if (Date.now() >= composerActionSuppressClickUntil) return;
4250
+ event.preventDefault();
4251
+ event.stopImmediatePropagation();
4252
+ }, { capture: true });
4253
+ }
4254
+ }
4255
+
3698
4256
  function bindSidePanelContextMenu() {
3699
4257
  elements.sidePanel?.addEventListener("contextmenu", showSidePanelContextMenu);
3700
4258
  elements.sidePanel?.addEventListener("keydown", (event) => {
@@ -3813,6 +4371,7 @@ function persistTerminalTabsLayout(layout) {
3813
4371
  } catch {
3814
4372
  // Ignore storage failures; the layout control should still work for this page load.
3815
4373
  }
4374
+ markDurableUiLayoutDirty("terminalTabs", "layout");
3816
4375
  }
3817
4376
 
3818
4377
  function readStoredToolOutputExpanded() {
@@ -3906,6 +4465,36 @@ function restoreSubagentOpenModeSetting() {
3906
4465
  setSubagentOpenMode(readStoredSubagentOpenMode(), { persist: false });
3907
4466
  }
3908
4467
 
4468
+ function readStoredSubagentAutoClearEnabled() {
4469
+ try {
4470
+ return localStorage.getItem(SUBAGENT_AUTO_CLEAR_STORAGE_KEY) === "1";
4471
+ } catch {
4472
+ return false;
4473
+ }
4474
+ }
4475
+
4476
+ function persistSubagentAutoClearEnabled(enabled) {
4477
+ try {
4478
+ localStorage.setItem(SUBAGENT_AUTO_CLEAR_STORAGE_KEY, enabled ? "1" : "0");
4479
+ } catch {
4480
+ // Ignore storage failures; the preference still applies for this page load.
4481
+ }
4482
+ }
4483
+
4484
+ function setSubagentAutoClearEnabled(enabled, { persist = true, announce = false } = {}) {
4485
+ subagentAutoClearEnabled = Boolean(enabled);
4486
+ if (persist) persistSubagentAutoClearEnabled(subagentAutoClearEnabled);
4487
+ renderSubagents();
4488
+ if (announce) addEvent(`subagent auto-clear ${subagentAutoClearEnabled ? "enabled" : "disabled"}`, "info");
4489
+ if (subagentAutoClearEnabled && !subagentsLoading && !subagentsClearingFinished && finishedSubagentRunSelections().length) {
4490
+ void clearFinishedSubagentRuns({ automatic: true });
4491
+ }
4492
+ }
4493
+
4494
+ function restoreSubagentAutoClearSetting() {
4495
+ setSubagentAutoClearEnabled(readStoredSubagentAutoClearEnabled(), { persist: false });
4496
+ }
4497
+
3909
4498
  function normalizeTerminalCustomGroupTitle(value, fallback = "Custom group") {
3910
4499
  const title = String(value || "").replace(/\s+/g, " ").trim();
3911
4500
  return (title || fallback).slice(0, 40);
@@ -3967,6 +4556,7 @@ function persistTerminalCustomGroups() {
3967
4556
  } catch {
3968
4557
  // Ignore storage failures; custom tab groups still work for this page load.
3969
4558
  }
4559
+ markDurableUiLayoutDirty("terminalTabs", "customGroups");
3970
4560
  }
3971
4561
 
3972
4562
  function workspaceGroupsForSave() {
@@ -4846,22 +5436,134 @@ function normalizeFeatureCategory(value) {
4846
5436
  return value === "lightweight-feature" || value === "complex-feature" ? value : "";
4847
5437
  }
4848
5438
 
5439
+ function normalizeFeatureDecisionKind(value) {
5440
+ return value === "feature_lightweight" || value === "feature_complex" ? value : "";
5441
+ }
5442
+
5443
+ function normalizeFeatureDecisionReason(value) {
5444
+ if (typeof value !== "string") return "";
5445
+ return value
5446
+ .replace(/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, " ")
5447
+ .replace(/\s+/g, " ")
5448
+ .trim()
5449
+ .slice(0, FEATURE_DECISION_REASON_MAX_CHARS)
5450
+ .trimEnd();
5451
+ }
5452
+
5453
+ // Accepts the structured {kind,reason} classifier payload and the legacy exact label.
5454
+ // Every other payload fails closed so the popup stays unavailable.
5455
+ function parseFeatureDecisionPayload(value) {
5456
+ if (typeof value !== "string" || !value || value.length > FEATURE_DECISION_PAYLOAD_MAX_CHARS) return null;
5457
+ const legacyKind = normalizeFeatureDecisionKind(value);
5458
+ if (legacyKind) return { kind: legacyKind, reason: "" };
5459
+ if (!value.startsWith("{")) return null;
5460
+ let parsed;
5461
+ try {
5462
+ parsed = JSON.parse(value);
5463
+ } catch {
5464
+ return null;
5465
+ }
5466
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
5467
+ const keys = Object.keys(parsed);
5468
+ if (keys.length !== 2 || !keys.includes("kind") || !keys.includes("reason")) return null;
5469
+ if (typeof parsed.reason !== "string") return null;
5470
+ const kind = normalizeFeatureDecisionKind(parsed.kind);
5471
+ const reason = normalizeFeatureDecisionReason(parsed.reason);
5472
+ return kind && reason ? { kind, reason } : null;
5473
+ }
5474
+
5475
+ function featureDecisionKindLabel(kind) {
5476
+ return kind === "feature_complex" ? "Complex feature" : "Lightweight feature";
5477
+ }
5478
+
5479
+ function formatFeatureDecisionText(decision) {
5480
+ if (!decision) return "";
5481
+ const reason = decision.reason || `The classifier reported ${decision.kind} without a reason.`;
5482
+ return `Decision: ${featureDecisionKindLabel(decision.kind)} (${decision.kind})\nReason: ${reason}`;
5483
+ }
5484
+
5485
+ function featureDecisionForTab(tabId) {
5486
+ const category = normalizeFeatureCategory(featureCategoryByTab.get(tabId));
5487
+ const decision = featureDecisionOutputByTab.get(tabId) || null;
5488
+ if (!decision || !normalizeFeatureDecisionKind(decision.kind)) return null;
5489
+ if (category === "lightweight-feature" && decision.kind === "feature_lightweight") return decision;
5490
+ if (category === "complex-feature" && decision.kind === "feature_complex") return decision;
5491
+ return null;
5492
+ }
5493
+
5494
+ function featureDecisionOutputForTab(tabId) {
5495
+ return formatFeatureDecisionText(featureDecisionForTab(tabId));
5496
+ }
5497
+
5498
+ function closeFeatureDecisionDialog({ restoreFocus = true } = {}) {
5499
+ const dialog = elements.featureDecisionDialog;
5500
+ if (!dialog?.open) {
5501
+ featureDecisionDialogTabId = null;
5502
+ if (elements.featureDecisionDialogOutput) elements.featureDecisionDialogOutput.textContent = "";
5503
+ return;
5504
+ }
5505
+ if (!restoreFocus) modalSurfaceState.delete(dialog);
5506
+ dialog.close();
5507
+ }
5508
+
5509
+ function syncFeatureDecisionDialog() {
5510
+ const dialog = elements.featureDecisionDialog;
5511
+ if (!dialog?.open) return;
5512
+ const output = featureDecisionOutputForTab(featureDecisionDialogTabId);
5513
+ if (featureDecisionDialogTabId !== activeTabId || !output || elements.featureDecisionDialogOutput?.textContent !== output) {
5514
+ closeFeatureDecisionDialog({ restoreFocus: false });
5515
+ }
5516
+ }
5517
+
5518
+ function openFeatureDecisionDialog() {
5519
+ const tabId = activeTabId;
5520
+ const output = featureDecisionOutputForTab(tabId);
5521
+ const dialog = elements.featureDecisionDialog;
5522
+ if (!tabId || !output || !dialog || !elements.featureDecisionDialogOutput) return;
5523
+ featureDecisionDialogTabId = tabId;
5524
+ elements.featureDecisionDialogOutput.textContent = output;
5525
+ if (!dialog.open) dialog.showModal();
5526
+ queueMicrotask(() => elements.featureDecisionDialogCloseButton?.focus({ preventScroll: true }));
5527
+ }
5528
+
5529
+ function clearFeatureDecisionStateForTab(tabId, { render = false } = {}) {
5530
+ if (!tabId) return;
5531
+ featureCategoryByTab.delete(tabId);
5532
+ featureDecisionOutputByTab.delete(tabId);
5533
+ if (featureDecisionDialogTabId === tabId) closeFeatureDecisionDialog({ restoreFocus: false });
5534
+ if (render && tabId === activeTabId) renderFeatureCategoryTag(tabId);
5535
+ }
5536
+
4849
5537
  function renderFeatureCategoryTag(tabId = activeTabId) {
4850
5538
  const tag = elements.featureCategoryTag;
4851
5539
  if (!tag) return;
4852
5540
  const category = normalizeFeatureCategory(featureCategoryByTab.get(tabId));
5541
+ const output = featureDecisionOutputForTab(tabId);
4853
5542
  tag.hidden = !category;
5543
+ tag.disabled = !output;
4854
5544
  tag.textContent = category;
5545
+ tag.setAttribute("aria-label", output ? `Show classifier decision and reason for ${category}` : category || "Feature category");
4855
5546
  tag.classList.toggle("lightweight-feature", category === "lightweight-feature");
4856
5547
  tag.classList.toggle("complex-feature", category === "complex-feature");
5548
+ syncFeatureDecisionDialog();
5549
+ }
5550
+
5551
+ function handleFeatureDecisionOutputStatus(statusText, tabId = activeTabId) {
5552
+ if (!tabId) return;
5553
+ const decision = parseFeatureDecisionPayload(statusText);
5554
+ if (decision) featureDecisionOutputByTab.set(tabId, decision);
5555
+ else featureDecisionOutputByTab.delete(tabId);
5556
+ if (tabId === activeTabId) renderFeatureCategoryTag(tabId);
5557
+ else if (featureDecisionDialogTabId === tabId) syncFeatureDecisionDialog();
4857
5558
  }
4858
5559
 
4859
5560
  function handleFeatureCategoryStatus(statusText, tabId = activeTabId) {
4860
5561
  if (!tabId) return;
4861
5562
  const category = normalizeFeatureCategory(statusText);
4862
5563
  if (category) featureCategoryByTab.set(tabId, category);
4863
- else featureCategoryByTab.delete(tabId);
5564
+ else clearFeatureDecisionStateForTab(tabId);
4864
5565
  if (tabId === activeTabId) renderFeatureCategoryTag(tabId);
5566
+ else if (featureDecisionDialogTabId === tabId) syncFeatureDecisionDialog();
4865
5567
  }
4866
5568
 
4867
5569
  function trackSkillUsage(tabId, skillName, kind = "used", source = "", details = {}) {
@@ -5247,6 +5949,7 @@ function updateComposerModeButtons() {
5247
5949
  }
5248
5950
  renderBusyPromptBehaviorTag();
5249
5951
  document.body.classList.toggle("pi-run-active", runActive || abortAvailable);
5952
+ scheduleComposerActionSlotLayoutRestore();
5250
5953
  }
5251
5954
 
5252
5955
  function scheduleComposerModeButtonsUpdate() {
@@ -5572,6 +6275,7 @@ function setSidePanelCollapsed(collapsed, { persist = true, focusPanel = false }
5572
6275
  } catch {
5573
6276
  // Ignore storage failures; the toggle should still work for this page load.
5574
6277
  }
6278
+ markDurableUiLayoutDirty("sidePanel", "collapsed");
5575
6279
  }
5576
6280
 
5577
6281
  function restoreSidePanelState() {
@@ -5581,7 +6285,7 @@ function restoreSidePanelState() {
5581
6285
  return;
5582
6286
  }
5583
6287
  const stored = readStoredSidePanelCollapsed();
5584
- setSidePanelCollapsed(stored ?? false, { persist: stored !== null });
6288
+ setSidePanelCollapsed(stored ?? false, { persist: false });
5585
6289
  }
5586
6290
 
5587
6291
  function readStoredWorkspaceDashboardCollapsed() {
@@ -5649,6 +6353,7 @@ function bindMobileViewChanges() {
5649
6353
  if (!mobileViewMedia) return;
5650
6354
  const syncForViewport = (event) => {
5651
6355
  applyMobileShellViewport();
6356
+ syncComposerActionGridAvailability();
5652
6357
  if (isMobileShellV2Active()) return;
5653
6358
  setComposerActionsOpen(false);
5654
6359
  setMobileFooterExpanded(false);
@@ -6480,8 +7185,8 @@ function renderUpdateNotification(status = latestUpdateStatus, { force = false }
6480
7185
  if (elements.updateNotificationMessage) {
6481
7186
  let message = "Updates are available. Direct Web UI updates are only enabled from localhost on the host machine.";
6482
7187
  if (canRunUpdate) {
6483
- if (hasPiUpdate && hasPackageUpdate) message = "Run pi update --self for Pi only, or update all to use pi update --all when supported and include Web UI, Optional Features, configured Pi packages, and detected Pi package roots, then restart this Web UI server automatically.";
6484
- else if (hasPackageUpdate) message = "Update all checks for pi update --all support, then refreshes Web UI/package entries, Optional Features, configured Pi packages, and detected Pi package roots before restarting this Web UI server automatically.";
7188
+ if (hasPiUpdate && hasPackageUpdate) message = "Run pi update --self for Pi only, or update all to use Pi for configured packages and Optional Features while refreshing detected core Pi/Web UI package roots, then restart this Web UI server automatically.";
7189
+ else if (hasPackageUpdate) message = "Update all uses Pi for configured packages and Optional Features, then refreshes detected core Pi/Web UI package roots before restarting this Web UI server automatically.";
6485
7190
  else message = "Run pi update --self for Pi only, then restart this Web UI server automatically.";
6486
7191
  }
6487
7192
  elements.updateNotificationMessage.textContent = message;
@@ -6723,8 +7428,8 @@ function piUpdateConfirmationText({ all = false } = {}) {
6723
7428
  const workingWarning = hasWorkingTab() ? "\n\nOne or more Pi tabs look busy or blocked. Finish or abort in-flight work before updating if you need to preserve it." : "";
6724
7429
  const versionText = items.length ? `\n\nDetected update: ${items.join(" · ")}.` : "";
6725
7430
  const commandText = all ? '"pi update --all" when supported, otherwise "pi update --self" followed by "pi update --extensions"' : '"pi update --self"';
6726
- const scope = all ? "Pi, configured packages, Optional Features, and detected Pi package roots" : "Pi only";
6727
- const extra = all ? " It will also run npm/bun package updates for detected Web UI, Optional Feature, agent, project, and global Pi package roots." : "";
7431
+ const scope = all ? "Pi, configured packages including Optional Features, and detected core Pi/Web UI package roots" : "Pi only";
7432
+ const extra = all ? " Pi owns configured Optional Feature updates; direct npm/bun updates are limited to detected core Pi/Web UI package roots." : "";
6728
7433
  return `Run ${scope} now?${versionText}\n\nThis will run ${commandText} on the Web UI host.${extra} After it finishes, Pi Web UI will restart itself. Browser clients will briefly disconnect, and managed Pi tabs/RPC processes will be restarted from saved session state when possible.${workingWarning}`;
6729
7434
  }
6730
7435
 
@@ -8556,6 +9261,7 @@ async function handleVoiceConversationTurnEnd(tabContext = activeTabContext()) {
8556
9261
 
8557
9262
  function renderOptionalFeatureDependentDisplays() {
8558
9263
  renderOptionalFeatureControls();
9264
+ if (elements.optionalFeatureMigrationDialog?.open) renderOptionalFeatureMigrationDialog();
8559
9265
  renderThemeSelect();
8560
9266
  renderWidgets();
8561
9267
  renderStatus();
@@ -9060,10 +9766,15 @@ function activeTabContext(tabId = activeTabId) {
9060
9766
 
9061
9767
  function setActiveTabId(tabId, { remember = false } = {}) {
9062
9768
  const nextTabId = tabId || null;
9063
- if (nextTabId !== activeTabId) activeTabGeneration += 1;
9769
+ if (nextTabId !== activeTabId) {
9770
+ activeTabGeneration += 1;
9771
+ closeFeatureDecisionDialog({ restoreFocus: false });
9772
+ closeSessionSummaryOverlay({ restoreFocus: false });
9773
+ }
9064
9774
  activeTabId = nextTabId;
9065
9775
  bindGitWorkflowToActiveTab();
9066
9776
  renderFeatureCategoryTag(nextTabId);
9777
+ renderSessionSummaryControls();
9067
9778
  if (remember) rememberActiveTab();
9068
9779
  return activeTabContext(nextTabId);
9069
9780
  }
@@ -10101,6 +10812,594 @@ async function moveFileTreeEntry(entry = fileContextMenuState?.entry) {
10101
10812
  await moveFileTreeEntryToDestination(entry, destinationPath, { confirmMove: true });
10102
10813
  }
10103
10814
 
10815
+ // --- Durable UI layout settings -------------------------------------------
10816
+ // Browser storage stays the immediate, offline-capable cache while the durable
10817
+ // per-user layout lives in the WebUI settings file behind
10818
+ // GET/PUT /api/interface-preferences. Local writes always apply first; server
10819
+ // reconciliation is non-blocking, coalesced, and revision guarded.
10820
+ const UI_LAYOUT_SCHEMA_VERSION = 1;
10821
+ const UI_LAYOUT_ENDPOINT = "/api/interface-preferences";
10822
+ const UI_LAYOUT_SAVE_DEBOUNCE_MS = 250;
10823
+ const UI_LAYOUT_MAX_CONFLICT_RETRIES = 1;
10824
+ const UI_LAYOUT_FIELDS = ["sidePanel", "composerActions", "footerScopedModelOrder", "terminalTabs", "fileViewerWidth"];
10825
+ const UI_LAYOUT_SIDE_PANEL_FIELDS = ["sectionOrder", "collapsedSectionIds", "hiddenSectionIds", "collapsed"];
10826
+ const UI_LAYOUT_COMPOSER_FIELDS = ["order", "grid"];
10827
+ const UI_LAYOUT_TERMINAL_FIELDS = ["layout", "customGroups"];
10828
+ const UI_LAYOUT_PENDING_STORAGE_PREFIX = "pi-webui-ui-layout-pending-v3:";
10829
+ const UI_LAYOUT_PENDING_WRITER_ID = globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(16).slice(2)}`;
10830
+ let durableLayoutPendingMutationSerial = 0;
10831
+ const UI_LAYOUT_ID_MAX_LENGTH = 256;
10832
+ const UI_LAYOUT_TITLE_MAX_LENGTH = 160;
10833
+ const UI_LAYOUT_LIST_MAX_ITEMS = 128;
10834
+ const UI_LAYOUT_GROUP_MAX_COUNT = 32;
10835
+ const UI_LAYOUT_GRID_MAX_COLUMNS = 24;
10836
+ const UI_LAYOUT_GRID_MAX_SLOTS = 4096;
10837
+ const UI_LAYOUT_FILE_VIEWER_WIDTH_MAX_PX = 4096;
10838
+ const UI_LAYOUT_UNSAFE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
10839
+ const UI_LAYOUT_CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/;
10840
+
10841
+ let durableLayoutRevision = null;
10842
+ const durableLayoutGenerations = new Map();
10843
+ const durableLayoutDirtyFields = new Map();
10844
+ let durableLayoutSaveTimer = null;
10845
+ let durableLayoutSaveInFlight = false;
10846
+ let durableLayoutConflictAttempts = 0;
10847
+ let durableLayoutWarned = false;
10848
+ let durableLayoutReadEpoch = 0;
10849
+ let durableLayoutAppliedReadEpoch = 0;
10850
+ let durableLayoutWriteFenceReadEpoch = 0;
10851
+
10852
+ function readDurableLayoutCache(key) {
10853
+ try {
10854
+ return localStorage.getItem(key);
10855
+ } catch {
10856
+ return null;
10857
+ }
10858
+ }
10859
+
10860
+ function writeDurableLayoutCache(key, value) {
10861
+ try {
10862
+ localStorage.setItem(key, value);
10863
+ } catch {
10864
+ // Browser storage is only the local cache for the durable layout settings.
10865
+ }
10866
+ }
10867
+
10868
+ function durableLayoutIdList(value) {
10869
+ if (!Array.isArray(value)) return null;
10870
+ const ids = [];
10871
+ const seen = new Set();
10872
+ for (const item of value) {
10873
+ if (typeof item !== "string") continue;
10874
+ const id = item.trim();
10875
+ if (!id || id.length > UI_LAYOUT_ID_MAX_LENGTH || UI_LAYOUT_CONTROL_CHARACTERS.test(id) || seen.has(id)) continue;
10876
+ seen.add(id);
10877
+ ids.push(id);
10878
+ if (ids.length >= UI_LAYOUT_LIST_MAX_ITEMS) break;
10879
+ }
10880
+ return ids;
10881
+ }
10882
+
10883
+ function durableLayoutStoredIdList(key) {
10884
+ const raw = readDurableLayoutCache(key);
10885
+ if (raw === null) return null;
10886
+ try {
10887
+ return durableLayoutIdList(JSON.parse(raw));
10888
+ } catch {
10889
+ return null;
10890
+ }
10891
+ }
10892
+
10893
+ function collectDurableSidePanelLayout() {
10894
+ const collapsed = readStoredSidePanelCollapsed();
10895
+ return {
10896
+ sectionOrder: durableLayoutStoredIdList(SIDE_PANEL_SECTION_ORDER_STORAGE_KEY),
10897
+ collapsedSectionIds: durableLayoutStoredIdList(SIDE_PANEL_SECTION_STORAGE_KEY),
10898
+ hiddenSectionIds: durableLayoutStoredIdList(SIDE_PANEL_SECTION_VISIBILITY_STORAGE_KEY),
10899
+ collapsed: typeof collapsed === "boolean" ? collapsed : null,
10900
+ };
10901
+ }
10902
+
10903
+ function collectDurableComposerActionsLayout() {
10904
+ const stored = readStoredComposerActionLayout();
10905
+ let grid = null;
10906
+ if (stored && Number.isInteger(stored.columns) && stored.columns >= 1 && stored.columns <= UI_LAYOUT_GRID_MAX_COLUMNS) {
10907
+ const positions = {};
10908
+ const usedSlots = new Set();
10909
+ let count = 0;
10910
+ for (const [rawId, slot] of stored.positions) {
10911
+ const id = typeof rawId === "string" ? rawId.trim() : "";
10912
+ if (!id || id.length > UI_LAYOUT_ID_MAX_LENGTH || UI_LAYOUT_CONTROL_CHARACTERS.test(id) || UI_LAYOUT_UNSAFE_KEYS.has(id)) continue;
10913
+ if (!Number.isInteger(slot) || slot < 0 || slot >= UI_LAYOUT_GRID_MAX_SLOTS || usedSlots.has(slot)) continue;
10914
+ usedSlots.add(slot);
10915
+ positions[id] = slot;
10916
+ count += 1;
10917
+ if (count >= UI_LAYOUT_LIST_MAX_ITEMS) break;
10918
+ }
10919
+ grid = { version: 2, columns: stored.columns, positions };
10920
+ }
10921
+ // Composer order and sparse grid always travel together as one logical update.
10922
+ return { order: durableLayoutStoredIdList(COMPOSER_ACTION_ORDER_STORAGE_KEY), grid };
10923
+ }
10924
+
10925
+ function collectDurableTerminalTabsLayout() {
10926
+ const rawLayout = readDurableLayoutCache(TERMINAL_TABS_LAYOUT_STORAGE_KEY);
10927
+ const rawGroups = readDurableLayoutCache(TERMINAL_CUSTOM_GROUPS_STORAGE_KEY);
10928
+ let customGroups = null;
10929
+ if (rawGroups !== null) {
10930
+ let parsed = null;
10931
+ try {
10932
+ parsed = JSON.parse(rawGroups);
10933
+ } catch {
10934
+ parsed = null;
10935
+ }
10936
+ const records = Array.isArray(parsed?.groups) ? parsed.groups : Array.isArray(parsed) ? parsed : [];
10937
+ const groups = [];
10938
+ const groupIds = new Set();
10939
+ const claimedTabIds = new Set();
10940
+ for (const record of records) {
10941
+ const id = String(record?.id || "").trim();
10942
+ if (!id || id.length > UI_LAYOUT_ID_MAX_LENGTH || UI_LAYOUT_CONTROL_CHARACTERS.test(id) || groupIds.has(id)) continue;
10943
+ const title = normalizeTerminalCustomGroupTitle(record?.title).slice(0, UI_LAYOUT_TITLE_MAX_LENGTH).trim();
10944
+ const tabIds = (durableLayoutIdList(normalizeTerminalCustomGroupTabIds(record?.tabIds)) || []).filter((tabId) => {
10945
+ if (claimedTabIds.has(tabId)) return false;
10946
+ claimedTabIds.add(tabId);
10947
+ return true;
10948
+ });
10949
+ if (!title || tabIds.length < 2) continue;
10950
+ groupIds.add(id);
10951
+ groups.push({ id, title, tabIds });
10952
+ if (groups.length >= UI_LAYOUT_GROUP_MAX_COUNT) break;
10953
+ }
10954
+ customGroups = { version: 1, groups };
10955
+ }
10956
+ return { layout: TERMINAL_TABS_LAYOUTS.has(rawLayout) ? rawLayout : null, customGroups };
10957
+ }
10958
+
10959
+ function collectDurableFileViewerWidth() {
10960
+ const width = readStoredFileViewerWidth();
10961
+ if (!Number.isFinite(width)) return null;
10962
+ const rounded = Math.round(width);
10963
+ return rounded >= FILE_VIEWER_WIDTH_MIN_PX && rounded <= UI_LAYOUT_FILE_VIEWER_WIDTH_MAX_PX ? rounded : null;
10964
+ }
10965
+
10966
+ function collectDurableUiLayoutField(field) {
10967
+ switch (field) {
10968
+ case "sidePanel":
10969
+ return collectDurableSidePanelLayout();
10970
+ case "composerActions":
10971
+ return collectDurableComposerActionsLayout();
10972
+ case "footerScopedModelOrder":
10973
+ return durableLayoutStoredIdList(FOOTER_SCOPED_MODEL_ORDER_STORAGE_KEY);
10974
+ case "terminalTabs":
10975
+ return collectDurableTerminalTabsLayout();
10976
+ case "fileViewerWidth":
10977
+ return collectDurableFileViewerWidth();
10978
+ default:
10979
+ return null;
10980
+ }
10981
+ }
10982
+
10983
+ function durableUiLayoutSubFields(field) {
10984
+ if (field === "sidePanel") return UI_LAYOUT_SIDE_PANEL_FIELDS;
10985
+ if (field === "composerActions") return UI_LAYOUT_COMPOSER_FIELDS;
10986
+ if (field === "terminalTabs") return UI_LAYOUT_TERMINAL_FIELDS;
10987
+ return null;
10988
+ }
10989
+
10990
+ function durableUiLayoutValuePresent(value) {
10991
+ return value !== null && value !== undefined;
10992
+ }
10993
+
10994
+ function durableUiLayoutMutationValue(field, subfield = null) {
10995
+ const value = collectDurableUiLayoutField(field);
10996
+ return subfield ? value?.[subfield] ?? null : value;
10997
+ }
10998
+
10999
+ function durableUiLayoutEntryPatch(field, entry) {
11000
+ if (!entry?.subfields?.size) return entry?.value ?? null;
11001
+ return Object.fromEntries([...entry.subfields].map((subfield) => [subfield, entry.value?.[subfield] ?? null]));
11002
+ }
11003
+
11004
+ function durableUiLayoutPendingMutationRecords() {
11005
+ const records = [];
11006
+ try {
11007
+ for (let index = 0; index < localStorage.length; index += 1) {
11008
+ const key = localStorage.key(index);
11009
+ if (!key?.startsWith(UI_LAYOUT_PENDING_STORAGE_PREFIX)) continue;
11010
+ let value;
11011
+ try {
11012
+ value = JSON.parse(localStorage.getItem(key) || "null");
11013
+ } catch {
11014
+ continue;
11015
+ }
11016
+ if (!value || value.version !== 3 || !UI_LAYOUT_FIELDS.includes(value.field)) continue;
11017
+ const allowedSubfields = durableUiLayoutSubFields(value.field);
11018
+ const subfield = typeof value.subfield === "string" ? value.subfield : null;
11019
+ if (subfield && !allowedSubfields?.includes(subfield)) continue;
11020
+ if (allowedSubfields && value.field !== "composerActions" && !subfield) continue;
11021
+ records.push({
11022
+ key,
11023
+ field: value.field,
11024
+ subfield,
11025
+ value: value.value,
11026
+ updatedAt: Number(value.updatedAt) || 0,
11027
+ });
11028
+ }
11029
+ } catch {
11030
+ return [];
11031
+ }
11032
+ return records;
11033
+ }
11034
+
11035
+ function writeDurableUiLayoutPendingMutation(field, subfield, value) {
11036
+ try {
11037
+ durableLayoutPendingMutationSerial += 1;
11038
+ const key = `${UI_LAYOUT_PENDING_STORAGE_PREFIX}${UI_LAYOUT_PENDING_WRITER_ID}:${Date.now().toString(36)}:${durableLayoutPendingMutationSerial.toString(36)}`;
11039
+ localStorage.setItem(key, JSON.stringify({
11040
+ version: 3,
11041
+ field,
11042
+ subfield,
11043
+ value,
11044
+ updatedAt: Date.now(),
11045
+ }));
11046
+ return key;
11047
+ } catch {
11048
+ return null;
11049
+ }
11050
+ }
11051
+
11052
+ function removeDurableUiLayoutPendingMutation(key) {
11053
+ if (!key) return;
11054
+ try {
11055
+ localStorage.removeItem(key);
11056
+ } catch {
11057
+ // A later startup can retry an immutable mutation record that remains.
11058
+ }
11059
+ }
11060
+
11061
+ function clearAcknowledgedDurableUiLayoutPendingMutations(snapshot) {
11062
+ for (const entry of snapshot.values()) {
11063
+ if (entry.subfieldMutationIds?.size) {
11064
+ for (const mutationId of entry.subfieldMutationIds.values()) removeDurableUiLayoutPendingMutation(mutationId);
11065
+ } else {
11066
+ removeDurableUiLayoutPendingMutation(entry.mutationId);
11067
+ }
11068
+ }
11069
+ }
11070
+
11071
+ function restoreDurableUiLayoutPendingJournal() {
11072
+ const records = durableUiLayoutPendingMutationRecords();
11073
+ const candidates = new Map();
11074
+ for (const record of records) {
11075
+ const path = record.subfield ? `${record.field}.${record.subfield}` : record.field;
11076
+ const previous = candidates.get(path);
11077
+ if (!previous || record.updatedAt > previous.updatedAt || (record.updatedAt === previous.updatedAt && record.key > previous.key)) {
11078
+ candidates.set(path, record);
11079
+ }
11080
+ }
11081
+ // Mutation records are immutable. Once a newer record exists for the same
11082
+ // path, older records are safely superseded and can never be rewritten.
11083
+ for (const record of records) {
11084
+ const path = record.subfield ? `${record.field}.${record.subfield}` : record.field;
11085
+ if (candidates.get(path)?.key !== record.key) removeDurableUiLayoutPendingMutation(record.key);
11086
+ }
11087
+
11088
+ for (const field of UI_LAYOUT_FIELDS) {
11089
+ const allowedSubfields = durableUiLayoutSubFields(field);
11090
+ const fieldCandidates = allowedSubfields && field !== "composerActions"
11091
+ ? allowedSubfields.map((subfield) => candidates.get(`${field}.${subfield}`)).filter(Boolean)
11092
+ : [candidates.get(field)].filter(Boolean);
11093
+ if (!fieldCandidates.length) continue;
11094
+ const patch = allowedSubfields && field !== "composerActions"
11095
+ ? Object.fromEntries(fieldCandidates.map((candidate) => [candidate.subfield, candidate.value]))
11096
+ : fieldCandidates[0].value;
11097
+ applyDurableUiLayoutField(field, patch);
11098
+ const generation = durableUiLayoutGeneration(field) + 1;
11099
+ const subfields = allowedSubfields && field !== "composerActions"
11100
+ ? new Set(fieldCandidates.map((candidate) => candidate.subfield))
11101
+ : null;
11102
+ const subfieldGenerations = subfields
11103
+ ? new Map([...subfields].map((subfield) => [subfield, generation]))
11104
+ : null;
11105
+ const subfieldMutationIds = subfields
11106
+ ? new Map(fieldCandidates.map((candidate) => [candidate.subfield, candidate.key]))
11107
+ : null;
11108
+ durableLayoutGenerations.set(field, generation);
11109
+ durableLayoutDirtyFields.set(field, {
11110
+ generation,
11111
+ value: collectDurableUiLayoutField(field),
11112
+ subfields,
11113
+ subfieldGenerations,
11114
+ subfieldMutationIds,
11115
+ mutationId: subfields ? null : fieldCandidates[0].key,
11116
+ });
11117
+ }
11118
+ if (durableLayoutDirtyFields.size) scheduleDurableUiLayoutSave();
11119
+ }
11120
+
11121
+ function applyDurableSidePanelLayout(value) {
11122
+ if (!value) return;
11123
+ if (Array.isArray(value.sectionOrder)) {
11124
+ writeDurableLayoutCache(SIDE_PANEL_SECTION_ORDER_STORAGE_KEY, JSON.stringify(value.sectionOrder));
11125
+ restoreSidePanelSectionOrder();
11126
+ }
11127
+ if (Array.isArray(value.hiddenSectionIds)) {
11128
+ writeDurableLayoutCache(SIDE_PANEL_SECTION_VISIBILITY_STORAGE_KEY, JSON.stringify(value.hiddenSectionIds));
11129
+ restoreSidePanelSectionVisibility();
11130
+ }
11131
+ if (Array.isArray(value.collapsedSectionIds)) {
11132
+ writeDurableLayoutCache(SIDE_PANEL_SECTION_STORAGE_KEY, JSON.stringify(value.collapsedSectionIds));
11133
+ restoreSidePanelSectionState();
11134
+ }
11135
+ if (typeof value.collapsed === "boolean") {
11136
+ writeDurableLayoutCache(SIDE_PANEL_STORAGE_KEY, value.collapsed ? "1" : "0");
11137
+ restoreSidePanelState();
11138
+ }
11139
+ }
11140
+
11141
+ function applyDurableComposerActionsLayout(value) {
11142
+ if (!value) return;
11143
+ if (Array.isArray(value.order)) {
11144
+ writeDurableLayoutCache(COMPOSER_ACTION_ORDER_STORAGE_KEY, JSON.stringify(value.order));
11145
+ restoreComposerActionOrder();
11146
+ }
11147
+ if (value.grid && value.grid.version === 2) {
11148
+ // Keep the saved geometry as the canonical layout. Restore projects its
11149
+ // horizontal positions into the current responsive grid without rewriting
11150
+ // the source slots, so resizing back restores the exact original cells.
11151
+ writeDurableLayoutCache(COMPOSER_ACTION_LAYOUT_STORAGE_KEY, JSON.stringify(value.grid));
11152
+ restoreComposerActionSlotLayout();
11153
+ }
11154
+ }
11155
+
11156
+ function applyDurableFooterScopedModelOrder(value) {
11157
+ if (!Array.isArray(value)) return;
11158
+ writeDurableLayoutCache(FOOTER_SCOPED_MODEL_ORDER_STORAGE_KEY, JSON.stringify(value));
11159
+ footerScopedModels = orderedFooterScopedModels();
11160
+ renderFooter();
11161
+ }
11162
+
11163
+ function applyDurableTerminalTabsLayout(value) {
11164
+ if (!value) return;
11165
+ if (TERMINAL_TABS_LAYOUTS.has(value.layout)) {
11166
+ writeDurableLayoutCache(TERMINAL_TABS_LAYOUT_STORAGE_KEY, value.layout);
11167
+ setTerminalTabsLayout(value.layout, { persist: false });
11168
+ }
11169
+ if (value.customGroups && value.customGroups.version === 1) {
11170
+ writeDurableLayoutCache(TERMINAL_CUSTOM_GROUPS_STORAGE_KEY, JSON.stringify(value.customGroups));
11171
+ restoreTerminalCustomGroups();
11172
+ syncTerminalCustomGroupsWithTabs(tabs, { persist: false });
11173
+ renderTabs();
11174
+ }
11175
+ }
11176
+
11177
+ function applyDurableFileViewerWidth(value) {
11178
+ if (!Number.isFinite(value)) return;
11179
+ const width = Math.round(value);
11180
+ if (width < FILE_VIEWER_WIDTH_MIN_PX) return;
11181
+ writeDurableLayoutCache(FILE_VIEWER_WIDTH_STORAGE_KEY, String(width));
11182
+ restoreFileViewerWidthPreference();
11183
+ if (activeFileViewer && !isSidePanelOverlayView()) applyFileViewerWidth(width);
11184
+ }
11185
+
11186
+ function applyDurableUiLayoutField(field, value) {
11187
+ if (field === "sidePanel") applyDurableSidePanelLayout(value);
11188
+ else if (field === "composerActions") applyDurableComposerActionsLayout(value);
11189
+ else if (field === "footerScopedModelOrder") applyDurableFooterScopedModelOrder(value);
11190
+ else if (field === "terminalTabs") applyDurableTerminalTabsLayout(value);
11191
+ else if (field === "fileViewerWidth") applyDurableFileViewerWidth(value);
11192
+ }
11193
+
11194
+ function durableUiLayoutInteractionActive(field = null) {
11195
+ const activeByField = {
11196
+ sidePanel: Boolean(sidePanelSectionPointerDrag?.active),
11197
+ composerActions: Boolean(composerActionPointerDrag?.active),
11198
+ footerScopedModelOrder: Boolean(footerScopedModelPointerDrag?.active),
11199
+ terminalTabs: Boolean(terminalTabDragId),
11200
+ fileViewerWidth: Boolean(fileViewerResizeState),
11201
+ };
11202
+ return field ? activeByField[field] === true : Object.values(activeByField).some(Boolean);
11203
+ }
11204
+
11205
+ function durableUiLayoutGeneration(field) {
11206
+ return durableLayoutGenerations.get(field) || 0;
11207
+ }
11208
+
11209
+ function warnDurableUiLayoutOnce(message) {
11210
+ if (durableLayoutWarned) return;
11211
+ durableLayoutWarned = true;
11212
+ addEvent(message, "warn");
11213
+ }
11214
+
11215
+ function scheduleDurableUiLayoutSave(delay = UI_LAYOUT_SAVE_DEBOUNCE_MS) {
11216
+ // One coalescing writer: repeated drag-over commits only reset this timer.
11217
+ if (durableLayoutSaveTimer !== null) clearTimeout(durableLayoutSaveTimer);
11218
+ durableLayoutSaveTimer = setTimeout(() => {
11219
+ durableLayoutSaveTimer = null;
11220
+ flushDurableUiLayoutSave();
11221
+ }, delay);
11222
+ }
11223
+
11224
+ function markDurableUiLayoutDirty(field, subfield = null) {
11225
+ if (!UI_LAYOUT_FIELDS.includes(field)) return;
11226
+ const allowedSubfields = durableUiLayoutSubFields(field);
11227
+ if (subfield && !allowedSubfields?.includes(subfield)) return;
11228
+ const generation = durableUiLayoutGeneration(field) + 1;
11229
+ const previous = durableLayoutDirtyFields.get(field);
11230
+ const value = collectDurableUiLayoutField(field);
11231
+ let subfields = null;
11232
+ let subfieldGenerations = null;
11233
+ let subfieldMutationIds = null;
11234
+ let mutationId = null;
11235
+ if (allowedSubfields && field !== "composerActions") {
11236
+ subfields = new Set(previous?.subfields || []);
11237
+ subfieldGenerations = new Map(previous?.subfieldGenerations || []);
11238
+ subfieldMutationIds = new Map(previous?.subfieldMutationIds || []);
11239
+ const changedSubfields = subfield ? [subfield] : allowedSubfields;
11240
+ for (const key of changedSubfields) {
11241
+ const nextMutationId = writeDurableUiLayoutPendingMutation(field, key, value?.[key] ?? null);
11242
+ if (nextMutationId) {
11243
+ removeDurableUiLayoutPendingMutation(subfieldMutationIds.get(key));
11244
+ subfieldMutationIds.set(key, nextMutationId);
11245
+ }
11246
+ subfields.add(key);
11247
+ subfieldGenerations.set(key, generation);
11248
+ }
11249
+ } else {
11250
+ mutationId = writeDurableUiLayoutPendingMutation(field, null, value);
11251
+ if (mutationId) removeDurableUiLayoutPendingMutation(previous?.mutationId);
11252
+ else mutationId = previous?.mutationId || null;
11253
+ }
11254
+ durableLayoutGenerations.set(field, generation);
11255
+ durableLayoutDirtyFields.set(field, {
11256
+ generation,
11257
+ value,
11258
+ subfields,
11259
+ subfieldGenerations,
11260
+ subfieldMutationIds,
11261
+ mutationId,
11262
+ });
11263
+ durableLayoutConflictAttempts = 0;
11264
+ scheduleDurableUiLayoutSave();
11265
+ }
11266
+
11267
+ function applyDurableUiLayoutSnapshot(data, { generations = null, readEpoch = 0 } = {}) {
11268
+ if (!data || typeof data !== "object") return false;
11269
+ if (readEpoch && readEpoch <= durableLayoutWriteFenceReadEpoch) return false;
11270
+ if (readEpoch && readEpoch < durableLayoutAppliedReadEpoch) return false;
11271
+ if (readEpoch) durableLayoutAppliedReadEpoch = readEpoch;
11272
+ if (typeof data.layoutRevision === "string" && data.layoutRevision) durableLayoutRevision = data.layoutRevision;
11273
+ const layout = data.layout && typeof data.layout === "object" ? data.layout : null;
11274
+ if (!layout || layout.version !== UI_LAYOUT_SCHEMA_VERSION) return Boolean(durableLayoutRevision);
11275
+ for (const field of UI_LAYOUT_FIELDS) {
11276
+ const requestedGeneration = generations ? generations.get(field) ?? 0 : durableUiLayoutGeneration(field);
11277
+ const generationChanged = durableUiLayoutGeneration(field) !== requestedGeneration;
11278
+ const dirtyEntry = durableLayoutDirtyFields.get(field);
11279
+ const serverValue = layout[field] ?? null;
11280
+ const localValue = collectDurableUiLayoutField(field);
11281
+ const subfields = durableUiLayoutSubFields(field);
11282
+ const dirtySubfields = dirtyEntry?.subfields;
11283
+
11284
+ if (subfields && field !== "composerActions") {
11285
+ const applicable = {};
11286
+ let hasApplicable = false;
11287
+ for (const subfield of subfields) {
11288
+ const isDirty = dirtySubfields?.has(subfield) === true;
11289
+ const remote = serverValue?.[subfield] ?? null;
11290
+ const local = localValue?.[subfield] ?? null;
11291
+ if (!isDirty && !generationChanged && !durableUiLayoutInteractionActive(field) && durableUiLayoutValuePresent(remote)) {
11292
+ applicable[subfield] = remote;
11293
+ hasApplicable = true;
11294
+ }
11295
+ if (!isDirty && !durableUiLayoutValuePresent(remote) && durableUiLayoutValuePresent(local)) {
11296
+ markDurableUiLayoutDirty(field, subfield);
11297
+ }
11298
+ }
11299
+ if (hasApplicable) applyDurableUiLayoutField(field, applicable);
11300
+ continue;
11301
+ }
11302
+
11303
+ if (!dirtyEntry && !generationChanged && !durableUiLayoutInteractionActive(field) && durableUiLayoutValuePresent(serverValue)) {
11304
+ applyDurableUiLayoutField(field, serverValue);
11305
+ }
11306
+ if (!dirtyEntry && !durableUiLayoutValuePresent(serverValue) && durableUiLayoutValuePresent(localValue)) {
11307
+ markDurableUiLayoutDirty(field);
11308
+ }
11309
+ }
11310
+ return true;
11311
+ }
11312
+
11313
+ async function refreshDurableUiLayoutFromServer() {
11314
+ const generations = new Map(UI_LAYOUT_FIELDS.map((field) => [field, durableUiLayoutGeneration(field)]));
11315
+ const readEpoch = ++durableLayoutReadEpoch;
11316
+ try {
11317
+ const response = await api(UI_LAYOUT_ENDPOINT, { scoped: false });
11318
+ return applyDurableUiLayoutSnapshot(response.data, { generations, readEpoch });
11319
+ } catch {
11320
+ // Keep the local cache authoritative until the settings file is reachable.
11321
+ return false;
11322
+ }
11323
+ }
11324
+
11325
+ async function flushDurableUiLayoutSave() {
11326
+ if (durableLayoutSaveInFlight || !durableLayoutDirtyFields.size) return;
11327
+ if ([...durableLayoutDirtyFields.keys()].some((field) => durableUiLayoutInteractionActive(field))) {
11328
+ scheduleDurableUiLayoutSave();
11329
+ return;
11330
+ }
11331
+ if (typeof navigator !== "undefined" && navigator.onLine === false) return;
11332
+ durableLayoutSaveInFlight = true;
11333
+ let snapshot = new Map();
11334
+ let retryImmediately = false;
11335
+ try {
11336
+ if (!durableLayoutRevision) await refreshDurableUiLayoutFromServer();
11337
+ if (!durableLayoutRevision || !durableLayoutDirtyFields.size) return;
11338
+ snapshot = new Map([...durableLayoutDirtyFields].map(([field, entry]) => [field, {
11339
+ ...entry,
11340
+ subfields: entry.subfields ? new Set(entry.subfields) : null,
11341
+ subfieldGenerations: entry.subfieldGenerations ? new Map(entry.subfieldGenerations) : null,
11342
+ subfieldMutationIds: entry.subfieldMutationIds ? new Map(entry.subfieldMutationIds) : null,
11343
+ }]));
11344
+ const patch = { version: UI_LAYOUT_SCHEMA_VERSION };
11345
+ for (const [field, entry] of snapshot) patch[field] = durableUiLayoutEntryPatch(field, entry);
11346
+ const response = await api(UI_LAYOUT_ENDPOINT, {
11347
+ method: "PUT",
11348
+ scoped: false,
11349
+ body: { layout: patch, expectedLayoutRevision: durableLayoutRevision },
11350
+ });
11351
+ // A successful write is newer than every GET that began before this
11352
+ // acknowledgement, even if one of those reads completes afterward.
11353
+ durableLayoutWriteFenceReadEpoch = Math.max(durableLayoutWriteFenceReadEpoch, durableLayoutReadEpoch);
11354
+ if (typeof response.data?.layoutRevision === "string" && response.data.layoutRevision) durableLayoutRevision = response.data.layoutRevision;
11355
+ for (const [field, entry] of snapshot) {
11356
+ const current = durableLayoutDirtyFields.get(field);
11357
+ if (!current) continue;
11358
+ if (entry.subfields?.size) {
11359
+ for (const subfield of entry.subfields) {
11360
+ if (current.subfieldGenerations?.get(subfield) !== entry.subfieldGenerations?.get(subfield)) continue;
11361
+ if (current.subfieldMutationIds?.get(subfield) !== entry.subfieldMutationIds?.get(subfield)) continue;
11362
+ current.subfields.delete(subfield);
11363
+ current.subfieldGenerations.delete(subfield);
11364
+ current.subfieldMutationIds.delete(subfield);
11365
+ }
11366
+ if (!current.subfields.size) durableLayoutDirtyFields.delete(field);
11367
+ else current.value = collectDurableUiLayoutField(field);
11368
+ } else if (current.generation === entry.generation && current.mutationId === entry.mutationId) {
11369
+ durableLayoutDirtyFields.delete(field);
11370
+ }
11371
+ }
11372
+ clearAcknowledgedDurableUiLayoutPendingMutations(snapshot);
11373
+ durableLayoutConflictAttempts = 0;
11374
+ durableLayoutWarned = false;
11375
+ } catch (error) {
11376
+ const status = Number(error?.statusCode) || 0;
11377
+ if (status === 409) {
11378
+ durableLayoutConflictAttempts += 1;
11379
+ await refreshDurableUiLayoutFromServer();
11380
+ if (durableLayoutConflictAttempts <= UI_LAYOUT_MAX_CONFLICT_RETRIES) retryImmediately = durableLayoutDirtyFields.size > 0;
11381
+ else warnDurableUiLayoutOnce("Durable layout changes stayed in this browser because the saved layout kept changing elsewhere.");
11382
+ } else if (status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 429) {
11383
+ // Keep the pending journal for recovery, but do not retry a rejected
11384
+ // payload until another user/lifecycle event supplies a new opportunity.
11385
+ warnDurableUiLayoutOnce(`Could not save the durable UI layout: ${error?.message || String(error)}`);
11386
+ }
11387
+ // Offline and server failures keep the newest dirty state for the next
11388
+ // mutation, online event, or foreground reconciliation.
11389
+ } finally {
11390
+ durableLayoutSaveInFlight = false;
11391
+ }
11392
+ const hasNewerMutation = [...durableLayoutDirtyFields].some(([field, entry]) => snapshot.get(field)?.generation !== entry.generation);
11393
+ if (retryImmediately || hasNewerMutation) scheduleDurableUiLayoutSave(retryImmediately ? 0 : UI_LAYOUT_SAVE_DEBOUNCE_MS);
11394
+ }
11395
+
11396
+ function reconcileDurableUiLayout() {
11397
+ if (durableUiLayoutInteractionActive()) return;
11398
+ refreshDurableUiLayoutFromServer().then((ready) => {
11399
+ if (ready && durableLayoutDirtyFields.size) scheduleDurableUiLayoutSave(0);
11400
+ });
11401
+ }
11402
+
10104
11403
  function readStoredSidePanelWidth() {
10105
11404
  try {
10106
11405
  const width = Number.parseFloat(localStorage.getItem(SIDE_PANEL_WIDTH_STORAGE_KEY) || "");
@@ -10184,8 +11483,13 @@ async function restoreSidePanelWidthPreference() {
10184
11483
  else updateSidePanelResizeHandle(localWidth || SIDE_PANEL_WIDTH_DEFAULT_PX);
10185
11484
 
10186
11485
  const restoreRevision = sidePanelWidthPreferenceRevision;
11486
+ const layoutGenerations = new Map(UI_LAYOUT_FIELDS.map((field) => [field, durableUiLayoutGeneration(field)]));
11487
+ const readEpoch = ++durableLayoutReadEpoch;
10187
11488
  try {
11489
+ // One non-blocking unscoped read hydrates both the width preference and the
11490
+ // durable layout after the synchronous local-cache startup pass.
10188
11491
  const response = await api("/api/interface-preferences", { scoped: false });
11492
+ applyDurableUiLayoutSnapshot(response.data, { generations: layoutGenerations, readEpoch });
10189
11493
  if (restoreRevision !== sidePanelWidthPreferenceRevision) return;
10190
11494
  const userWidth = Number(response.data?.preferences?.sidePanelWidth);
10191
11495
  if (Number.isFinite(userWidth) && userWidth >= SIDE_PANEL_WIDTH_MIN_PX) {
@@ -10253,7 +11557,10 @@ function syncSidePanelWidthForViewport() {
10253
11557
  updateSidePanelResizeHandle();
10254
11558
  return;
10255
11559
  }
10256
- applySidePanelWidth(currentSidePanelWidth());
11560
+ // Keep viewport/layout reconciliation anchored to the durable preference.
11561
+ // Reading the rendered width here can capture an in-progress CSS transition
11562
+ // during hard-reset startup and permanently freeze the panel below its saved width.
11563
+ applySidePanelWidth(readStoredSidePanelWidth() || currentSidePanelWidth());
10257
11564
  }
10258
11565
 
10259
11566
  function readStoredFileViewerWidth() {
@@ -10271,6 +11578,7 @@ function persistFileViewerWidth(width) {
10271
11578
  } catch {
10272
11579
  // Ignore storage failures; resizing should still work for this page load.
10273
11580
  }
11581
+ markDurableUiLayoutDirty("fileViewerWidth");
10274
11582
  }
10275
11583
 
10276
11584
  function fileViewerMaxWidth() {
@@ -11167,6 +12475,7 @@ function syncTabMetadata(nextTabs = []) {
11167
12475
  setTabActivity(tab.id, tab.activity);
11168
12476
  if (Object.prototype.hasOwnProperty.call(tab, "appRunner")) setAppRunnerData(tab.id, { activeRun: tab.appRunner });
11169
12477
  if (Object.prototype.hasOwnProperty.call(tab, "conversationMode")) updateConversationModeForTab(tab.id, tab.conversationMode, { render: false });
12478
+ if (tab.sessionSummary) updateSessionSummaryForTab(tab.id, tab.sessionSummary);
11170
12479
  }
11171
12480
  for (const tabId of tabActivities.keys()) {
11172
12481
  if (!liveIds.has(tabId)) {
@@ -11176,7 +12485,7 @@ function syncTabMetadata(nextTabs = []) {
11176
12485
  suppressPendingAgentDoneNotificationsForTab(tabId, { markSeen: false });
11177
12486
  actionFeedbackByTab.delete(tabId);
11178
12487
  skillUsageByTab.delete(tabId);
11179
- featureCategoryByTab.delete(tabId);
12488
+ clearFeatureDecisionStateForTab(tabId);
11180
12489
  tabMessagesCache.delete(tabId);
11181
12490
  widgetsByTab.delete(tabId);
11182
12491
  appRunnerDataByTab.delete(tabId);
@@ -11193,6 +12502,8 @@ function syncTabMetadata(nextTabs = []) {
11193
12502
  if (voiceConversationTabId === tabId) stopVoiceConversationLoop();
11194
12503
  clearGitWorkflowForTab(tabId);
11195
12504
  commandCatalogsByTab.delete(tabId);
12505
+ sessionSummaryByTab.delete(tabId);
12506
+ if (sessionSummaryOverlayTabId === tabId) closeSessionSummaryOverlay({ restoreFocus: false });
11196
12507
  clearGitFooterPayloadState(tabId);
11197
12508
  gitFooterPayloadRequestSerialByTab.delete(tabId);
11198
12509
  }
@@ -11210,8 +12521,10 @@ function applyTabMetadata(tab) {
11210
12521
  else tabs[index] = { ...tabs[index], ...tab };
11211
12522
  if (tab.activity) setTabActivity(tab.id, tab.activity);
11212
12523
  if (Object.prototype.hasOwnProperty.call(tab, "conversationMode")) updateConversationModeForTab(tab.id, tab.conversationMode, { render: false });
12524
+ if (tab.sessionSummary) updateSessionSummaryForTab(tab.id, tab.sessionSummary);
11213
12525
  renderConversationModeControls();
11214
12526
  renderWorkflowModeControls();
12527
+ renderSessionSummaryControls();
11215
12528
  renderTabs();
11216
12529
  return true;
11217
12530
  }
@@ -11502,6 +12815,7 @@ function cancelPendingDialogs() {
11502
12815
  }).catch((error) => console.warn("failed to cancel stale extension dialog", error));
11503
12816
  }
11504
12817
  activeDialog = null;
12818
+ activeDialogCancel = null;
11505
12819
  if (elements.dialog.open) elements.dialog.close();
11506
12820
  }
11507
12821
 
@@ -13122,7 +14436,7 @@ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs", all
13122
14436
  tabDrafts.delete(id);
13123
14437
  clearAttachments(id);
13124
14438
  clearGitWorkflowForTab(id);
13125
- featureCategoryByTab.delete(id);
14439
+ clearFeatureDecisionStateForTab(id);
13126
14440
  commandCatalogsByTab.delete(id);
13127
14441
  appRunnerDataByTab.delete(id);
13128
14442
  tabMessagesCache.delete(id);
@@ -13175,6 +14489,10 @@ async function closeAllTerminalTabs() {
13175
14489
 
13176
14490
  async function initializeTabs() {
13177
14491
  const loadedTabs = await refreshTabs({ selectStored: true });
14492
+ // Durable groups can arrive before the initial tab catalog. Rehydrate them
14493
+ // after tabs load so valid memberships are not filtered against an empty set.
14494
+ restoreTerminalCustomGroups();
14495
+ syncTerminalCustomGroupsWithTabs(tabs, { persist: false });
13178
14496
  restoreMobileContinuityState();
13179
14497
  resetActiveTabUi();
13180
14498
  renderTabs();
@@ -18282,6 +19600,7 @@ function writeFooterScopedModelOrder(order) {
18282
19600
  try {
18283
19601
  localStorage.setItem(FOOTER_SCOPED_MODEL_ORDER_STORAGE_KEY, JSON.stringify([...new Set(order.filter(Boolean))]));
18284
19602
  } catch {}
19603
+ markDurableUiLayoutDirty("footerScopedModelOrder");
18285
19604
  }
18286
19605
 
18287
19606
  function orderedFooterScopedModels() {
@@ -19754,7 +21073,7 @@ function finishedSubagentRunSelections(data = latestSubagents) {
19754
21073
  ));
19755
21074
  }
19756
21075
 
19757
- async function clearFinishedSubagentRuns() {
21076
+ async function clearFinishedSubagentRuns({ automatic = false } = {}) {
19758
21077
  if (subagentsClearingFinished || subagentsLoading) return;
19759
21078
  const selections = finishedSubagentRunSelections();
19760
21079
  if (!selections.length) return;
@@ -19782,8 +21101,8 @@ async function clearFinishedSubagentRuns() {
19782
21101
  renderSubagents();
19783
21102
  scheduleRefreshSubagents();
19784
21103
  }
19785
- if (dismissed) addEvent(`cleared ${dismissed} finished subagent ${dismissed === 1 ? "run" : "runs"}`, "info");
19786
- if (failures.length) addEvent(`could not clear ${failures.length} finished subagent ${failures.length === 1 ? "run" : "runs"}`, "warn");
21104
+ if (dismissed) addEvent(`${automatic ? "auto-cleared" : "cleared"} ${dismissed} finished subagent ${dismissed === 1 ? "run" : "runs"}`, "info");
21105
+ if (failures.length) addEvent(`could not ${automatic ? "auto-clear" : "clear"} ${failures.length} finished subagent ${failures.length === 1 ? "run" : "runs"}`, "warn");
19787
21106
  }
19788
21107
 
19789
21108
  function subagentOverlayTranscriptMessages(data = subagentOverlayData) {
@@ -20796,6 +22115,13 @@ function renderSubagents() {
20796
22115
  elements.subagentCountBadge.textContent = String(totalAgents);
20797
22116
  elements.subagentCountBadge.hidden = totalAgents === 0;
20798
22117
  }
22118
+ if (elements.subagentsAutoClearButton) {
22119
+ elements.subagentsAutoClearButton.setAttribute("aria-pressed", subagentAutoClearEnabled ? "true" : "false");
22120
+ elements.subagentsAutoClearButton.classList.toggle("selected", subagentAutoClearEnabled);
22121
+ elements.subagentsAutoClearButton.title = subagentAutoClearEnabled
22122
+ ? "Auto-Clear is on: finished subagent runs are removed automatically"
22123
+ : "Auto-Clear is off: keep finished subagent runs until they are cleared manually";
22124
+ }
20799
22125
  if (elements.subagentsClearFinishedButton) {
20800
22126
  elements.subagentsClearFinishedButton.disabled = subagentsLoading || subagentsClearingFinished || finishedRuns.length === 0;
20801
22127
  elements.subagentsClearFinishedButton.textContent = subagentsClearingFinished ? "Clearing…" : "Clear finished";
@@ -20826,6 +22152,7 @@ function renderSubagents() {
20826
22152
 
20827
22153
  async function refreshSubagents() {
20828
22154
  if (subagentsLoading) return;
22155
+ let refreshed = false;
20829
22156
  let subagentViewsChanged = false;
20830
22157
  let materializedTerminalViews = false;
20831
22158
  subagentsLoading = true;
@@ -20837,6 +22164,7 @@ async function refreshSubagents() {
20837
22164
  subagentViewsChanged = syncSubagentTerminalViewsFromOverview();
20838
22165
  materializedTerminalViews = materializeRetainedSubagentTerminalViews();
20839
22166
  subagentsError = null;
22167
+ refreshed = true;
20840
22168
  } catch (error) {
20841
22169
  subagentsError = error;
20842
22170
  } finally {
@@ -20849,6 +22177,9 @@ async function refreshSubagents() {
20849
22177
  }
20850
22178
  if (subagentViewsChanged || materializedTerminalViews) renderTabs();
20851
22179
  }
22180
+ if (refreshed && subagentAutoClearEnabled && finishedSubagentRunSelections().length) {
22181
+ await clearFinishedSubagentRuns({ automatic: true });
22182
+ }
20852
22183
  }
20853
22184
 
20854
22185
  function scheduleRefreshSubagents(delay) {
@@ -21461,6 +22792,166 @@ function releaseDialogLineClass(plainLine, section) {
21461
22792
  return "";
21462
22793
  }
21463
22794
 
22795
+ // Enter inside a native input dialog must never fall through to the browser's
22796
+ // implicit `method="dialog"` submission. "ignore" leaves IME composition alone,
22797
+ // "suppress" only blocks the implicit close, and "submit" sends one response.
22798
+ function dialogInputEnterIntent(event) {
22799
+ if (!event || event.key !== "Enter") return "ignore";
22800
+ if (event.isComposing || event.keyCode === 229) return "ignore";
22801
+ if (event.repeat) return "suppress";
22802
+ if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return "suppress";
22803
+ return "submit";
22804
+ }
22805
+
22806
+ const QUESTIONNAIRE_TITLE_PATTERN = /^Question\s+([1-9]\d*)\s+of\s+([1-9]\d*):\s+\S.*$/;
22807
+ const QUESTIONNAIRE_ROW_PATTERN = /^(\d{2})\.\s(.*)$/;
22808
+ const QUESTIONNAIRE_STATE_PATTERN = /^(\[ \]|\[x\]|\[selected\])\s(.*)$/;
22809
+ const QUESTIONNAIRE_MAX_QUESTIONS = 20;
22810
+ const QUESTIONNAIRE_MAX_OPTIONS = 50;
22811
+
22812
+ function isQuestionnaireChangeOtherAction(value) {
22813
+ const prefix = "Change Other… (currently ";
22814
+ if (!value.startsWith(prefix) || !value.endsWith(")")) return false;
22815
+ const encoded = value.slice(prefix.length, -1);
22816
+ try {
22817
+ const other = JSON.parse(encoded);
22818
+ return typeof other === "string" && JSON.stringify(other) === encoded;
22819
+ } catch {
22820
+ return false;
22821
+ }
22822
+ }
22823
+
22824
+ // Bounded, presentation-only grammar for the native questionnaire runtime's
22825
+ // action strings. Anything outside this list stays a generic option.
22826
+ function questionnaireContinueCount(text) {
22827
+ const match = String(text || "").match(/^Continue with (0|[1-9]\d*) selection\(s\)$/);
22828
+ if (!match) return null;
22829
+ const count = Number(match[1]);
22830
+ return Number.isSafeInteger(count) && count <= QUESTIONNAIRE_MAX_OPTIONS + 1 ? count : null;
22831
+ }
22832
+
22833
+ function questionnaireActionKind(text) {
22834
+ const value = String(text || "");
22835
+ if (value === "Cancel questionnaire") return "cancel";
22836
+ if (value === "Ask Pi to clarify…") return "clarify";
22837
+ if (value === "Remove Other answer") return "remove-other";
22838
+ if (value === "Other… (enter a custom answer)" || value === "Add Other…") return "other";
22839
+ if (isQuestionnaireChangeOtherAction(value)) return "other";
22840
+ if (questionnaireContinueCount(value) !== null) return "continue";
22841
+ return null;
22842
+ }
22843
+
22844
+ // Parses one native option string for presentation only; the caller always
22845
+ // transports the untouched original string back to the extension.
22846
+ function parseQuestionnaireOption(text) {
22847
+ const value = String(text || "");
22848
+ const action = questionnaireActionKind(value);
22849
+ if (action) return { kind: "action", action, value };
22850
+
22851
+ const row = value.match(QUESTIONNAIRE_ROW_PATTERN);
22852
+ if (!row) return null;
22853
+ const number = row[1];
22854
+ const state = row[2].match(QUESTIONNAIRE_STATE_PATTERN);
22855
+ const marker = state ? (state[1] === "[ ]" ? "unselected" : "selected") : "none";
22856
+ const body = state ? state[2] : row[2];
22857
+ if (!body.trim()) return null;
22858
+
22859
+ const separator = body.indexOf(" — ");
22860
+ const label = separator === -1 ? body : body.slice(0, separator);
22861
+ const description = separator === -1 ? "" : body.slice(separator + 3);
22862
+ if (!label.trim()) return null;
22863
+ return { kind: "option", marker, number, label, description, value };
22864
+ }
22865
+
22866
+ function questionnaireActionSequenceMatches(mode, actionRows) {
22867
+ const values = actionRows.map((row) => row.value);
22868
+ if (mode === "single") {
22869
+ const expected = values[0] === "Other… (enter a custom answer)"
22870
+ ? ["Other… (enter a custom answer)", "Ask Pi to clarify…", "Cancel questionnaire"]
22871
+ : ["Ask Pi to clarify…", "Cancel questionnaire"];
22872
+ return values.length === expected.length && values.every((value, index) => value === expected[index]);
22873
+ }
22874
+
22875
+ let index = 0;
22876
+ if (values[index] === "Add Other…") {
22877
+ index += 1;
22878
+ } else if (isQuestionnaireChangeOtherAction(values[index] || "")) {
22879
+ index += 1;
22880
+ if (values[index] !== "Remove Other answer") return false;
22881
+ index += 1;
22882
+ }
22883
+ if (values[index] !== "Ask Pi to clarify…") return false;
22884
+ index += 1;
22885
+ if (questionnaireContinueCount(values[index]) === null) return false;
22886
+ index += 1;
22887
+ return values[index] === "Cancel questionnaire" && index === values.length - 1;
22888
+ }
22889
+
22890
+ // Detection requires the complete runtime title, contiguous numbered rows, one
22891
+ // consistent state-marker mode, and the exact ordered action tail. This keeps
22892
+ // lookalike extension selects on the generic renderer.
22893
+ function questionnaireSelectParts(prompt, options) {
22894
+ if (!Array.isArray(options) || options.length < 3 || options.length > QUESTIONNAIRE_MAX_OPTIONS + 5) return null;
22895
+ const title = stripAnsi(prompt?.title || "").trim();
22896
+ const titleMatch = title.match(QUESTIONNAIRE_TITLE_PATTERN);
22897
+ if (!titleMatch) return null;
22898
+ const current = Number(titleMatch[1]);
22899
+ const total = Number(titleMatch[2]);
22900
+ if (current > total || total > QUESTIONNAIRE_MAX_QUESTIONS) return null;
22901
+
22902
+ const rows = [];
22903
+ for (const option of options) {
22904
+ const parsed = parseQuestionnaireOption(String(option));
22905
+ if (!parsed) return null;
22906
+ rows.push(parsed);
22907
+ }
22908
+
22909
+ const firstAction = rows.findIndex((row) => row.kind === "action");
22910
+ if (firstAction < 1 || firstAction > QUESTIONNAIRE_MAX_OPTIONS) return null;
22911
+ const optionRows = rows.slice(0, firstAction);
22912
+ const actionRows = rows.slice(firstAction);
22913
+ if (actionRows.some((row) => row.kind !== "action")) return null;
22914
+ if (!optionRows.every((row, index) => row.kind === "option" && row.number === String(index + 1).padStart(2, "0"))) return null;
22915
+
22916
+ const single = optionRows.every((row) => row.marker === "none");
22917
+ const multi = optionRows.every((row) => row.marker !== "none");
22918
+ if (!single && !multi) return null;
22919
+ const mode = multi ? "multi" : "single";
22920
+ if (!questionnaireActionSequenceMatches(mode, actionRows)) return null;
22921
+ return { rows, mode };
22922
+ }
22923
+
22924
+ function renderQuestionnaireOptionButton(row, mode) {
22925
+ const classNames = ["questionnaire-option", `questionnaire-option-${mode}`];
22926
+ if (row.marker === "selected") classNames.push("is-selected");
22927
+ const button = make("button", classNames.join(" "));
22928
+ button.type = "button";
22929
+ // The visible text is split into semantic parts, so the accessible name keeps
22930
+ // the exact native string that click transport sends back.
22931
+ button.setAttribute("aria-label", row.value);
22932
+ if (row.marker !== "none") button.setAttribute("aria-pressed", String(row.marker === "selected"));
22933
+
22934
+ button.append(make("span", "questionnaire-option-number", row.number));
22935
+ if (row.marker !== "none") {
22936
+ const state = make("span", "questionnaire-option-state", row.marker === "selected" ? "✓" : "");
22937
+ state.setAttribute("aria-hidden", "true");
22938
+ button.append(state);
22939
+ }
22940
+ const text = make("span", "questionnaire-option-text");
22941
+ text.append(make("span", "questionnaire-option-label", row.label));
22942
+ if (row.description) text.append(make("span", "questionnaire-option-description", row.description));
22943
+ button.append(text);
22944
+ return button;
22945
+ }
22946
+
22947
+ function renderQuestionnaireActionButton(row) {
22948
+ const classNames = ["questionnaire-action", `questionnaire-action-${row.action}`];
22949
+ if (row.action === "continue") classNames.push("primary");
22950
+ const button = make("button", classNames.join(" "), row.value);
22951
+ button.type = "button";
22952
+ return button;
22953
+ }
22954
+
21464
22955
  function renderReleaseDialogMessage(parent, text) {
21465
22956
  parent.replaceChildren();
21466
22957
  let section = "";
@@ -23319,6 +24810,7 @@ function renderAppRunnerControls() {
23319
24810
  item.append(label, command);
23320
24811
  panel.append(item);
23321
24812
  }
24813
+ scheduleComposerActionSlotLayoutRestore();
23322
24814
  }
23323
24815
 
23324
24816
  function renderAppRunnerInfoDialog() {
@@ -29839,10 +31331,10 @@ function resetChatOutput() {
29839
31331
  transcriptRenderer.replaceChildren(elements.chat, ...preservedNodes);
29840
31332
  }
29841
31333
 
29842
- function appendChatMessageBubble(bubble) {
31334
+ function appendChatMessageBubble(bubble, { liveTail = false } = {}) {
29843
31335
  const liveBubbles = standaloneLiveTranscriptBubbles();
29844
31336
  const tailAnchor = [...elements.chat.children]
29845
- .find((child) => child !== bubble && (child === runIndicatorBubble || liveBubbles.has(child)));
31337
+ .find((child) => child !== bubble && (child === runIndicatorBubble || (!liveTail && liveBubbles.has(child))));
29846
31338
  if (tailAnchor) elements.chat.insertBefore(bubble, tailAnchor);
29847
31339
  else elements.chat.append(bubble);
29848
31340
  }
@@ -31082,7 +32574,7 @@ function appendMessage(message, options = {}) {
31082
32574
  return reused;
31083
32575
  }
31084
32576
  const created = createMessageBubble(message, { ...options, segmentId });
31085
- appendChatMessageBubble(created.bubble);
32577
+ appendChatMessageBubble(created.bubble, { liveTail: streaming || message?.live === true });
31086
32578
  return created;
31087
32579
  }
31088
32580
 
@@ -32421,12 +33913,33 @@ function resetOptionalFeatureAvailability() {
32421
33913
  for (const key of Object.keys(optionalFeatureAvailability)) optionalFeatureAvailability[key] = false;
32422
33914
  optionalFeatureAvailability.themeBundle = availableThemes.length > 0;
32423
33915
  renderOptionalFeatureControls();
33916
+ if (activeTabId) queueMicrotask(() => refreshQuestionnaireFeatureAvailability());
32424
33917
  }
32425
33918
 
32426
33919
  function optionalFeaturePackageStatus(featureId) {
32427
33920
  return optionalFeaturePackageStatuses.get(featureId) || null;
32428
33921
  }
32429
33922
 
33923
+ function optionalFeatureManualInstallCommand(feature) {
33924
+ return feature?.packageName ? `pi install npm:${feature.packageName}` : "";
33925
+ }
33926
+
33927
+ function optionalFeatureNeedsInstall(feature) {
33928
+ const status = optionalFeaturePackageStatus(feature?.id);
33929
+ if (!status || isOptionalFeatureDisabled(feature?.id)) return false;
33930
+ const legacyNeedsInstall = status.ready !== true && status.resourceConflict !== true;
33931
+ if (status.state) return ["missing", "legacy-migratable"].includes(status.state) && status.resourceConflict !== true;
33932
+ return legacyNeedsInstall;
33933
+ }
33934
+
33935
+ function optionalFeatureBatchCandidates(features = OPTIONAL_FEATURES) {
33936
+ return features.filter((feature) => optionalFeatureNeedsInstall(feature));
33937
+ }
33938
+
33939
+ function optionalFeatureBatchIsActive() {
33940
+ return optionalFeatureBatchState?.phase === "running";
33941
+ }
33942
+
32430
33943
  function optionalFeaturePackageVersionLabel(status) {
32431
33944
  if (!status?.installedVersion) return "";
32432
33945
  return status.declaredSpec ? `${status.installedVersion} (expects ${status.declaredSpec})` : status.installedVersion;
@@ -32491,13 +34004,24 @@ function optionalFeatureInstallFailureFromError(error) {
32491
34004
  const message = details.message || error?.message || String(error);
32492
34005
  const hint = details.hint || (error?.backendOffline
32493
34006
  ? "The Web UI server connection failed. Check that pi-webui is still running, then retry."
32494
- : "Run the shown npm command manually from the Web UI host to inspect the full package-manager output.");
34007
+ : "Run the shown Pi command manually from the Web UI host to inspect the full installer output.");
32495
34008
  return { ...details, message, hint, statusCode: error?.statusCode };
32496
34009
  }
32497
34010
 
34011
+ function optionalFeatureInstallFailureFromBatchResult(result, feature) {
34012
+ const details = result?.optionalFeatureInstall || {};
34013
+ return {
34014
+ ...details,
34015
+ message: details.message || result?.error || `Pi could not install ${feature.packageName}`,
34016
+ hint: details.hint || "Run the shown Pi command manually from the Web UI host to inspect the full installer output.",
34017
+ command: details.command || optionalFeatureManualInstallCommand(feature),
34018
+ };
34019
+ }
34020
+
32498
34021
  async function copyOptionalFeatureInstallCommand(featureId) {
34022
+ const feature = OPTIONAL_FEATURE_BY_ID.get(featureId);
32499
34023
  const state = optionalFeatureInstallState(featureId);
32500
- const command = String(state?.command || "").trim();
34024
+ const command = String(state?.command || optionalFeatureManualInstallCommand(feature)).trim();
32501
34025
  if (!command) {
32502
34026
  addEvent("optional feature install command is not available yet", "warn");
32503
34027
  return;
@@ -32510,17 +34034,470 @@ async function copyOptionalFeatureInstallCommand(featureId) {
32510
34034
  }
32511
34035
  }
32512
34036
 
32513
- async function refreshOptionalFeaturePackageStatuses({ announce = false } = {}) {
34037
+ function optionalFeatureAuditFeature(featureId) {
34038
+ return optionalFeatureMigrationSnapshot.features.find((feature) => feature?.featureId === featureId) || null;
34039
+ }
34040
+
34041
+ function optionalFeatureDisplayLabel(featureId, packageName = "") {
34042
+ return OPTIONAL_FEATURE_BY_ID.get(featureId)?.label || packageName || featureId || "optional feature";
34043
+ }
34044
+
34045
+ function optionalFeatureCandidateSignature(snapshot, featureIds) {
34046
+ const requested = new Set(featureIds || []);
34047
+ return (snapshot?.features || [])
34048
+ .filter((feature) => requested.has(feature.featureId))
34049
+ .map((feature) => `${feature.featureId}:${feature.state}:${feature.sourceKind}:${feature.previouslyEnabled === true}`)
34050
+ .sort()
34051
+ .join("|");
34052
+ }
34053
+
34054
+ function optionalFeatureMigrationCandidates(featureIds = null, { includeBrowserDisabled = false } = {}) {
34055
+ const requested = featureIds ? new Set(featureIds) : null;
34056
+ return (optionalFeatureMigrationSnapshot.features || []).filter((feature) => {
34057
+ if (feature?.state !== "legacy-migratable") return false;
34058
+ if (requested && !requested.has(feature.featureId)) return false;
34059
+ return includeBrowserDisabled || !isOptionalFeatureDisabled(feature.featureId);
34060
+ });
34061
+ }
34062
+
34063
+ function optionalFeatureMigrationElapsedMs() {
34064
+ const progress = optionalFeatureMigrationSnapshot.progress;
34065
+ if (progress?.startedAt) {
34066
+ const startedAt = Date.parse(progress.startedAt);
34067
+ if (Number.isFinite(startedAt)) return Math.max(Number(progress.elapsedMs) || 0, Date.now() - startedAt);
34068
+ }
34069
+ if (optionalFeatureMigrationSnapshot.phase === "checking") return Date.now() - optionalFeatureMigrationCheckingStartedAt;
34070
+ return Number(progress?.elapsedMs) || 0;
34071
+ }
34072
+
34073
+ function optionalFeatureMigrationProgressText(progress = optionalFeatureMigrationSnapshot.progress) {
34074
+ if (!progress) return "";
34075
+ const elapsed = formatDuration(optionalFeatureMigrationElapsedMs());
34076
+ if (progress.phase === "migrating" && progress.currentFeatureId) {
34077
+ const label = optionalFeatureDisplayLabel(progress.currentFeatureId, progress.currentPackageName);
34078
+ return `Installing ${progress.index || (progress.completed || 0) + 1} of ${progress.total || 0}: ${label}${elapsed ? ` · elapsed ${elapsed}` : ""}`;
34079
+ }
34080
+ if (progress.phase === "partial") return `${progress.succeeded || 0} succeeded · ${progress.failed || 0} failed${elapsed ? ` · finished after ${elapsed}` : ""}`;
34081
+ if (progress.phase === "complete") return `${progress.succeeded || progress.total || 0} installed successfully${elapsed ? ` · finished after ${elapsed}` : ""}`;
34082
+ return "";
34083
+ }
34084
+
34085
+ function optionalFeatureMigrationPhaseMessage(phase) {
34086
+ switch (phase) {
34087
+ case "checking": return "checking optional features";
34088
+ case "ready": return "optional feature audit ready";
34089
+ case "action-required": return "optional feature audit needs attention";
34090
+ case "migrating": return "optional feature migration started";
34091
+ case "partial": return "optional feature migration finished with failures";
34092
+ case "complete": return "optional feature migration completed";
34093
+ case "degraded": return "optional feature audit degraded; Web UI is running core-only";
34094
+ default: return "";
34095
+ }
34096
+ }
34097
+
34098
+ function rememberOptionalFeatureMigrationEvent(key) {
34099
+ optionalFeatureMigrationResultEvents.add(key);
34100
+ while (optionalFeatureMigrationResultEvents.size > 256) optionalFeatureMigrationResultEvents.delete(optionalFeatureMigrationResultEvents.values().next().value);
34101
+ }
34102
+
34103
+ function announceOptionalFeatureMigrationSnapshot(snapshot) {
34104
+ if (snapshot.phase !== optionalFeatureMigrationLastPhase) {
34105
+ optionalFeatureMigrationLastPhase = snapshot.phase;
34106
+ const message = optionalFeatureMigrationPhaseMessage(snapshot.phase);
34107
+ if (message) addEvent(message, ["degraded", "action-required", "partial"].includes(snapshot.phase) ? "warn" : "info");
34108
+ }
34109
+ const progress = snapshot.progress;
34110
+ if (progress?.phase === "migrating" && progress.currentFeatureId) {
34111
+ const startKey = `${progress.startedAt || snapshot.revision}:start:${progress.currentFeatureId}`;
34112
+ if (!optionalFeatureMigrationResultEvents.has(startKey)) {
34113
+ rememberOptionalFeatureMigrationEvent(startKey);
34114
+ addEvent(optionalFeatureMigrationProgressText(progress), "info");
34115
+ }
34116
+ }
34117
+ for (const result of progress?.results || []) {
34118
+ const key = `${progress.startedAt || snapshot.revision}:${result.featureId}:${result.ok}:${result.kind || ""}`;
34119
+ if (optionalFeatureMigrationResultEvents.has(key)) continue;
34120
+ rememberOptionalFeatureMigrationEvent(key);
34121
+ const label = optionalFeatureDisplayLabel(result.featureId, result.packageName);
34122
+ addEvent(`${label}: ${result.ok ? "installed and verified" : result.message || "installation failed"}`, result.ok ? "info" : "error");
34123
+ }
34124
+ }
34125
+
34126
+ function applyOptionalFeatureProgressStates(snapshot) {
34127
+ const progress = snapshot.progress;
34128
+ if (!progress) return;
34129
+ const startedAt = Number.isFinite(Date.parse(progress.startedAt || "")) ? Date.parse(progress.startedAt) : Date.now();
34130
+ for (const result of progress.results || []) {
34131
+ const feature = OPTIONAL_FEATURE_BY_ID.get(result.featureId);
34132
+ const previous = optionalFeatureInstallState(result.featureId) || {};
34133
+ optionalFeatureInstallStates.set(result.featureId, {
34134
+ ...previous,
34135
+ phase: result.ok ? "done" : "failed",
34136
+ actionLabel: progress.migration ? "Migrate" : "Install",
34137
+ startedAt: previous.startedAt || startedAt,
34138
+ endedAt: progress.completedAt ? Date.parse(progress.completedAt) || Date.now() : Date.now(),
34139
+ detail: result.message || (result.ok ? "Installed and verified" : "Installation failed"),
34140
+ hint: result.ok ? "The server verified this package registration." : "Retry this package or run the copied Pi command on the Web UI host.",
34141
+ command: previous.command || optionalFeatureManualInstallCommand(feature),
34142
+ errorKind: result.kind || previous.errorKind || "",
34143
+ });
34144
+ }
34145
+ if (progress.phase === "migrating" && progress.currentFeatureId) {
34146
+ const current = OPTIONAL_FEATURE_BY_ID.get(progress.currentFeatureId);
34147
+ const previous = optionalFeatureInstallState(progress.currentFeatureId) || {};
34148
+ optionalFeatureInstallStates.set(progress.currentFeatureId, {
34149
+ ...previous,
34150
+ phase: "installing",
34151
+ actionLabel: progress.migration ? "Migrate" : "Install",
34152
+ startedAt: previous.startedAt || startedAt,
34153
+ endedAt: 0,
34154
+ detail: optionalFeatureMigrationProgressText(progress),
34155
+ hint: "Pi installs packages sequentially. This operation continues if the browser disconnects.",
34156
+ command: previous.command || optionalFeatureManualInstallCommand(current),
34157
+ });
34158
+ }
34159
+ if (progress.restartDeferred === true) {
34160
+ optionalFeatureRestartNotice = { autoRestarted: false, restartDeferred: true, tabId: activeTabId };
34161
+ } else if (progress.autoRestarted === true) {
34162
+ optionalFeatureRestartNotice = { autoRestarted: true, restartDeferred: false, tabId: activeTabId };
34163
+ }
34164
+ optionalFeatureBatchState = {
34165
+ phase: progress.phase === "migrating" ? "running" : progress.phase === "partial" ? "failed" : "done",
34166
+ scopeLabel: progress.migration ? "previous optional features" : "optional features",
34167
+ total: progress.total || 0,
34168
+ succeeded: progress.succeeded ?? (progress.results || []).filter((result) => result.ok).length,
34169
+ failed: progress.failed ?? (progress.results || []).filter((result) => !result.ok).length,
34170
+ startedAt,
34171
+ endedAt: progress.completedAt ? Date.parse(progress.completedAt) || Date.now() : 0,
34172
+ };
34173
+ }
34174
+
34175
+ function refreshOptionalFeatureMigrationElapsedText() {
34176
+ const detail = elements.optionalFeatureMigrationSurface?.querySelector(".optional-feature-migration-detail");
34177
+ if (!detail) return;
34178
+ if (optionalFeatureMigrationSnapshot.phase === "checking") {
34179
+ const elapsed = optionalFeatureMigrationElapsedMs();
34180
+ detail.textContent = elapsed >= 1000 ? `Read-only startup audit · elapsed ${formatDuration(elapsed)}` : "Read-only startup audit";
34181
+ } else if (optionalFeatureMigrationSnapshot.phase === "migrating") {
34182
+ detail.textContent = optionalFeatureMigrationProgressText(optionalFeatureMigrationSnapshot.progress) || "Preparing sequential Pi installs…";
34183
+ }
34184
+ }
34185
+
34186
+ function ensureOptionalFeatureMigrationRenderTimer() {
34187
+ const timed = ["checking", "migrating"].includes(optionalFeatureMigrationSnapshot.phase);
34188
+ if (timed && !optionalFeatureMigrationRenderTimer) {
34189
+ optionalFeatureMigrationRenderTimer = setInterval(() => {
34190
+ refreshOptionalFeatureMigrationElapsedText();
34191
+ if (optionalFeatureMigrationSnapshot.phase === "migrating") renderOptionalFeaturePanel();
34192
+ }, 1000);
34193
+ } else if (!timed && optionalFeatureMigrationRenderTimer) {
34194
+ clearInterval(optionalFeatureMigrationRenderTimer);
34195
+ optionalFeatureMigrationRenderTimer = null;
34196
+ }
34197
+ }
34198
+
34199
+ function optionalFeatureMigrationAction(label, handler, className = "") {
34200
+ const button = make("button", className, label);
34201
+ button.type = "button";
34202
+ button.addEventListener("click", handler);
34203
+ return button;
34204
+ }
34205
+
34206
+ function optionalFeatureConflictDescription(feature) {
34207
+ return `${optionalFeatureDisplayLabel(feature.featureId, feature.packageName)}: Pi package + top-level resource; the top-level copy was safely excluded.`;
34208
+ }
34209
+
34210
+ async function copyOptionalFeatureConflictFix(feature) {
34211
+ const text = [
34212
+ `Recommended fix for ${feature.packageName}:`,
34213
+ "Keep the registered Pi package as the canonical source.",
34214
+ "Disable or remove the duplicate top-level extension/skill/prompt/theme alias, then use Recheck in Pi Web UI.",
34215
+ ].join("\n");
32514
34216
  try {
32515
- const response = await api("/api/optional-features", { scoped: false });
32516
- optionalFeaturePackageStatusError = "";
32517
- optionalFeaturePackageStatuses.clear();
32518
- for (const status of response.data?.features || []) {
32519
- if (status?.featureId) optionalFeaturePackageStatuses.set(status.featureId, status);
34217
+ await copyText(text);
34218
+ addEvent(`copied recommended conflict fix for ${optionalFeatureDisplayLabel(feature.featureId, feature.packageName)}`, "info");
34219
+ } catch (error) {
34220
+ addEvent(`could not copy optional feature conflict fix: ${error.message || String(error)}`, "warn");
34221
+ }
34222
+ }
34223
+
34224
+ function optionalFeatureFailureOutputTail() {
34225
+ const tails = [];
34226
+ for (const [featureId, state] of optionalFeatureInstallStates) {
34227
+ if (state?.phase !== "failed" || !state.outputTail) continue;
34228
+ tails.push(`${optionalFeatureDisplayLabel(featureId)}\n${String(state.outputTail).slice(-2000)}`);
34229
+ }
34230
+ return tails.join("\n\n").slice(-4000);
34231
+ }
34232
+
34233
+ async function restartOptionalFeatureTab() {
34234
+ const tabId = optionalFeatureRestartNotice?.tabId || activeTabId;
34235
+ try {
34236
+ await sendPrompt("prompt", "/reload", { targetTabId: tabId, throwOnError: true });
34237
+ optionalFeatureRestartNotice = null;
34238
+ renderOptionalFeatureMigrationSurface();
34239
+ } catch (error) {
34240
+ addEvent(`optional feature tab restart failed: ${error.message || String(error)}`, "error");
34241
+ }
34242
+ }
34243
+
34244
+ function renderOptionalFeatureMigrationSurface() {
34245
+ const surface = elements.optionalFeatureMigrationSurface;
34246
+ if (!surface) return;
34247
+ const snapshot = optionalFeatureMigrationSnapshot;
34248
+ const summary = snapshot.summary || {};
34249
+ const conflicts = (snapshot.features || []).filter((feature) => feature.state === "conflict");
34250
+ const progress = snapshot.progress;
34251
+ const card = make("div", `optional-feature-migration-card phase-${snapshot.phase}`);
34252
+ const copy = make("div", "optional-feature-migration-copy");
34253
+ const title = make("strong", "optional-feature-migration-title");
34254
+ const detail = make("span", "optional-feature-migration-detail");
34255
+ const actions = make("div", "optional-feature-migration-actions");
34256
+
34257
+ if (snapshot.phase === "checking") {
34258
+ title.textContent = "Checking optional features…";
34259
+ const elapsed = optionalFeatureMigrationElapsedMs();
34260
+ detail.textContent = elapsed >= 1000 ? `Read-only startup audit · elapsed ${formatDuration(elapsed)}` : "Read-only startup audit";
34261
+ } else if (snapshot.phase === "degraded") {
34262
+ title.textContent = "Web UI started safely without optional companions";
34263
+ detail.textContent = snapshot.diagnostic?.message || "The optional-feature audit could not establish a safe configuration.";
34264
+ actions.append(optionalFeatureMigrationAction("Recheck", () => recheckOptionalFeatureMigration(), "primary"));
34265
+ } else if (snapshot.phase === "migrating") {
34266
+ title.textContent = "Migrating optional features";
34267
+ detail.textContent = optionalFeatureMigrationProgressText(progress) || "Preparing sequential Pi installs…";
34268
+ } else if (snapshot.phase === "partial") {
34269
+ title.textContent = "Optional feature migration needs attention";
34270
+ detail.textContent = optionalFeatureMigrationProgressText(progress);
34271
+ const failedIds = (progress?.results || []).filter((result) => !result.ok).map((result) => result.featureId);
34272
+ if (failedIds.length) actions.append(optionalFeatureMigrationAction("Retry failed", () => openOptionalFeatureMigrationDialog({ featureIds: failedIds, retryFailed: true }), "primary"));
34273
+ actions.append(optionalFeatureMigrationAction("Copy commands", () => copyFailedOptionalFeatureCommands()));
34274
+ } else if (snapshot.phase === "complete") {
34275
+ title.textContent = "Optional feature migration complete";
34276
+ detail.textContent = optionalFeatureMigrationProgressText(progress) || `${summary.ready || 0} optional features ready`;
34277
+ } else if (snapshot.phase === "action-required") {
34278
+ title.textContent = conflicts.length ? "Optional feature conflicts were safely excluded" : "Previous optional features need migration";
34279
+ detail.textContent = conflicts.length
34280
+ ? conflicts.map(optionalFeatureConflictDescription).join(" ")
34281
+ : `${summary.migratable || 0} previously available companion${summary.migratable === 1 ? "" : "s"} can be restored${snapshot.installKind === "upgrade" ? " after this Web UI upgrade" : ""}.`;
34282
+ if (summary.migratable > 0) {
34283
+ actions.append(optionalFeatureMigrationAction("Migrate…", () => openOptionalFeatureMigrationDialog(), "primary"));
34284
+ actions.append(optionalFeatureMigrationAction("Later", () => dismissOptionalFeatureMigration()));
34285
+ }
34286
+ for (const conflict of conflicts) actions.append(optionalFeatureMigrationAction("Copy recommended fix", () => copyOptionalFeatureConflictFix(conflict)));
34287
+ if (conflicts.length) actions.append(optionalFeatureMigrationAction("Recheck", () => recheckOptionalFeatureMigration()));
34288
+ } else {
34289
+ title.textContent = `Core ready · ${summary.ready || 0} optional feature${summary.ready === 1 ? "" : "s"} ready`;
34290
+ detail.textContent = summary.migratable > 0
34291
+ ? "Migration was deferred. Restore remains available in Optional features."
34292
+ : summary.missing > 0 ? `${summary.missing} optional companion${summary.missing === 1 ? " is" : "s are"} not installed.` : "Optional feature audit complete.";
34293
+ }
34294
+
34295
+ copy.append(title, detail);
34296
+ card.append(copy);
34297
+ if (actions.childElementCount) card.append(actions);
34298
+
34299
+ if (conflicts.length) {
34300
+ const alert = make("div", "optional-feature-migration-alert sr-only", "Optional feature conflict detected; duplicate top-level resources were safely excluded.");
34301
+ alert.setAttribute("role", "alert");
34302
+ card.append(alert);
34303
+ }
34304
+ if (snapshot.phase === "partial") {
34305
+ const alert = make("div", "optional-feature-migration-alert sr-only", `${progress?.failed || 0} optional feature installations failed.`);
34306
+ alert.setAttribute("role", "alert");
34307
+ card.append(alert);
34308
+ }
34309
+ const outputTail = optionalFeatureFailureOutputTail();
34310
+ if (outputTail && snapshot.phase === "partial") card.append(make("pre", "optional-feature-migration-output", outputTail));
34311
+
34312
+ if (optionalFeatureRestartNotice) {
34313
+ const notice = make("div", "optional-feature-restart-notice");
34314
+ const noticeText = optionalFeatureRestartNotice.restartDeferred
34315
+ ? "New optional features are ready. Restart is deferred because the affected tab was busy."
34316
+ : "Restarted tab to load new features.";
34317
+ notice.append(make("span", undefined, noticeText));
34318
+ if (optionalFeatureRestartNotice.restartDeferred) {
34319
+ notice.append(optionalFeatureMigrationAction("Restart tab", () => restartOptionalFeatureTab(), "primary"));
34320
+ } else {
34321
+ notice.append(optionalFeatureMigrationAction("Dismiss", () => {
34322
+ optionalFeatureRestartNotice = null;
34323
+ renderOptionalFeatureMigrationSurface();
34324
+ }));
32520
34325
  }
34326
+ card.append(notice);
34327
+ }
34328
+
34329
+ const focusKey = ["complete", "partial"].includes(snapshot.phase) ? `${snapshot.revision}:${snapshot.phase}:${progress?.completedAt || ""}` : "";
34330
+ if (focusKey) {
34331
+ card.tabIndex = -1;
34332
+ card.classList.add("optional-feature-migration-completion-summary");
34333
+ }
34334
+ surface.replaceChildren(card);
34335
+ surface.hidden = false;
34336
+ ensureOptionalFeatureMigrationRenderTimer();
34337
+ if (focusKey && focusKey !== optionalFeatureMigrationCompletionFocusKey) {
34338
+ optionalFeatureMigrationCompletionFocusKey = focusKey;
34339
+ queueMicrotask(() => card.isConnected && card.focus({ preventScroll: true }));
34340
+ }
34341
+ }
34342
+
34343
+ function applyOptionalFeatureMigrationSnapshot(snapshot, { announce = true } = {}) {
34344
+ if (!snapshot || typeof snapshot !== "object" || !Array.isArray(snapshot.features)) return false;
34345
+ if (snapshot.phase === "checking" && optionalFeatureMigrationSnapshot.phase !== "checking") optionalFeatureMigrationCheckingStartedAt = Date.now();
34346
+ optionalFeatureMigrationSnapshot = snapshot;
34347
+ optionalFeaturePackageStatuses.clear();
34348
+ for (const status of snapshot.features) {
34349
+ if (status?.featureId) optionalFeaturePackageStatuses.set(status.featureId, status);
34350
+ }
34351
+ optionalFeaturePackageStatusesLoaded = true;
34352
+ optionalFeaturePackageStatusError = "";
34353
+ applyOptionalFeatureProgressStates(snapshot);
34354
+ if (announce) announceOptionalFeatureMigrationSnapshot(snapshot);
34355
+ renderOptionalFeatureMigrationSurface();
34356
+ renderOptionalFeatureControls();
34357
+ return true;
34358
+ }
34359
+
34360
+ async function recheckOptionalFeatureMigration() {
34361
+ addEvent("rechecking optional features", "info");
34362
+ try {
34363
+ const response = await api("/api/optional-feature-migration/recheck", { method: "POST", body: {}, scoped: false });
34364
+ applyOptionalFeatureMigrationSnapshot(response.data);
34365
+ } catch (error) {
34366
+ addEvent(`optional feature recheck failed: ${error.message || String(error)}`, "error");
34367
+ }
34368
+ }
34369
+
34370
+ async function dismissOptionalFeatureMigration({ closeDialog = false, retryOnStale = true } = {}) {
34371
+ const revision = optionalFeatureMigrationSnapshot.revision;
34372
+ try {
34373
+ const response = await api("/api/optional-feature-migration/dismiss", { method: "POST", body: { revision }, scoped: false });
34374
+ applyOptionalFeatureMigrationSnapshot(response.data);
34375
+ if (closeDialog && elements.optionalFeatureMigrationDialog?.open) elements.optionalFeatureMigrationDialog.close();
34376
+ addEvent("optional feature migration deferred; the Migrate action remains available in Optional features", "info");
34377
+ } catch (error) {
34378
+ if (retryOnStale && error.statusCode === 409 && /stale|revision/i.test(error.message || "")) {
34379
+ await refreshOptionalFeaturePackageStatuses();
34380
+ return dismissOptionalFeatureMigration({ closeDialog, retryOnStale: false });
34381
+ }
34382
+ addEvent(`could not defer optional feature migration: ${error.message || String(error)}`, "error");
34383
+ }
34384
+ }
34385
+
34386
+ function renderOptionalFeatureMigrationDialog() {
34387
+ const state = optionalFeatureMigrationDialogState;
34388
+ if (!state || !elements.optionalFeatureMigrationChoices) return;
34389
+ const features = optionalFeatureMigrationCandidates(state.featureIds, { includeBrowserDisabled: true });
34390
+ const availableIds = new Set(features.map((feature) => feature.featureId));
34391
+ state.selected = new Set([...state.selected].filter((featureId) => availableIds.has(featureId) && !isOptionalFeatureDisabled(featureId)));
34392
+ elements.optionalFeatureMigrationChoices.replaceChildren();
34393
+
34394
+ for (const feature of features) {
34395
+ const item = make("div", "optional-feature-migration-choice");
34396
+ const choice = make("label", "optional-feature-migration-choice-label");
34397
+ const input = make("input");
34398
+ input.type = "checkbox";
34399
+ input.value = feature.featureId;
34400
+ input.checked = state.selected.has(feature.featureId);
34401
+ input.disabled = isOptionalFeatureDisabled(feature.featureId);
34402
+ input.addEventListener("change", () => {
34403
+ if (input.checked) state.selected.add(feature.featureId);
34404
+ else state.selected.delete(feature.featureId);
34405
+ renderOptionalFeatureMigrationDialog();
34406
+ });
34407
+ const label = make("span");
34408
+ label.append(make("strong", undefined, optionalFeatureDisplayLabel(feature.featureId, feature.packageName)));
34409
+ label.append(make("span", "optional-feature-migration-choice-package", feature.packageName));
34410
+ choice.append(input, label);
34411
+ const details = make("details", "optional-feature-migration-choice-details");
34412
+ details.append(
34413
+ make("summary", undefined, "Details"),
34414
+ make("span", undefined, `${feature.previouslyEnabled ? "Previously enabled" : "Previously disabled"} · source: ${feature.sourceKind || "legacy evidence"} · Pi will install ${feature.expectedSpec || feature.packageName}.`),
34415
+ );
34416
+ item.append(choice, details);
34417
+ elements.optionalFeatureMigrationChoices.append(item);
34418
+ }
34419
+
34420
+ const selectedFeatures = features.filter((feature) => state.selected.has(feature.featureId));
34421
+ elements.optionalFeatureMigrationDialogTitle.textContent = state.retryFailed ? "Retry failed optional features" : "Migrate optional features";
34422
+ elements.optionalFeatureMigrationDialogMessage.textContent = state.retryFailed
34423
+ ? "Retry only the failed packages. Successful packages stay installed. This is the only confirmation before retry."
34424
+ : "Previously enabled features are selected unless they are disabled in this browser. Pi installs the confirmed selection sequentially.";
34425
+ elements.optionalFeatureMigrationDialogSummary.textContent = selectedFeatures.length
34426
+ ? `${selectedFeatures.length} selected: ${selectedFeatures.map((feature) => optionalFeatureDisplayLabel(feature.featureId, feature.packageName)).join(", ")}. Pi may download code and update its package registration.`
34427
+ : "No features selected. Browser-disabled and previously disabled features remain unselected.";
34428
+ elements.optionalFeatureMigrationConfirmButton.textContent = state.retryFailed ? "Retry selected" : "Migrate selected";
34429
+ elements.optionalFeatureMigrationConfirmButton.disabled = selectedFeatures.length === 0 || optionalFeatureBatchIsActive();
34430
+ elements.optionalFeatureMigrationLaterButton.hidden = state.retryFailed;
34431
+ elements.optionalFeatureMigrationDialogError.hidden = !state.error;
34432
+ elements.optionalFeatureMigrationDialogError.textContent = state.error || "";
34433
+ elements.optionalFeatureMigrationChooseDetails.querySelector("summary").textContent = `Choose features (${selectedFeatures.length} selected)`;
34434
+ }
34435
+
34436
+ function openOptionalFeatureMigrationDialog({ featureIds = null, retryFailed = false } = {}) {
34437
+ const features = optionalFeatureMigrationCandidates(featureIds, { includeBrowserDisabled: true });
34438
+ if (!features.length) {
34439
+ addEvent("no migratable optional features are currently available", "info");
34440
+ return;
34441
+ }
34442
+ const selected = new Set(features
34443
+ .filter((feature) => retryFailed || feature.selectedByDefault === true)
34444
+ .filter((feature) => !isOptionalFeatureDisabled(feature.featureId))
34445
+ .map((feature) => feature.featureId));
34446
+ optionalFeatureMigrationDialogState = {
34447
+ featureIds: features.map((feature) => feature.featureId),
34448
+ selected,
34449
+ retryFailed,
34450
+ error: "",
34451
+ signature: optionalFeatureCandidateSignature(optionalFeatureMigrationSnapshot, features.map((feature) => feature.featureId)),
34452
+ };
34453
+ renderOptionalFeatureMigrationDialog();
34454
+ if (!elements.optionalFeatureMigrationDialog.open) elements.optionalFeatureMigrationDialog.showModal();
34455
+ queueMicrotask(() => elements.optionalFeatureMigrationConfirmButton?.focus({ preventScroll: true }));
34456
+ }
34457
+
34458
+ async function copyFailedOptionalFeatureCommands() {
34459
+ const commands = [...optionalFeatureInstallStates]
34460
+ .filter(([, state]) => state?.phase === "failed")
34461
+ .map(([featureId, state]) => state.command || optionalFeatureManualInstallCommand(OPTIONAL_FEATURE_BY_ID.get(featureId)))
34462
+ .filter(Boolean);
34463
+ if (!commands.length) {
34464
+ addEvent("no failed optional feature commands are available", "warn");
34465
+ return;
34466
+ }
34467
+ try {
34468
+ await copyText([...new Set(commands)].join("\n"));
34469
+ addEvent(`copied ${new Set(commands).size} failed optional feature command${new Set(commands).size === 1 ? "" : "s"}`, "info");
34470
+ } catch (error) {
34471
+ addEvent(`could not copy failed optional feature commands: ${error.message || String(error)}`, "warn");
34472
+ }
34473
+ }
34474
+
34475
+ async function refreshQuestionnaireFeatureAvailability(tabContext = activeTabContext()) {
34476
+ if (!tabContext.tabId) return false;
34477
+ try {
34478
+ const response = await api("/api/tools?scope=session", { tabId: tabContext.tabId });
34479
+ if (!isCurrentTabContext(tabContext)) return false;
34480
+ optionalFeatureAvailability.questionnaire = Array.isArray(response.data?.tools)
34481
+ && response.data.tools.some((tool) => tool?.name === "questionnaire");
32521
34482
  renderOptionalFeatureControls();
32522
34483
  return true;
34484
+ } catch {
34485
+ if (isCurrentTabContext(tabContext)) {
34486
+ optionalFeatureAvailability.questionnaire = false;
34487
+ renderOptionalFeatureControls();
34488
+ }
34489
+ return false;
34490
+ }
34491
+ }
34492
+
34493
+ async function refreshOptionalFeaturePackageStatuses({ announce = false } = {}) {
34494
+ try {
34495
+ const response = await api("/api/optional-features", { scoped: false });
34496
+ applyOptionalFeatureMigrationSnapshot(response.data, { announce: true });
34497
+ await refreshQuestionnaireFeatureAvailability();
34498
+ return true;
32523
34499
  } catch (error) {
34500
+ optionalFeaturePackageStatusesLoaded = false;
32524
34501
  optionalFeaturePackageStatusError = error.message || String(error);
32525
34502
  renderOptionalFeatureControls();
32526
34503
  if (announce) addEvent(`optional feature package status check failed: ${optionalFeaturePackageStatusError}`, "warn");
@@ -32635,8 +34612,10 @@ function updateOptionalFeatureAvailability() {
32635
34612
  }
32636
34613
 
32637
34614
  function optionalFeatureStatus(featureId) {
34615
+ const feature = OPTIONAL_FEATURE_BY_ID.get(featureId);
32638
34616
  const detected = isOptionalFeatureDetected(featureId);
32639
- const disabled = isOptionalFeatureDisabled(featureId);
34617
+ const managedWithTools = feature?.manageWith === "tools";
34618
+ const disabled = managedWithTools ? false : isOptionalFeatureDisabled(featureId);
32640
34619
  const packageStatus = optionalFeaturePackageStatus(featureId);
32641
34620
  const installMessage = optionalFeatureInstallMessages.get(featureId);
32642
34621
  const installState = optionalFeatureInstallState(featureId);
@@ -32647,26 +34626,52 @@ function optionalFeatureStatus(featureId) {
32647
34626
  return {
32648
34627
  label: optionalFeatureInstallPhaseLabel(installState),
32649
34628
  className: "updating",
32650
- detail: optionalFeatureInstallDetail(installState, installMessage || "npm install is running; waiting for package-manager output"),
32651
- hint: "The package manager may be quiet for a while; elapsed time updates here until npm exits.",
32652
- command: installState?.command || "",
34629
+ detail: optionalFeatureInstallDetail(installState, installMessage || "Pi install is running; waiting for installer output"),
34630
+ hint: "Pi may be quiet while resolving the package; elapsed time updates here until it exits.",
34631
+ command: installState?.command || optionalFeatureManualInstallCommand(feature),
32653
34632
  };
32654
34633
  }
32655
34634
  if (installState?.phase === "failed") {
32656
34635
  return {
32657
34636
  label: optionalFeatureInstallPhaseLabel(installState),
32658
34637
  className: "failed",
32659
- detail: optionalFeatureInstallDetail(installState, installState.detail || installMessage || "npm install failed"),
32660
- hint: installState.hint || "Copy the npm command and run it manually from the Web UI host for full diagnostics.",
32661
- command: installState.command || "",
34638
+ detail: optionalFeatureInstallDetail(installState, installState.detail || installMessage || "Pi install failed"),
34639
+ hint: installState.hint || "Copy the Pi command and run it manually from the Web UI host for full diagnostics.",
34640
+ command: installState.command || optionalFeatureManualInstallCommand(feature),
32662
34641
  };
32663
34642
  }
32664
34643
  const doneDetail = installState?.phase === "done" ? optionalFeatureInstallDetail(installState, installMessage) : "";
34644
+ if (disabled) return {
34645
+ label: "Disabled",
34646
+ className: "disabled",
34647
+ detail: `Disabled in this browser and excluded from migration selection${versionSuffix}`,
34648
+ hint: "Enable it in Optional features before installing or restoring it.",
34649
+ };
34650
+ if (!packageStatus && !detected) return { label: "Checking", className: "updating", detail: "Checking Pi installation and registration status…" };
34651
+ if (packageStatus?.resourceConflict) return {
34652
+ label: "Duplicate conflict",
34653
+ className: "failed",
34654
+ detail: `Configured both as a Pi package and as a top-level resource; remove one registration before reloading${versionSuffix}`,
34655
+ hint: "Do not install again. Keep either the package entry or the extensions/skills/prompts/themes alias, not both.",
34656
+ };
32665
34657
  if (packageStatus?.updateAvailable) return { label: "Update available", className: "updating", detail: packageStatus.updateReason || `Installed package is older than the Web UI expects${versionSuffix}` };
34658
+ if (detected && managedWithTools) return { label: "Loaded", className: "enabled", detail: doneDetail || `Detected in the active Pi tab; manage access in Tools${versionSuffix}`, command: installState?.command || "" };
32666
34659
  if (detected && !disabled) return { label: "Enabled", className: "enabled", detail: doneDetail || `Detected and enabled in Web UI${versionSuffix}`, command: installState?.command || "" };
32667
34660
  if (detected && disabled) return { label: "Disabled", className: "disabled", detail: `Detected, but disabled in Web UI${versionSuffix}` };
32668
- if (packageStatus?.installed) return { label: "Installed", className: "installed", detail: doneDetail || `Package is installed but not loaded in the active Pi tab${versionSuffix}`, command: installState?.command || "" };
32669
- return { label: "Install needed", className: "missing", detail: installMessage || "Package is not installed or not visible from the Web UI package root" };
34661
+ if (packageStatus?.locallyConfigured) return { label: "Available locally", className: "installed", detail: doneDetail || `Enabled as a top-level Pi resource; reload this tab if the capability is not detected yet${versionSuffix}` };
34662
+ if (packageStatus?.installed && packageStatus?.configured) return { label: "Installed", className: "installed", detail: doneDetail || `Registered with Pi but not loaded in the active tab${versionSuffix}`, command: installState?.command || "" };
34663
+ if (packageStatus?.installed && !packageStatus?.configured) return {
34664
+ label: "Registration needed",
34665
+ className: "missing",
34666
+ detail: doneDetail || `Package files exist, but the package is not registered in Pi settings${versionSuffix}`,
34667
+ command: optionalFeatureManualInstallCommand(feature),
34668
+ };
34669
+ return {
34670
+ label: "Install needed",
34671
+ className: "missing",
34672
+ detail: installMessage || "Package is not installed and registered with Pi",
34673
+ command: optionalFeatureManualInstallCommand(feature),
34674
+ };
32670
34675
  }
32671
34676
 
32672
34677
  function optionalFeatureTooltip(feature, status) {
@@ -32699,10 +34704,52 @@ function optionalFeatureWidgetHasSpecializedRenderer(key) {
32699
34704
  return key.startsWith("btw:") || key.startsWith("release-npm:") || key.startsWith("release-aur:") || key === AUR_REVIEW_RPC_WIDGET_KEY || key === "workflow:subprocess" || key === WORKFLOW_INSPECTOR_WIDGET_KEY;
32700
34705
  }
32701
34706
 
34707
+ function renderOptionalFeatureBatchToolbar() {
34708
+ const candidates = optionalFeatureBatchCandidates();
34709
+ const migratable = optionalFeatureMigrationCandidates();
34710
+ const busy = optionalFeatureBatchIsActive();
34711
+ const toolbar = make("div", "optional-feature-batch-toolbar");
34712
+ const action = make("button", "optional-feature-batch-action", busy ? "Installing…" : "Install all");
34713
+ action.type = "button";
34714
+ action.disabled = busy || optionalFeatureInstallInProgress.size > 0 || !optionalFeaturePackageStatusesLoaded || candidates.length === 0 || !!optionalFeaturePackageStatusError;
34715
+ action.setAttribute("aria-label", candidates.length
34716
+ ? `Install all ${candidates.length} missing or unregistered optional features`
34717
+ : "All optional features are installed and registered");
34718
+ if (busy) action.setAttribute("aria-busy", "true");
34719
+ action.addEventListener("click", () => installOptionalFeatureBatch(OPTIONAL_FEATURES, { scopeLabel: "all optional features" }));
34720
+
34721
+ const actionGroup = make("div", "optional-feature-batch-actions");
34722
+ if (migratable.length) {
34723
+ const migrate = make("button", "optional-feature-batch-action primary", "Migrate…");
34724
+ migrate.type = "button";
34725
+ migrate.disabled = busy || optionalFeatureInstallInProgress.size > 0;
34726
+ migrate.setAttribute("aria-label", `Migrate ${migratable.length} previously available optional feature${migratable.length === 1 ? "" : "s"}`);
34727
+ migrate.addEventListener("click", () => openOptionalFeatureMigrationDialog());
34728
+ actionGroup.append(migrate);
34729
+ }
34730
+ actionGroup.append(action);
34731
+
34732
+ let summary = !optionalFeaturePackageStatusesLoaded
34733
+ ? optionalFeaturePackageStatusError ? "Install availability unknown" : "Checking Pi package status…"
34734
+ : candidates.length ? `${candidates.length} missing or unregistered` : "All installed and registered";
34735
+ if (optionalFeatureMigrationSnapshot.phase === "checking") summary = "Checking optional features…";
34736
+ if (optionalFeatureBatchState?.phase === "running") {
34737
+ summary = optionalFeatureMigrationProgressText() || `Installing ${optionalFeatureBatchState.total} sequentially with Pi…`;
34738
+ } else if (["done", "failed"].includes(optionalFeatureBatchState?.phase)) {
34739
+ summary = `Batch finished: ${optionalFeatureBatchState.succeeded} succeeded, ${optionalFeatureBatchState.failed} failed.`;
34740
+ }
34741
+ const status = make("div", `optional-feature-batch-status${optionalFeatureBatchState?.failed ? " warning" : ""}`, summary);
34742
+ status.setAttribute("role", "status");
34743
+ status.setAttribute("aria-live", "polite");
34744
+ toolbar.append(status, actionGroup);
34745
+ return toolbar;
34746
+ }
34747
+
32702
34748
  function renderOptionalFeaturePanel() {
32703
34749
  if (!elements.optionalFeaturesBox) return;
32704
34750
  elements.optionalFeaturesBox.replaceChildren();
32705
34751
  elements.optionalFeaturesBox.classList.remove("muted");
34752
+ elements.optionalFeaturesBox.append(renderOptionalFeatureBatchToolbar());
32706
34753
 
32707
34754
  if (optionalFeaturePackageStatusError) {
32708
34755
  const notice = make("div", "optional-feature-panel-notice error");
@@ -32743,10 +34790,18 @@ function renderOptionalFeatureSection(section, features) {
32743
34790
  sectionNode.dataset.optionalFeatureSection = section.id;
32744
34791
 
32745
34792
  const header = make("div", "optional-feature-section-header");
32746
- header.append(
32747
- make("div", "optional-feature-section-title", section.label),
32748
- make("span", "optional-feature-section-count", String(features.length)),
32749
- );
34793
+ const headerActions = make("div", "optional-feature-section-actions");
34794
+ const candidates = optionalFeatureBatchCandidates(features);
34795
+ const installMissing = make("button", "optional-feature-section-install", optionalFeatureBatchIsActive() ? "Installing…" : "Install missing");
34796
+ installMissing.type = "button";
34797
+ installMissing.disabled = optionalFeatureBatchIsActive() || optionalFeatureInstallInProgress.size > 0 || !optionalFeaturePackageStatusesLoaded || candidates.length === 0 || !!optionalFeaturePackageStatusError;
34798
+ installMissing.setAttribute("aria-label", candidates.length
34799
+ ? `Install ${candidates.length} missing or unregistered features in ${section.label}`
34800
+ : `All features in ${section.label} are installed and registered`);
34801
+ if (optionalFeatureBatchIsActive()) installMissing.setAttribute("aria-busy", "true");
34802
+ installMissing.addEventListener("click", () => installOptionalFeatureBatch(features, { scopeLabel: section.label }));
34803
+ headerActions.append(make("span", "optional-feature-section-count", String(features.length)), installMissing);
34804
+ header.append(make("div", "optional-feature-section-title", section.label), headerActions);
32750
34805
  sectionNode.append(header);
32751
34806
  if (section.description) sectionNode.append(make("div", "optional-feature-section-description", section.description));
32752
34807
 
@@ -32768,6 +34823,7 @@ function renderOptionalFeatureRow(feature) {
32768
34823
  const tooltip = optionalFeatureTooltip(feature, status);
32769
34824
  row.dataset.tooltip = tooltip;
32770
34825
  row.setAttribute("aria-label", tooltip.replace(/\s+/g, " "));
34826
+ if (installing) row.setAttribute("aria-busy", "true");
32771
34827
  row.tabIndex = 0;
32772
34828
 
32773
34829
  const main = make("div", "optional-feature-main");
@@ -32776,7 +34832,8 @@ function renderOptionalFeatureRow(feature) {
32776
34832
  main.append(title);
32777
34833
  if (status.detail) {
32778
34834
  const detail = make("div", `optional-feature-detail ${status.className === "failed" ? "error" : ""}`.trim(), status.detail);
32779
- detail.setAttribute("aria-live", installing ? "polite" : "off");
34835
+ if (status.className === "failed" && !installing) detail.setAttribute("role", "alert");
34836
+ else detail.setAttribute("aria-live", installing ? "polite" : "off");
32780
34837
  main.append(detail);
32781
34838
  }
32782
34839
  if (installing) {
@@ -32796,7 +34853,7 @@ function renderOptionalFeatureRow(feature) {
32796
34853
  const actions = make("div", "optional-feature-actions");
32797
34854
  const action = make("button", "optional-feature-action");
32798
34855
  action.type = "button";
32799
- action.disabled = installing;
34856
+ action.disabled = installing || optionalFeatureBatchIsActive() || (!optionalFeaturePackageStatusesLoaded && !detected);
32800
34857
  if (installing) {
32801
34858
  action.textContent = installState?.actionLabel === "Update" ? "Updating…" : "Installing…";
32802
34859
  action.setAttribute("aria-busy", "true");
@@ -32805,10 +34862,19 @@ function renderOptionalFeatureRow(feature) {
32805
34862
  action.textContent = "Retry…";
32806
34863
  action.classList.add(retryAsUpdate ? "update" : "install");
32807
34864
  action.addEventListener("click", () => installOptionalFeature(feature.id, { update: retryAsUpdate }));
34865
+ } else if (isOptionalFeatureDisabled(feature.id)) {
34866
+ action.textContent = "Enable";
34867
+ action.addEventListener("click", () => setOptionalFeatureDisabled(feature.id, false));
34868
+ } else if (packageStatus?.resourceConflict) {
34869
+ action.textContent = "Conflict";
34870
+ action.disabled = true;
32808
34871
  } else if (packageStatus?.updateAvailable) {
32809
34872
  action.textContent = "Update…";
32810
34873
  action.classList.add("update");
32811
34874
  action.addEventListener("click", () => installOptionalFeature(feature.id, { update: true }));
34875
+ } else if (detected && feature.manageWith === "tools") {
34876
+ action.textContent = "Tools…";
34877
+ action.addEventListener("click", () => openNativeToolsSelector());
32812
34878
  } else if (detected) {
32813
34879
  action.textContent = enabled ? "Disable" : "Enable";
32814
34880
  action.addEventListener("click", async () => {
@@ -32837,7 +34903,7 @@ function renderOptionalFeatureRow(feature) {
32837
34903
  successMessage: `${feature.label} was ${disabled ? "re-enabled" : "disabled again"}.`,
32838
34904
  });
32839
34905
  });
32840
- } else if (packageStatus?.installed) {
34906
+ } else if (packageStatus?.ready) {
32841
34907
  action.textContent = "Reload";
32842
34908
  action.addEventListener("click", () => sendPrompt("prompt", "/reload"));
32843
34909
  } else {
@@ -32846,9 +34912,21 @@ function renderOptionalFeatureRow(feature) {
32846
34912
  action.addEventListener("click", () => installOptionalFeature(feature.id));
32847
34913
  }
32848
34914
  actions.append(action);
34915
+ if (failed) {
34916
+ const retryFailed = make("button", "optional-feature-action install", "Retry failed");
34917
+ retryFailed.type = "button";
34918
+ retryFailed.disabled = optionalFeatureBatchIsActive();
34919
+ retryFailed.addEventListener("click", () => {
34920
+ const audit = optionalFeatureAuditFeature(feature.id);
34921
+ if (audit?.state === "legacy-migratable") openOptionalFeatureMigrationDialog({ featureIds: [feature.id], retryFailed: true });
34922
+ else installOptionalFeature(feature.id, { update: packageStatus?.updateAvailable === true });
34923
+ });
34924
+ actions.replaceChildren(retryFailed);
34925
+ }
32849
34926
  if (status.command) {
32850
34927
  const copyCommand = make("button", "optional-feature-action copy-command", "Copy cmd");
32851
34928
  copyCommand.type = "button";
34929
+ copyCommand.disabled = optionalFeatureBatchIsActive();
32852
34930
  copyCommand.addEventListener("click", () => copyOptionalFeatureInstallCommand(feature.id));
32853
34931
  actions.append(copyCommand);
32854
34932
  }
@@ -32983,16 +35061,16 @@ function commandUnavailableMessage(commandName) {
32983
35061
 
32984
35062
  async function installOptionalFeature(featureId, { update = false } = {}) {
32985
35063
  const feature = OPTIONAL_FEATURE_BY_ID.get(featureId);
32986
- if (!feature || optionalFeatureInstallInProgress.has(featureId)) return;
35064
+ if (!feature || optionalFeatureInstallInProgress.has(featureId) || optionalFeatureBatchIsActive()) return;
32987
35065
 
32988
35066
  const actionLabel = update ? "Update" : "Install";
32989
35067
  const warning = [
32990
35068
  `${actionLabel} optional feature: ${feature.label}?`,
32991
35069
  "",
32992
- `This will run npm install for ${feature.packageName} in the Web UI package install root.`,
32993
- "It can download code from npm and modify the local Pi/Web UI npm installation.",
32994
- "Progress, elapsed time, the npm command, and actionable failures will be shown in the optional-features row and activity log.",
32995
- "If this feature is already installed but disabled in Pi settings, cancel and enable it there instead.",
35070
+ `This will run ${optionalFeatureManualInstallCommand(feature)} with the selected Pi CLI.`,
35071
+ "Pi can download code from npm and update its user package registration and package storage.",
35072
+ "Progress, elapsed time, the Pi command, and actionable failures will be shown in the optional-features row and activity log.",
35073
+ "Re-running the same Pi install command is the supported update path.",
32996
35074
  "",
32997
35075
  "Continue?",
32998
35076
  ].join("\n");
@@ -33000,34 +35078,34 @@ async function installOptionalFeature(featureId, { update = false } = {}) {
33000
35078
 
33001
35079
  const startedAt = Date.now();
33002
35080
  optionalFeatureInstallInProgress.add(featureId);
33003
- optionalFeatureInstallMessages.set(featureId, `${actionLabel} preparing; resolving Web UI package install root…`);
35081
+ optionalFeatureInstallMessages.set(featureId, `${actionLabel} preparing with Pi…`);
33004
35082
  setOptionalFeatureInstallState(featureId, {
33005
35083
  phase: "preparing",
33006
35084
  actionLabel,
33007
35085
  startedAt,
33008
35086
  endedAt: 0,
33009
- detail: "Resolving safe Web UI package install root…",
33010
- hint: "The package manager has not started yet.",
33011
- command: "",
35087
+ detail: "Resolving the selected Pi CLI…",
35088
+ hint: "The Pi installer has not started yet.",
35089
+ command: optionalFeatureManualInstallCommand(feature),
33012
35090
  outputTail: "",
33013
35091
  });
33014
35092
  startOptionalFeatureInstallProgressTimer(featureId);
33015
- addEvent(`${update ? "updating" : "installing"} optional feature ${feature.label} (${feature.packageName})…`, "warn");
35093
+ addEvent(`${update ? "updating" : "installing"} optional feature ${feature.label} (${feature.packageName}) with Pi…`, "warn");
33016
35094
  setTimeout(() => {
33017
35095
  const state = optionalFeatureInstallState(featureId);
33018
35096
  if (optionalFeatureInstallInProgress.has(featureId) && state?.startedAt === startedAt && state.phase === "preparing") {
33019
- optionalFeatureInstallMessages.set(featureId, `${actionLabel} running via npm; waiting for package-manager output…`);
35097
+ optionalFeatureInstallMessages.set(featureId, `${actionLabel} running via Pi; waiting for installer output…`);
33020
35098
  setOptionalFeatureInstallState(featureId, {
33021
35099
  phase: "installing",
33022
- detail: "npm install is running; waiting for package-manager output…",
33023
- hint: "npm can be quiet while resolving packages. Keep this page open; elapsed time updates here.",
35100
+ detail: "Pi install is running; waiting for installer output…",
35101
+ hint: "Pi may be quiet while resolving the npm package. Keep this page open; elapsed time updates here.",
33024
35102
  });
33025
35103
  }
33026
35104
  }, 1200);
33027
35105
 
33028
35106
  try {
33029
35107
  const response = await api("/api/optional-feature-install", { method: "POST", body: { featureId }, scoped: false });
33030
- const command = response.data?.command || "";
35108
+ const command = response.data?.command || optionalFeatureManualInstallCommand(feature);
33031
35109
  disabledOptionalFeatures.delete(featureId);
33032
35110
  storeDisabledOptionalFeatures();
33033
35111
  optionalFeatureInstallMessages.set(featureId, response.data?.message || `${actionLabel} finished`);
@@ -33035,24 +35113,24 @@ async function installOptionalFeature(featureId, { update = false } = {}) {
33035
35113
  phase: "refreshing",
33036
35114
  actionLabel,
33037
35115
  startedAt,
33038
- detail: "npm finished; checking package status and refreshed Web UI capabilities…",
33039
- hint: "If the package is installed but not detected, reload the active Pi tab.",
35116
+ detail: "Pi finished; checking installation and registration status…",
35117
+ hint: "Reload the active Pi tab to load newly registered resources.",
33040
35118
  command,
33041
35119
  outputTail: "",
33042
35120
  });
33043
- addEvent(response.data?.message || `${update ? "updated" : "installed"} ${feature.packageName}`, "info");
35121
+ addEvent(response.data?.message || `${update ? "updated" : "installed"} ${feature.packageName} with Pi`, "info");
33044
35122
  const output = [response.data?.stderr, response.data?.stdout].filter(Boolean).join("\n").trim();
33045
- if (output) addEvent(`npm output for ${feature.packageName}:\n${output.slice(-4000)}`, "info");
35123
+ if (output) addEvent(`Pi install output for ${feature.packageName}:\n${output.slice(-4000)}`, "info");
33046
35124
  await refreshOptionalFeaturePackageStatuses({ announce: true });
33047
35125
  setOptionalFeatureInstallState(featureId, {
33048
35126
  phase: "done",
33049
35127
  actionLabel,
33050
35128
  endedAt: Date.now(),
33051
- detail: response.data?.message || `${actionLabel} finished. Reload the active Pi tab to load newly installed resources.`,
35129
+ detail: response.data?.message || `${actionLabel} finished. Reload the active Pi tab to load newly registered resources.`,
33052
35130
  hint: "Use Reload if this row still says Installed instead of Enabled.",
33053
35131
  command,
33054
35132
  });
33055
- if (await appConfirmText(`${feature.label} ${actionLabel.toLowerCase()} finished. Reload the active Pi tab now to enable newly loaded resources?`, { affected: "The active Pi tab", confirmLabel: "Reload tab", danger: false })) {
35133
+ if (await appConfirmText(`${feature.label} ${actionLabel.toLowerCase()} finished. Reload the active Pi tab now to load its resources?`, { affected: "The active Pi tab", confirmLabel: "Reload tab", danger: false })) {
33056
35134
  sendPrompt("prompt", "/reload");
33057
35135
  } else {
33058
35136
  const tabContext = activeTabContext();
@@ -33068,7 +35146,7 @@ async function installOptionalFeature(featureId, { update = false } = {}) {
33068
35146
  endedAt: Date.now(),
33069
35147
  detail: failure.message,
33070
35148
  hint: failure.hint,
33071
- command: failure.command || optionalFeatureInstallState(featureId)?.command || "",
35149
+ command: failure.command || optionalFeatureInstallState(featureId)?.command || optionalFeatureManualInstallCommand(feature),
33072
35150
  outputTail: failure.outputTail || "",
33073
35151
  errorKind: failure.kind || "unknown",
33074
35152
  });
@@ -33080,6 +35158,221 @@ async function installOptionalFeature(featureId, { update = false } = {}) {
33080
35158
  }
33081
35159
  }
33082
35160
 
35161
+ async function installOptionalFeatureBatch(features, { scopeLabel = "optional features" } = {}) {
35162
+ if (optionalFeatureBatchIsActive() || optionalFeatureInstallInProgress.size > 0) return;
35163
+ const candidates = optionalFeatureBatchCandidates(features);
35164
+ if (!candidates.length) {
35165
+ addEvent(`no missing or unregistered ${scopeLabel} to install`, "info");
35166
+ return;
35167
+ }
35168
+
35169
+ const warning = [
35170
+ `Install ${candidates.length} missing or unregistered ${scopeLabel}?`,
35171
+ "",
35172
+ "The selected Pi CLI will run one install command at a time:",
35173
+ ...candidates.map((feature) => optionalFeatureManualInstallCommand(feature)),
35174
+ "",
35175
+ "Pi can download code from npm and update its user package registration and package storage.",
35176
+ "The batch continues after individual failures and reports every result.",
35177
+ "The affected tab restarts automatically only when idle; busy work is never interrupted.",
35178
+ "",
35179
+ "Continue?",
35180
+ ].join("\n");
35181
+ if (!(await appConfirmText(warning, {
35182
+ affected: `${candidates.length} optional feature package${candidates.length === 1 ? "" : "s"}`,
35183
+ confirmLabel: candidates.length === 1 ? "Install feature" : "Install features",
35184
+ }))) return;
35185
+
35186
+ await runOptionalFeatureBatch(candidates, {
35187
+ scopeLabel,
35188
+ migration: false,
35189
+ signatureFeatureIds: candidates.map((feature) => feature.id),
35190
+ candidateSignature: optionalFeatureCandidateSignature(optionalFeatureMigrationSnapshot, candidates.map((feature) => feature.id)),
35191
+ reopen: () => installOptionalFeatureBatch(features, { scopeLabel }),
35192
+ });
35193
+ }
35194
+
35195
+ async function postOptionalFeatureBatch({ featureIds, migration, signatureFeatureIds, candidateSignature, retryOnStale = true }) {
35196
+ const submit = () => api("/api/optional-feature-install-batch", {
35197
+ method: "POST",
35198
+ body: { tab: activeTabId, featureIds, revision: optionalFeatureMigrationSnapshot.revision, migration },
35199
+ scoped: false,
35200
+ });
35201
+ try {
35202
+ return await submit();
35203
+ } catch (error) {
35204
+ const staleRevision = error.statusCode === 409 && /stale|revision/i.test(error.message || "");
35205
+ if (!staleRevision || !retryOnStale) throw error;
35206
+ await refreshOptionalFeaturePackageStatuses();
35207
+ const refreshedSignature = optionalFeatureCandidateSignature(optionalFeatureMigrationSnapshot, signatureFeatureIds);
35208
+ if (refreshedSignature !== candidateSignature) {
35209
+ error.optionalFeatureCandidatesChanged = true;
35210
+ throw error;
35211
+ }
35212
+ try {
35213
+ return await submit();
35214
+ } catch (retryError) {
35215
+ const stillStale = retryError.statusCode === 409 && /stale|revision/i.test(retryError.message || "");
35216
+ if (stillStale) retryError.optionalFeatureRevisionChurn = true;
35217
+ throw retryError;
35218
+ }
35219
+ }
35220
+ }
35221
+
35222
+ function restoreOptionalFeatureInstallStates(previousStates) {
35223
+ for (const [featureId, state] of previousStates) {
35224
+ if (state) optionalFeatureInstallStates.set(featureId, state);
35225
+ else optionalFeatureInstallStates.delete(featureId);
35226
+ }
35227
+ }
35228
+
35229
+ async function runOptionalFeatureBatch(candidates, {
35230
+ scopeLabel = "optional features",
35231
+ migration = false,
35232
+ signatureFeatureIds = candidates.map((feature) => feature.id),
35233
+ candidateSignature = optionalFeatureCandidateSignature(optionalFeatureMigrationSnapshot, signatureFeatureIds),
35234
+ reopen = null,
35235
+ } = {}) {
35236
+ if (!candidates.length || optionalFeatureBatchIsActive() || optionalFeatureInstallInProgress.size > 0) return;
35237
+ const startedAt = Date.now();
35238
+ const actionLabel = migration ? "Migrate" : "Install";
35239
+ const featureIds = candidates.map((feature) => feature.id);
35240
+ const previousStates = new Map(candidates.map((feature) => [feature.id, optionalFeatureInstallState(feature.id)]));
35241
+ optionalFeatureBatchState = { phase: "running", scopeLabel, total: candidates.length, succeeded: 0, failed: 0, startedAt };
35242
+ candidates.forEach((feature, index) => {
35243
+ optionalFeatureInstallInProgress.add(feature.id);
35244
+ optionalFeatureInstallMessages.set(feature.id, `Queued (${index + 1} of ${candidates.length})…`);
35245
+ setOptionalFeatureInstallState(feature.id, {
35246
+ phase: "installing",
35247
+ actionLabel,
35248
+ startedAt,
35249
+ endedAt: 0,
35250
+ detail: `Installing ${index + 1} of ${candidates.length}: ${feature.label}`,
35251
+ hint: "Pi installs sequentially and continues after individual failures.",
35252
+ command: optionalFeatureManualInstallCommand(feature),
35253
+ outputTail: "",
35254
+ });
35255
+ startOptionalFeatureInstallProgressTimer(feature.id);
35256
+ });
35257
+ addEvent(`installing ${candidates.length} ${scopeLabel} sequentially with Pi`, "warn");
35258
+
35259
+ try {
35260
+ const response = await postOptionalFeatureBatch({ featureIds, migration, signatureFeatureIds, candidateSignature });
35261
+ const results = Array.isArray(response.data?.results) ? response.data.results : [];
35262
+ const resultByFeatureId = new Map(results.map((result) => [result?.featureId, result]));
35263
+ let succeeded = 0;
35264
+ let failed = 0;
35265
+
35266
+ for (const feature of candidates) {
35267
+ const result = resultByFeatureId.get(feature.id);
35268
+ if (result?.ok === true) {
35269
+ succeeded += 1;
35270
+ const data = result.data || {};
35271
+ const command = data.command || optionalFeatureManualInstallCommand(feature);
35272
+ optionalFeatureInstallMessages.set(feature.id, data.message || "Installed and registered with Pi");
35273
+ setOptionalFeatureInstallState(feature.id, {
35274
+ phase: "done",
35275
+ actionLabel,
35276
+ startedAt,
35277
+ endedAt: Date.now(),
35278
+ detail: data.message || "Installed and verified with Pi.",
35279
+ hint: response.data?.restart?.autoRestarted ? "The affected tab restarted automatically." : "The server verified this package registration.",
35280
+ command,
35281
+ outputTail: "",
35282
+ });
35283
+ const output = [data.stderr, data.stdout].filter(Boolean).join("\n").trim().slice(-4000);
35284
+ if (output) addEvent(`Pi install output for ${feature.packageName}:\n${output}`, "info");
35285
+ addEvent(data.message || `installed ${feature.packageName} with Pi`, "info");
35286
+ } else {
35287
+ failed += 1;
35288
+ const failure = optionalFeatureInstallFailureFromBatchResult(result, feature);
35289
+ optionalFeatureInstallMessages.set(feature.id, `${actionLabel} failed: ${failure.message}`);
35290
+ setOptionalFeatureInstallState(feature.id, {
35291
+ phase: "failed",
35292
+ actionLabel,
35293
+ startedAt,
35294
+ endedAt: Date.now(),
35295
+ detail: failure.message,
35296
+ hint: failure.hint,
35297
+ command: failure.command,
35298
+ outputTail: String(failure.outputTail || "").slice(-4000),
35299
+ errorKind: failure.kind || "unknown",
35300
+ });
35301
+ addEvent(`${actionLabel.toLowerCase()} optional feature ${feature.label} failed: ${failure.message}${failure.hint ? `\nHint: ${failure.hint}` : ""}`, "error");
35302
+ }
35303
+ }
35304
+
35305
+ optionalFeatureBatchState = { phase: failed ? "failed" : "done", scopeLabel, total: candidates.length, succeeded, failed, startedAt, endedAt: Date.now() };
35306
+ const restart = response.data?.restart || {};
35307
+ if (restart.autoRestarted || restart.restartDeferred) {
35308
+ optionalFeatureRestartNotice = { ...restart, tabId: activeTabId };
35309
+ addEvent(restart.autoRestarted ? "restarted tab to load new optional features" : "optional feature restart deferred because the tab is busy", restart.restartDeferred ? "warn" : "info");
35310
+ }
35311
+ await refreshOptionalFeaturePackageStatuses({ announce: true });
35312
+ addEvent(`optional feature batch finished: ${succeeded} succeeded, ${failed} failed`, failed ? "warn" : "info");
35313
+ renderOptionalFeatureMigrationSurface();
35314
+ // Backend-owned idle restart replaces the legacy post-batch prompt (formerly confirmLabel: "Reload tab").
35315
+ } catch (error) {
35316
+ if (error.optionalFeatureCandidatesChanged || error.optionalFeatureRevisionChurn) {
35317
+ restoreOptionalFeatureInstallStates(previousStates);
35318
+ optionalFeatureBatchState = null;
35319
+ if (error.optionalFeatureRevisionChurn) await refreshOptionalFeaturePackageStatuses();
35320
+ addEvent(error.optionalFeatureRevisionChurn
35321
+ ? "optional feature audit changed repeatedly; refreshed the plan before asking again"
35322
+ : "optional feature choices changed while confirmation was open; refreshed the current migration plan", "warn");
35323
+ if (typeof reopen === "function") setTimeout(reopen, 0);
35324
+ } else if (error.statusCode === 409 && /already in progress|mutation|busy/i.test(error.message || "")) {
35325
+ restoreOptionalFeatureInstallStates(previousStates);
35326
+ optionalFeatureBatchState = null;
35327
+ await refreshOptionalFeaturePackageStatuses();
35328
+ addEvent("another optional feature operation is already running; recovered its server-owned progress", "warn");
35329
+ } else {
35330
+ const failure = optionalFeatureInstallFailureFromError(error);
35331
+ for (const feature of candidates) {
35332
+ optionalFeatureInstallMessages.set(feature.id, `Batch request failed: ${failure.message}`);
35333
+ setOptionalFeatureInstallState(feature.id, {
35334
+ phase: "failed",
35335
+ actionLabel,
35336
+ startedAt,
35337
+ endedAt: Date.now(),
35338
+ detail: failure.message,
35339
+ hint: failure.hint,
35340
+ command: failure.command || optionalFeatureManualInstallCommand(feature),
35341
+ outputTail: String(failure.outputTail || "").slice(-4000),
35342
+ errorKind: failure.kind || "batch-request",
35343
+ });
35344
+ }
35345
+ optionalFeatureBatchState = { phase: "failed", scopeLabel, total: candidates.length, succeeded: 0, failed: candidates.length, startedAt, endedAt: Date.now() };
35346
+ addEvent(`optional feature batch request failed: ${failure.message}${failure.hint ? `\nHint: ${failure.hint}` : ""}`, "error");
35347
+ }
35348
+ } finally {
35349
+ for (const feature of candidates) {
35350
+ optionalFeatureInstallInProgress.delete(feature.id);
35351
+ clearOptionalFeatureInstallProgressTimer(feature.id);
35352
+ }
35353
+ renderOptionalFeatureControls();
35354
+ renderOptionalFeatureMigrationSurface();
35355
+ }
35356
+ }
35357
+
35358
+ async function migrateSelectedOptionalFeatures() {
35359
+ const state = optionalFeatureMigrationDialogState;
35360
+ if (!state || optionalFeatureBatchIsActive()) return;
35361
+ const selectedIds = [...state.selected].filter((featureId) => !isOptionalFeatureDisabled(featureId));
35362
+ const candidates = selectedIds.map((featureId) => OPTIONAL_FEATURE_BY_ID.get(featureId)).filter(Boolean);
35363
+ if (!candidates.length) return;
35364
+ elements.optionalFeatureMigrationConfirmButton.disabled = true;
35365
+ elements.optionalFeatureMigrationDialogError.hidden = true;
35366
+ elements.optionalFeatureMigrationDialog.close();
35367
+ await runOptionalFeatureBatch(candidates, {
35368
+ scopeLabel: state.retryFailed ? "failed optional features" : "previous optional features",
35369
+ migration: true,
35370
+ signatureFeatureIds: state.featureIds,
35371
+ candidateSignature: state.signature,
35372
+ reopen: () => openOptionalFeatureMigrationDialog({ featureIds: state.featureIds, retryFailed: state.retryFailed }),
35373
+ });
35374
+ }
35375
+
33083
35376
  function runPublishWorkflow(command) {
33084
35377
  setComposerActionsOpen(false);
33085
35378
  setPublishMenuOpen(false);
@@ -33122,6 +35415,176 @@ async function runNativeCommandMenu(command) {
33122
35415
  await sendPrompt("prompt", command);
33123
35416
  }
33124
35417
 
35418
+ function normalizeSessionSummaryClientState(value, previous = null, { resetProjection = false } = {}) {
35419
+ if (!value || typeof value !== "object" || Array.isArray(value) || value.version !== SESSION_SUMMARY_PROTOCOL_VERSION) return null;
35420
+ const status = ["idle", "generating", "success", "failure"].includes(value.status) ? value.status : "idle";
35421
+ const title = typeof value.title === "string" && value.title.length <= 44 && !/[\r\n]/.test(value.title) ? value.title.trim() : "";
35422
+ const summaryMarkdown = typeof value.summaryMarkdown === "string" && value.summaryMarkdown.length <= SESSION_SUMMARY_MARKDOWN_MAX_CHARS
35423
+ ? value.summaryMarkdown.trim()
35424
+ : "";
35425
+ const message = typeof value.message === "string" ? value.message.replace(/[\r\n]+/g, " ").slice(0, 512).trim() : "";
35426
+ const sessionId = typeof value.sessionId === "string" ? value.sessionId.slice(0, 128) : previous?.sessionId || "";
35427
+ const sessionChanged = !!(sessionId && previous?.sessionId && sessionId !== previous.sessionId);
35428
+ const inherited = resetProjection || sessionChanged ? null : previous;
35429
+ return {
35430
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
35431
+ status,
35432
+ configured: value.configured === true,
35433
+ enabled: value.enabled === true,
35434
+ durable: value.durable === true,
35435
+ sessionId,
35436
+ title: title || inherited?.title || "",
35437
+ summaryMarkdown: summaryMarkdown || inherited?.summaryMarkdown || "",
35438
+ message,
35439
+ updatedAt: typeof value.updatedAt === "string" ? value.updatedAt : new Date().toISOString(),
35440
+ };
35441
+ }
35442
+
35443
+ function sessionSummaryStateForTab(tabId = activeTabId) {
35444
+ if (!tabId) return null;
35445
+ const cached = sessionSummaryByTab.get(tabId);
35446
+ if (cached) return cached;
35447
+ const metadata = tabs.find((tab) => tab.id === tabId)?.sessionSummary;
35448
+ const normalized = normalizeSessionSummaryClientState(metadata);
35449
+ if (normalized) sessionSummaryByTab.set(tabId, normalized);
35450
+ return normalized;
35451
+ }
35452
+
35453
+ function renderSessionSummaryControls() {
35454
+ const available = !!activeTabId && hasAvailableCommand("summary", { tabId: activeTabId });
35455
+ const setupAvailable = !!activeTabId && hasAvailableCommand("summary-setup", { tabId: activeTabId });
35456
+ const state = sessionSummaryStateForTab(activeTabId);
35457
+ const status = state?.status === "generating" ? "Generating session summary…" : state?.status === "failure" ? `Session summary failed: ${state.message || "unknown error"}` : state?.summaryMarkdown ? "Open the latest session summary" : "Open or create a session summary";
35458
+ for (const button of [elements.summaryHeaderButton, elements.summaryActionButton]) {
35459
+ if (!button) continue;
35460
+ button.hidden = !available;
35461
+ button.disabled = !available || state?.status === "generating";
35462
+ button.setAttribute("aria-busy", state?.status === "generating" ? "true" : "false");
35463
+ applyStyledTooltip(button, status, { ariaLabel: status, align: "end" });
35464
+ }
35465
+ if (elements.optionsSummarySetupButton) elements.optionsSummarySetupButton.hidden = !setupAvailable;
35466
+ }
35467
+
35468
+ function closeSessionSummaryOverlay({ restoreFocus = true } = {}) {
35469
+ const overlay = elements.sessionSummaryOverlay;
35470
+ if (!overlay || overlay.hidden) return;
35471
+ overlay.hidden = true;
35472
+ const focusReturn = sessionSummaryOverlayFocusReturn;
35473
+ sessionSummaryOverlayTabId = null;
35474
+ sessionSummaryOverlayFocusReturn = null;
35475
+ if (restoreFocus && focusReturn?.isConnected) queueMicrotask(() => focusReturn.focus({ preventScroll: true }));
35476
+ }
35477
+
35478
+ function renderSessionSummaryOverlay() {
35479
+ const overlay = elements.sessionSummaryOverlay;
35480
+ if (!overlay || overlay.hidden || !sessionSummaryOverlayTabId) return;
35481
+ const tab = tabs.find((item) => item.id === sessionSummaryOverlayTabId);
35482
+ const state = sessionSummaryStateForTab(sessionSummaryOverlayTabId);
35483
+ elements.sessionSummaryOverlayTitle.textContent = state?.title || "Session summary";
35484
+ elements.sessionSummaryOverlayMeta.textContent = `${tab?.title || "Pi terminal"}${state?.durable === false ? " · in-memory session" : ""}`;
35485
+ const generating = state?.status === "generating";
35486
+ const failed = state?.status === "failure";
35487
+ elements.sessionSummaryOverlayStatus.textContent = generating
35488
+ ? "Generating with the configured background model…"
35489
+ : failed
35490
+ ? state.message || "Summary generation failed. The previous successful summary is preserved."
35491
+ : state?.summaryMarkdown
35492
+ ? "Latest successful active-branch summary."
35493
+ : "No successful summary is available yet.";
35494
+ elements.sessionSummaryOverlayStatus.classList.toggle("error", failed);
35495
+ elements.sessionSummaryOverlayBody.replaceChildren();
35496
+ if (state?.summaryMarkdown) renderMarkdown(elements.sessionSummaryOverlayBody, state.summaryMarkdown);
35497
+ else elements.sessionSummaryOverlayBody.append(make("p", "muted", generating ? "Waiting for the first validated Markdown result…" : "Generate a summary to populate this view."));
35498
+ elements.sessionSummaryOverlayCopyButton.disabled = !state?.summaryMarkdown;
35499
+ elements.sessionSummaryOverlayRefreshButton.disabled = generating;
35500
+ elements.sessionSummaryOverlayRefreshButton.textContent = generating ? "Generating…" : "Refresh";
35501
+ }
35502
+
35503
+ function openSessionSummaryOverlay(tabId, { loading = false } = {}) {
35504
+ if (!tabId || !elements.sessionSummaryOverlay) return;
35505
+ sessionSummaryOverlayFocusReturn = document.activeElement instanceof HTMLElement ? document.activeElement : null;
35506
+ sessionSummaryOverlayTabId = tabId;
35507
+ if (loading) {
35508
+ const previous = sessionSummaryStateForTab(tabId);
35509
+ sessionSummaryByTab.set(tabId, normalizeSessionSummaryClientState({
35510
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
35511
+ status: "generating",
35512
+ configured: true,
35513
+ enabled: previous?.enabled === true,
35514
+ durable: previous?.durable === true,
35515
+ updatedAt: new Date().toISOString(),
35516
+ }, previous));
35517
+ }
35518
+ elements.sessionSummaryOverlay.hidden = false;
35519
+ renderSessionSummaryOverlay();
35520
+ }
35521
+
35522
+ function updateSessionSummaryForTab(tabId, value, { resetProjection = false } = {}) {
35523
+ if (!tabId) return null;
35524
+ const normalized = normalizeSessionSummaryClientState(value, sessionSummaryByTab.get(tabId), { resetProjection });
35525
+ if (!normalized) return null;
35526
+ sessionSummaryByTab.set(tabId, normalized);
35527
+ if (tabId === activeTabId) renderSessionSummaryControls();
35528
+ if (sessionSummaryOverlayTabId === tabId) renderSessionSummaryOverlay();
35529
+ return normalized;
35530
+ }
35531
+
35532
+ async function requestSessionSummaryGeneration(tabId, { refresh = false } = {}) {
35533
+ const previous = sessionSummaryStateForTab(tabId);
35534
+ updateSessionSummaryForTab(tabId, {
35535
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
35536
+ status: "generating",
35537
+ configured: true,
35538
+ enabled: previous?.enabled === true,
35539
+ durable: previous?.durable === true,
35540
+ updatedAt: new Date().toISOString(),
35541
+ });
35542
+ try {
35543
+ const signal = globalThis.AbortSignal?.timeout?.(SESSION_SUMMARY_REQUEST_TIMEOUT_MS);
35544
+ const response = await api("/api/session-summary/generate", { method: "POST", body: { refresh }, tabId, signal });
35545
+ if (response.data?.summary) updateSessionSummaryForTab(tabId, response.data.summary);
35546
+ if (response.data?.tab) applyTabMetadata(response.data.tab);
35547
+ return response;
35548
+ } catch (error) {
35549
+ updateSessionSummaryForTab(tabId, {
35550
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
35551
+ status: "failure",
35552
+ configured: true,
35553
+ enabled: previous?.enabled === true,
35554
+ durable: previous?.durable === true,
35555
+ message: error.message || String(error),
35556
+ updatedAt: new Date().toISOString(),
35557
+ });
35558
+ throw error;
35559
+ }
35560
+ }
35561
+
35562
+ async function openSessionSummaryForTab(tabId = activeTabId, { refresh = false } = {}) {
35563
+ if (!tabId || !hasAvailableCommand("summary", { tabId })) return;
35564
+ let state = sessionSummaryStateForTab(tabId);
35565
+ if (!state?.configured) {
35566
+ const response = await api("/api/session-summary/preferences", { tabId });
35567
+ state = updateSessionSummaryForTab(tabId, response.data?.summary || {
35568
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
35569
+ status: "idle",
35570
+ configured: response.data?.preferences?.configured === true,
35571
+ enabled: response.data?.preferences?.enabled === true,
35572
+ durable: false,
35573
+ updatedAt: new Date().toISOString(),
35574
+ });
35575
+ if (!response.data?.preferences?.configured) {
35576
+ await openNativeSessionSummarySetupDialog({ initialData: response.data });
35577
+ return;
35578
+ }
35579
+ }
35580
+ openSessionSummaryOverlay(tabId, { loading: refresh || !state?.summaryMarkdown });
35581
+ if (refresh || !state?.summaryMarkdown) await requestSessionSummaryGeneration(tabId, { refresh }).catch(() => {});
35582
+ }
35583
+
35584
+ function handleSessionSummaryEvent(event) {
35585
+ updateSessionSummaryForTab(event?.tabId, event?.summary, { resetProjection: event?.kind === "state" });
35586
+ }
35587
+
33125
35588
  function slashCommandName(message) {
33126
35589
  const match = String(message || "").trim().match(/^\/([^\s]+)$/);
33127
35590
  return match ? match[1].toLowerCase() : "";
@@ -33386,6 +35849,19 @@ function nativeSettingToggle(label, checked, hint, badge) {
33386
35849
  return { field, input };
33387
35850
  }
33388
35851
 
35852
+ function nativeSettingTextarea(label, value, hint, { maxLength = SESSION_SUMMARY_PROMPT_MAX_CHARS, rows = 6, badge } = {}) {
35853
+ const field = make("label", "native-settings-field native-settings-textarea-field");
35854
+ field.append(nativeSettingsLabelRow(label, badge));
35855
+ const textarea = make("textarea", "dialog-editor native-settings-textarea");
35856
+ textarea.value = String(value || "");
35857
+ textarea.maxLength = maxLength;
35858
+ textarea.rows = rows;
35859
+ textarea.spellcheck = true;
35860
+ field.append(textarea);
35861
+ if (hint) field.append(make("span", "native-settings-hint", hint));
35862
+ return { field, textarea };
35863
+ }
35864
+
33389
35865
  function nativeSettingsSection(title, description, controls, { open = true, badge } = {}) {
33390
35866
  const section = make("details", "native-settings-section");
33391
35867
  section.open = !!open;
@@ -33900,6 +36376,149 @@ function gitWorkflowSetupModelKey(model) {
33900
36376
  return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
33901
36377
  }
33902
36378
 
36379
+ async function openNativeSessionSummarySetupDialog({ initialData = null, onSaved } = {}) {
36380
+ nativeCommandTabId = activeTabId;
36381
+ openNativeCommandDialog({
36382
+ title: "/summary-setup",
36383
+ message: "Configure persistent background titles and Markdown summaries. Saving confirms the disclosure below, then immediately generates and opens the first summary.",
36384
+ });
36385
+ renderNativeLoading("Loading session summary preferences and available models…");
36386
+
36387
+ let data = initialData;
36388
+ if (!data) {
36389
+ try {
36390
+ const response = await nativeCommandApi("/api/session-summary/preferences");
36391
+ data = response.data || {};
36392
+ } catch (error) {
36393
+ setNativeCommandError(error.message || String(error));
36394
+ elements.nativeCommandBody.replaceChildren();
36395
+ return;
36396
+ }
36397
+ }
36398
+
36399
+ const preferences = data.preferences || {};
36400
+ const models = Array.isArray(data.models) ? data.models : [];
36401
+ if (!models.length) {
36402
+ setNativeCommandError("No authenticated Pi models are available. Run /login or configure a provider first.");
36403
+ elements.nativeCommandBody.replaceChildren();
36404
+ return;
36405
+ }
36406
+ const configuredKey = `${preferences.model?.provider || ""}/${preferences.model?.modelId || ""}`;
36407
+ const defaultKey = "openai-codex/gpt-5.6-luna";
36408
+ const modelKeys = new Set(models.map(gitWorkflowSetupModelKey));
36409
+ const initialModelKey = modelKeys.has(configuredKey) ? configuredKey : modelKeys.has(defaultKey) ? defaultKey : gitWorkflowSetupModelKey(models[0]);
36410
+ const modelOptions = models.map((model) => ({
36411
+ value: gitWorkflowSetupModelKey(model),
36412
+ label: `${gitWorkflowSetupModelKey(model)}${model.name && model.name !== model.id ? ` · ${model.name}` : ""}`,
36413
+ }));
36414
+ const controls = {
36415
+ model: nativeSettingSelect("Summary model", initialModelKey, modelOptions, "Dedicated authenticated provider/model. No fallback is used.", { label: "required", tone: "safety" }),
36416
+ thinking: nativeSettingSelect("Reasoning effort", preferences.model?.thinkingLevel || "low", SETTINGS_THINKING_OPTIONS, "Only levels supported by the selected model are offered.", { label: "required", tone: "safety" }),
36417
+ automatic: nativeSettingToggle("Generate automatically", preferences.enabled === true, "After eligible settled turns; automatic updates remain silent.", { label: "cost", tone: "safety" }),
36418
+ titleEnabled: nativeSettingToggle("Update generated titles", preferences.title?.enabled !== false, "Only default/automatic tab titles are eligible. Explicit names always win.", { label: "safe", tone: "safety" }),
36419
+ cadence: nativeSettingSelect("Title update cadence", preferences.title?.minSettledTurns || 3, [1, 2, 3, 5, 10, 20].map((value) => ({ value: String(value), label: `${value} settled user turn${value === 1 ? "" : "s"}` })), "Minimum turns between changed generated titles after the first title.", { label: "saved", tone: "browser" }),
36420
+ injectLatest: nativeSettingToggle("Inject latest summary into main-agent context", preferences.context?.injectLatest === true, "Off by default. When enabled, exactly one latest active-branch summary is injected as reference-only data.", { label: "privacy", tone: "safety" }),
36421
+ titlePrompt: nativeSettingTextarea("Editable title prompt", preferences.prompts?.title, "Maximum 8 KiB. This text is untrusted data, not system authority.", { rows: 4, badge: { label: "prompt", tone: "browser" } }),
36422
+ summaryPrompt: nativeSettingTextarea("Editable Markdown summary prompt", preferences.prompts?.summary, "Maximum 8 KiB. Generated Markdown is validated and capped at 16 KiB.", { rows: 7, badge: { label: "prompt", tone: "browser" } }),
36423
+ };
36424
+ const thinkingLevelsForModel = (modelKey) => {
36425
+ const levels = data.modelThinkingLevels?.[modelKey];
36426
+ return Array.isArray(levels) && levels.length ? levels : ["off"];
36427
+ };
36428
+ const syncThinkingLevels = () => {
36429
+ const current = controls.thinking.select.value || preferences.model?.thinkingLevel || "low";
36430
+ replaceNativeSettingSelectOptions(controls.thinking.select, thinkingLevelsForModel(controls.model.select.value), current);
36431
+ };
36432
+ controls.model.select.addEventListener("change", syncThinkingLevels);
36433
+ syncThinkingLevels();
36434
+
36435
+ const disclosure = data.disclosure || {};
36436
+ const body = make("div", "native-settings-panel session-summary-setup-panel");
36437
+ body.append(
36438
+ nativeSettingsNote("Privacy scope", disclosure.scope || "Active-branch user text, final assistant text, and tool names only. Thinking, images, tool arguments/results, credentials, and prior summaries are excluded."),
36439
+ nativeSettingsNote("Cost and provider behavior", disclosure.cost || "One configured-model request per eligible refresh; no provider fallback or automatic retry."),
36440
+ nativeSettingsNote("Persistence and context", disclosure.persistence || "Preferences and generated output are local. Main-agent context injection is off unless enabled."),
36441
+ nativeSettingsSection("Generation profile", "Choose the dedicated model, effort, and automatic-generation policy.", [controls.model, controls.thinking, controls.automatic], { open: true }),
36442
+ nativeSettingsSection("Titles", "Generated names never replace explicit session or browser names.", [controls.titleEnabled, controls.cadence], { open: true }),
36443
+ nativeSettingsSection("Prompts", "Editable instructions are bounded and treated as untrusted data.", [controls.titlePrompt, controls.summaryPrompt], { open: true }),
36444
+ nativeSettingsSection("Privacy and context", "The transcript scope is fixed to text and tool names; injection is separately opt-in.", [controls.injectLatest], { open: true }),
36445
+ );
36446
+ elements.nativeCommandBody.replaceChildren(body);
36447
+ elements.nativeCommandActions.replaceChildren();
36448
+ addNativeCommandAction("Cancel", closeNativeCommandDialog);
36449
+
36450
+ const signature = () => JSON.stringify({
36451
+ model: controls.model.select.value,
36452
+ thinking: controls.thinking.select.value,
36453
+ automatic: controls.automatic.input.checked,
36454
+ titleEnabled: controls.titleEnabled.input.checked,
36455
+ cadence: controls.cadence.select.value,
36456
+ injectLatest: controls.injectLatest.input.checked,
36457
+ titlePrompt: controls.titlePrompt.textarea.value,
36458
+ summaryPrompt: controls.summaryPrompt.textarea.value,
36459
+ });
36460
+ const initialSignature = signature();
36461
+ const updateDirty = () => { nativeSettingsDirty = signature() !== initialSignature; };
36462
+ for (const control of [controls.model.select, controls.thinking.select, controls.automatic.input, controls.titleEnabled.input, controls.cadence.select, controls.injectLatest.input, controls.titlePrompt.textarea, controls.summaryPrompt.textarea]) {
36463
+ control.addEventListener("input", updateDirty);
36464
+ control.addEventListener("change", updateDirty);
36465
+ }
36466
+
36467
+ const save = addNativeCommandAction("Save and generate", async () => {
36468
+ setNativeActionBusy(save, true, "Saving…");
36469
+ setNativeCommandError("");
36470
+ try {
36471
+ const selectedModel = models.find((model) => gitWorkflowSetupModelKey(model) === controls.model.select.value);
36472
+ if (!selectedModel) throw new Error("Select an available session summary model.");
36473
+ const titlePrompt = controls.titlePrompt.textarea.value.trim();
36474
+ const summaryPrompt = controls.summaryPrompt.textarea.value.trim();
36475
+ if (!titlePrompt || !summaryPrompt) throw new Error("Both editable prompts are required.");
36476
+ if (titlePrompt.length > SESSION_SUMMARY_PROMPT_MAX_CHARS || summaryPrompt.length > SESSION_SUMMARY_PROMPT_MAX_CHARS) throw new Error("Each editable prompt must not exceed 8 KiB.");
36477
+ const reviewed = await appConfirm({
36478
+ title: "Save session summary setup?",
36479
+ summary: `${disclosure.scope || "Selected active-branch text and tool names will be sent to the configured model."}\n\n${disclosure.cost || "Generation may incur provider usage."}`,
36480
+ affected: "Global session-summary preferences and the active tab's first generated summary",
36481
+ undoable: false,
36482
+ confirmLabel: "Save and generate",
36483
+ danger: false,
36484
+ });
36485
+ if (!reviewed) return;
36486
+ const response = await nativeCommandApi("/api/session-summary/preferences", {
36487
+ method: "PUT",
36488
+ body: {
36489
+ confirmed: true,
36490
+ preferences: {
36491
+ enabled: controls.automatic.input.checked,
36492
+ model: { provider: selectedModel.provider, modelId: selectedModel.id, thinkingLevel: controls.thinking.select.value },
36493
+ prompts: { title: titlePrompt, summary: summaryPrompt },
36494
+ input: { scope: "text-and-tool-names" },
36495
+ context: { injectLatest: controls.injectLatest.input.checked },
36496
+ title: { enabled: controls.titleEnabled.input.checked, minSettledTurns: Number(controls.cadence.select.value) },
36497
+ },
36498
+ },
36499
+ });
36500
+ const targetTabId = nativeCommandTabId || activeTabId;
36501
+ updateSessionSummaryForTab(targetTabId, response.data?.summary || {
36502
+ version: SESSION_SUMMARY_PROTOCOL_VERSION,
36503
+ status: "idle",
36504
+ configured: true,
36505
+ enabled: controls.automatic.input.checked,
36506
+ durable: false,
36507
+ updatedAt: new Date().toISOString(),
36508
+ });
36509
+ nativeSettingsDirty = false;
36510
+ closeNativeCommandDialog({ force: true });
36511
+ openSessionSummaryOverlay(targetTabId, { loading: true });
36512
+ await requestSessionSummaryGeneration(targetTabId, { refresh: true }).catch(() => {});
36513
+ if (typeof onSaved === "function") await onSaved(response.data?.preferences);
36514
+ } catch (error) {
36515
+ setNativeCommandError(error.message || String(error));
36516
+ } finally {
36517
+ setNativeActionBusy(save, false);
36518
+ }
36519
+ }, "primary");
36520
+ }
36521
+
33903
36522
  async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
33904
36523
  openNativeCommandDialog({
33905
36524
  title: "/git-workflow-setup",
@@ -34913,10 +37532,11 @@ async function openNativeAuthSelector(mode) {
34913
37532
  }
34914
37533
 
34915
37534
  async function handleNativeSlashSelectorCommand(message, { usesPromptInput = false } = {}) {
34916
- const name = slashCommandName(message);
37535
+ const summaryMatch = String(message || "").trim().match(/^\/summary(?:\s+(refresh))?$/i);
37536
+ const name = summaryMatch ? "summary" : slashCommandName(message);
34917
37537
  if (!NATIVE_SELECTOR_COMMANDS.has(name)) return false;
34918
37538
  const featureId = optionalFeatureIdForCommand(name);
34919
- if (name === "workflow-setup" && !hasLoadedRpcCommand(name)) {
37539
+ if ((name === "workflow-setup" || name === "summary" || name === "summary-setup") && !hasLoadedRpcCommand(name)) {
34920
37540
  const tabContext = activeTabContext();
34921
37541
  addEvent(commandUnavailableMessage(name), "warn");
34922
37542
  refreshCommands(tabContext).catch((error) => {
@@ -34945,6 +37565,12 @@ async function handleNativeSlashSelectorCommand(message, { usesPromptInput = fal
34945
37565
  case "settings":
34946
37566
  await openNativeSettingsDialog();
34947
37567
  return true;
37568
+ case "summary":
37569
+ await openSessionSummaryForTab(activeTabId, { refresh: summaryMatch?.[1]?.toLowerCase() === "refresh" });
37570
+ return true;
37571
+ case "summary-setup":
37572
+ await openNativeSessionSummarySetupDialog();
37573
+ return true;
34948
37574
  case "workflow-setup":
34949
37575
  await openNativeWorkflowSetupDialog();
34950
37576
  return true;
@@ -35112,7 +37738,7 @@ function renderCompactToolShell(event, { complete = false } = {}) {
35112
37738
  transcriptRenderer.ownMessage(bubble, { key: `live:compact-tool:${id}`, role: "toolExecution" });
35113
37739
  transcriptRenderer.ownSurface(body, { messageKey: `live:compact-tool:${id}`, kind: "tool-execution", segment: "0" });
35114
37740
  transcriptRenderer.ownSurface(status, { messageKey: `live:compact-tool:${id}`, kind: "tool-execution", segment: "status" });
35115
- appendChatMessageBubble(bubble);
37741
+ appendChatMessageBubble(bubble, { liveTail: true });
35116
37742
  shell = { bubble, role, status };
35117
37743
  compactToolShells.set(id, shell);
35118
37744
  }
@@ -35529,26 +38155,38 @@ function restoreCompactLiveOutputAfterChatRebuild() {
35529
38155
  compactThinkingBubble = null;
35530
38156
  compactThinkingNode = null;
35531
38157
  if (streamMessageActive) flushCompactLiveOutput();
35532
- for (const shell of compactToolShells.values()) appendChatMessageBubble(shell.bubble);
38158
+ for (const shell of compactToolShells.values()) appendChatMessageBubble(shell.bubble, { liveTail: true });
35533
38159
  renderRunIndicator({ scroll: false });
35534
38160
  }
35535
38161
 
35536
38162
  /**
35537
- * The chat DOM was rebuilt while an assistant message is still streaming:
35538
- * drop references to the detached nodes but keep stream text state, then
35539
- * re-append the live thinking/text bubbles so no partial output is lost.
38163
+ * Reconcile live stream surfaces after an authoritative transcript render.
38164
+ * Transcript resets intentionally keep mounted live-tail bubbles, so reuse
38165
+ * those nodes and only rebuild a surface when it was actually detached.
35540
38166
  */
35541
38167
  function restoreStreamRenderAfterChatRebuild() {
35542
38168
  const thinkingText = streamThinking?._rawThinkingText || streamThinking?.textContent || "";
35543
38169
  const thinkingComplete = streamThinkingBubble?.classList.contains("complete") === true;
35544
38170
  const toolCallWasVisible = !!(streamToolCallBubble?.parentElement === elements.chat || streamToolCallRawArguments || streamToolCallName);
35545
- streamBubble = null;
35546
- streamText = null;
35547
- streamThinkingBubble = null;
35548
- streamThinking = null;
35549
- streamToolCallBubble = null;
35550
- streamToolCallText = null;
35551
- streamBubbleVisibleSince = 0;
38171
+ const streamOutputMounted = !!(streamBubble?.parentElement === elements.chat && streamText?.isConnected && streamBubble.contains(streamText));
38172
+ const thinkingOutputMounted = !!(streamThinkingBubble?.parentElement === elements.chat && streamThinking?.isConnected && streamThinkingBubble.contains(streamThinking));
38173
+ const toolCallOutputMounted = !!(streamToolCallBubble?.parentElement === elements.chat && streamToolCallText?.isConnected && streamToolCallBubble.contains(streamToolCallText));
38174
+ if (!streamOutputMounted) {
38175
+ removeLiveTranscriptBubble(streamBubble, "assistant-rebuild");
38176
+ streamBubble = null;
38177
+ streamText = null;
38178
+ streamBubbleVisibleSince = 0;
38179
+ }
38180
+ if (!thinkingOutputMounted) {
38181
+ removeLiveTranscriptBubble(streamThinkingBubble, "thinking-rebuild");
38182
+ streamThinkingBubble = null;
38183
+ streamThinking = null;
38184
+ }
38185
+ if (!toolCallOutputMounted) {
38186
+ removeLiveTranscriptBubble(streamToolCallBubble, "tool-call-rebuild");
38187
+ streamToolCallBubble = null;
38188
+ streamToolCallText = null;
38189
+ }
35552
38190
  if (thinkingText && setStreamingThinkingText(thinkingText) && thinkingComplete) {
35553
38191
  streamThinkingBubble?.classList.add("complete");
35554
38192
  }
@@ -36856,6 +39494,7 @@ async function refreshCommands(tabContext = activeTabContext()) {
36856
39494
  rawAvailableCommands = catalog.raw;
36857
39495
  availableCommands = catalog.available;
36858
39496
  updateOptionalFeatureAvailability();
39497
+ renderSessionSummaryControls();
36859
39498
  renderCommands();
36860
39499
  if (elements.commandPaletteDialog?.open) renderCommandPalette({ preserveScroll: true });
36861
39500
  }
@@ -37691,6 +40330,7 @@ function removeQueuedDialogRequests(ids = []) {
37691
40330
  if (activeDialog && idSet.has(String(activeDialog.id || ""))) {
37692
40331
  if (elements.dialog.open) elements.dialog.close();
37693
40332
  activeDialog = null;
40333
+ activeDialogCancel = null;
37694
40334
  showNextDialog();
37695
40335
  return true;
37696
40336
  }
@@ -37709,6 +40349,10 @@ function handleExtensionUiRequest(request) {
37709
40349
  }
37710
40350
  case "setStatus": {
37711
40351
  const statusKey = request.statusKey || "extension";
40352
+ if (statusKey === FEATURE_DECISION_OUTPUT_STATUS_KEY) {
40353
+ handleFeatureDecisionOutputStatus(request.statusText, request.tabId || activeTabId);
40354
+ return;
40355
+ }
37712
40356
  if (statusKey === FEATURE_CATEGORY_STATUS_KEY) {
37713
40357
  handleFeatureCategoryStatus(request.statusText, request.tabId || activeTabId);
37714
40358
  return;
@@ -37831,6 +40475,7 @@ async function sendDialogResponse(payload) {
37831
40475
  if (responseId && activeDialog && String(activeDialog.id || "") !== responseId) return;
37832
40476
  if (elements.dialog.open) elements.dialog.close();
37833
40477
  activeDialog = null;
40478
+ activeDialogCancel = null;
37834
40479
  if (runIndicatorIsActive()) {
37835
40480
  setRunIndicatorActivity("Continuing after your response…");
37836
40481
  // Extension commands can continue background work after Pi has already
@@ -37842,6 +40487,23 @@ async function sendDialogResponse(payload) {
37842
40487
  }
37843
40488
  }
37844
40489
 
40490
+ function cancelActiveExtensionDialog(event) {
40491
+ if (!activeDialog || typeof activeDialogCancel !== "function") return false;
40492
+ event?.preventDefault?.();
40493
+ return activeDialogCancel();
40494
+ }
40495
+
40496
+ function createDialogResponder(sendResponse) {
40497
+ let responseSent = false;
40498
+ return (response, onAccept) => {
40499
+ if (responseSent) return false;
40500
+ responseSent = true;
40501
+ onAccept?.();
40502
+ sendResponse(response);
40503
+ return true;
40504
+ };
40505
+ }
40506
+
37845
40507
  function addDialogButton(label, handler, className) {
37846
40508
  const button = make("button", className, label);
37847
40509
  button.type = "button";
@@ -37877,7 +40539,7 @@ function appendWorkflowScriptTokens(parent, line) {
37877
40539
  if (start < line.length) parent.append(document.createTextNode(line.slice(start)));
37878
40540
  }
37879
40541
 
37880
- function renderWorkflowScriptPreview(request) {
40542
+ function renderWorkflowScriptPreview(request, respondToDialog) {
37881
40543
  const source = request.prefill ?? "";
37882
40544
  const sourceLines = source.split("\n");
37883
40545
  const searchableLines = sourceLines.map((line) => line.toLocaleLowerCase());
@@ -38019,14 +40681,15 @@ function renderWorkflowScriptPreview(request) {
38019
40681
 
38020
40682
  preview.append(metadata, toolbar, codeViewer);
38021
40683
  elements.dialogBody.append(preview);
38022
- addDialogButton("Cancel workflow", () => sendDialogResponse({ type: "extension_ui_response", id: request.id, cancelled: true, tabId: request.tabId }));
38023
- addDialogButton("Back to approval", () => sendDialogResponse({ type: "extension_ui_response", id: request.id, value: request.prefill, tabId: request.tabId }), "primary");
40684
+ addDialogButton("Cancel workflow", () => respondToDialog({ cancelled: true }));
40685
+ addDialogButton("Back to approval", () => respondToDialog({ value: request.prefill }), "primary");
38024
40686
  setTimeout(() => codeViewer.focus(), 0);
38025
40687
  }
38026
40688
 
38027
40689
  function showNextDialog() {
38028
40690
  if (activeDialog || dialogQueue.length === 0) return;
38029
40691
  activeDialog = dialogQueue.shift();
40692
+ activeDialogCancel = null;
38030
40693
  const request = activeDialog;
38031
40694
 
38032
40695
  const prompt = normalizeDialogPrompt(request);
@@ -38036,9 +40699,11 @@ function showNextDialog() {
38036
40699
  const isGuardrailDialog = isGuardrailDialogPrompt(displayPrompt);
38037
40700
  const isReleaseDialog = !!releasePrompt;
38038
40701
  const isWorkflowScriptPreview = isWorkflowScriptPreviewRequest(request, prompt);
40702
+ const questionnaire = request.method === "select" && !isReleaseDialog ? questionnaireSelectParts(prompt, request.options) : null;
38039
40703
  elements.dialog.classList.toggle("guardrail-dialog", isGuardrailDialog);
38040
40704
  elements.dialog.classList.toggle("release-dialog", isReleaseDialog);
38041
40705
  elements.dialog.classList.toggle("workflow-script-dialog", isWorkflowScriptPreview);
40706
+ elements.dialog.classList.toggle("questionnaire-dialog", !!questionnaire);
38042
40707
  elements.dialogTitle.textContent = displayPrompt.title;
38043
40708
  if (isReleaseDialog) renderReleaseDialogMessage(elements.dialogMessage, displayPrompt.message);
38044
40709
  else renderAnsiText(elements.dialogMessage, displayPrompt.message);
@@ -38046,9 +40711,33 @@ function showNextDialog() {
38046
40711
  elements.dialogBody.replaceChildren();
38047
40712
  elements.dialogActions.replaceChildren();
38048
40713
 
38049
- const cancel = () => sendDialogResponse({ type: "extension_ui_response", id: request.id, cancelled: true, tabId: request.tabId });
38050
-
38051
- if (request.method === "select") {
40714
+ const respondToDialog = createDialogResponder((response) => {
40715
+ sendDialogResponse({ type: "extension_ui_response", id: request.id, tabId: request.tabId, ...response });
40716
+ });
40717
+ const cancel = () => respondToDialog({ cancelled: true });
40718
+ activeDialogCancel = cancel;
40719
+
40720
+ if (questionnaire) {
40721
+ const options = make("div", "dialog-options questionnaire-options");
40722
+ const respondToQuestionnaire = (response) => respondToDialog(response, () => {
40723
+ options.querySelectorAll("button").forEach((button) => { button.disabled = true; });
40724
+ elements.dialogActions.querySelectorAll("button").forEach((button) => { button.disabled = true; });
40725
+ });
40726
+ activeDialogCancel = () => respondToQuestionnaire({ cancelled: true });
40727
+ (request.options || []).forEach((option, index) => {
40728
+ const optionLabel = String(option);
40729
+ const row = questionnaire.rows[index];
40730
+ const button = row.kind === "action"
40731
+ ? renderQuestionnaireActionButton(row)
40732
+ : renderQuestionnaireOptionButton(row, questionnaire.mode);
40733
+ // Presentation is derived, but the response always carries the exact
40734
+ // native option string the questionnaire runtime produced.
40735
+ button.addEventListener("click", () => respondToQuestionnaire({ value: optionLabel }));
40736
+ options.append(button);
40737
+ });
40738
+ elements.dialogBody.append(options);
40739
+ addDialogButton("Cancel", () => respondToQuestionnaire({ cancelled: true }), "questionnaire-dialog-cancel");
40740
+ } else if (request.method === "select") {
38052
40741
  const options = make("div", "dialog-options");
38053
40742
  for (const option of request.options || []) {
38054
40743
  const optionLabel = String(option);
@@ -38061,37 +40750,55 @@ function showNextDialog() {
38061
40750
  if (isReleaseDialog && /^\[x\]/.test(optionLabel)) button.classList.add("release-target-option", "release-target-selected");
38062
40751
  if (isReleaseDialog && /^\[ \]/.test(optionLabel)) button.classList.add("release-target-option");
38063
40752
  if (isReleaseDialog && /^(?:No|Cancel)$/i.test(optionLabel)) button.classList.add("release-cancel-action");
38064
- button.addEventListener("click", () => sendDialogResponse({ type: "extension_ui_response", id: request.id, value: optionLabel, tabId: request.tabId }));
40753
+ button.addEventListener("click", () => respondToDialog({ value: optionLabel }));
38065
40754
  options.append(button);
38066
40755
  }
38067
40756
  elements.dialogBody.append(options);
38068
40757
  addDialogButton("Cancel", cancel);
38069
40758
  } else if (request.method === "confirm") {
38070
40759
  addDialogButton("Cancel", cancel);
38071
- addDialogButton("No", () => sendDialogResponse({ type: "extension_ui_response", id: request.id, confirmed: false, tabId: request.tabId }));
38072
- addDialogButton("Yes", () => sendDialogResponse({ type: "extension_ui_response", id: request.id, confirmed: true, tabId: request.tabId }), "primary");
40760
+ addDialogButton("No", () => respondToDialog({ confirmed: false }));
40761
+ addDialogButton("Yes", () => respondToDialog({ confirmed: true }), "primary");
38073
40762
  } else if (request.method === "input") {
38074
40763
  const input = make("input", "dialog-input");
38075
40764
  input.value = request.prefill || "";
38076
40765
  input.placeholder = request.placeholder || "";
38077
40766
  elements.dialogBody.append(input);
38078
- addDialogButton("Cancel", cancel);
38079
- addDialogButton("Submit", () => sendDialogResponse({ type: "extension_ui_response", id: request.id, value: input.value, tabId: request.tabId }), "primary");
40767
+ // The dialog form uses method="dialog", so an unhandled Enter would close it
40768
+ // implicitly without ever sending a response and leave the extension blocked.
40769
+ // Keyboard, click, and cancel paths therefore share one guarded one-shot closure.
40770
+ const respondToInput = (response) => respondToDialog(response, () => {
40771
+ input.disabled = true;
40772
+ elements.dialogActions.querySelectorAll("button").forEach((button) => { button.disabled = true; });
40773
+ });
40774
+ const submitInput = () => respondToInput({ value: input.value });
40775
+ activeDialogCancel = () => respondToInput({ cancelled: true });
40776
+ input.addEventListener("keydown", (event) => {
40777
+ const intent = dialogInputEnterIntent(event);
40778
+ if (intent === "ignore") return;
40779
+ event.preventDefault();
40780
+ event.stopPropagation();
40781
+ if (intent === "submit") submitInput();
40782
+ });
40783
+ addDialogButton("Cancel", () => respondToInput({ cancelled: true }));
40784
+ addDialogButton("Submit", submitInput, "primary");
38080
40785
  setTimeout(() => input.focus(), 0);
38081
40786
  } else if (isWorkflowScriptPreview) {
38082
- renderWorkflowScriptPreview(request);
40787
+ renderWorkflowScriptPreview(request, respondToDialog);
38083
40788
  } else if (request.method === "editor") {
38084
40789
  const textarea = make("textarea", "dialog-editor");
38085
40790
  textarea.value = request.prefill || "";
38086
40791
  elements.dialogBody.append(textarea);
38087
40792
  addDialogButton("Cancel", cancel);
38088
- addDialogButton("Submit", () => sendDialogResponse({ type: "extension_ui_response", id: request.id, value: textarea.value, tabId: request.tabId }), "primary");
40793
+ addDialogButton("Submit", () => respondToDialog({ value: textarea.value }), "primary");
38089
40794
  setTimeout(() => textarea.focus(), 0);
38090
40795
  }
38091
40796
 
38092
40797
  elements.dialog.showModal();
38093
40798
  }
38094
40799
 
40800
+ elements.dialog.addEventListener("cancel", cancelActiveExtensionDialog);
40801
+
38095
40802
  function supervisorEventEnvelope(event, fallbackTabId = activeTabId) {
38096
40803
  if (!event || typeof event !== "object") return null;
38097
40804
  const fields = ["supervisorScopeId", "supervisorEpoch", "supervisorSeq"];
@@ -38214,6 +40921,26 @@ function handleInactiveTabEvent(event) {
38214
40921
  }
38215
40922
 
38216
40923
  function handleEvent(event) {
40924
+ if (event?.type === "webui_session_summary") {
40925
+ handleSessionSummaryEvent(event);
40926
+ return;
40927
+ }
40928
+ if (event?.type === "webui_optional_feature_migration") {
40929
+ applyOptionalFeatureMigrationSnapshot(event.snapshot);
40930
+ return;
40931
+ }
40932
+ if (["webui_optional_feature_restart_completed", "webui_optional_feature_restart_deferred"].includes(event?.type)) {
40933
+ optionalFeatureRestartNotice = {
40934
+ tabId: event.tabId || activeTabId,
40935
+ tabTitle: event.tabTitle || "terminal",
40936
+ autoRestarted: event.autoRestarted === true,
40937
+ restartDeferred: event.restartDeferred === true,
40938
+ reason: event.reason || "",
40939
+ };
40940
+ addEvent(event.autoRestarted ? "restarted tab to load new optional features" : "optional feature restart deferred because the tab is busy", event.restartDeferred ? "warn" : "info");
40941
+ renderOptionalFeatureMigrationSurface();
40942
+ return;
40943
+ }
38217
40944
  if (eventHasTabActivityPayload(event)) ingestEventTabActivity(event);
38218
40945
  if (event?.type === "auto_retry_start" || event?.type === "auto_retry_end") trackAutoRetryStateFromEvent(event);
38219
40946
  if (eventMayAffectSkillUsage(event)) trackSkillsFromEvent(event);
@@ -38225,8 +40952,7 @@ function handleEvent(event) {
38225
40952
  switch (event.type) {
38226
40953
  case "webui_connected": {
38227
40954
  const connectedTabId = event.tabId || activeTabId;
38228
- featureCategoryByTab.delete(connectedTabId);
38229
- if (connectedTabId === activeTabId) renderFeatureCategoryTag(connectedTabId);
40955
+ clearFeatureDecisionStateForTab(connectedTabId, { render: true });
38230
40956
  acceptOutputModeAcknowledgement(event);
38231
40957
  setWebuiVersion(event.version);
38232
40958
  setPiVersion(event.piVersion);
@@ -38608,6 +41334,10 @@ function connectEvents(tabContext = activeTabContext(), { requestedMode = "auto"
38608
41334
  });
38609
41335
  const source = new EventSource(`/api/events?${parameters.toString()}`);
38610
41336
  eventSource = source;
41337
+ source.onopen = () => {
41338
+ if (eventSource !== source || !isCurrentTabContext(tabContext)) return;
41339
+ refreshOptionalFeaturePackageStatuses().catch(() => {});
41340
+ };
38611
41341
  source.onmessage = (message) => {
38612
41342
  if (eventSource !== source || !isCurrentTabContext(tabContext)) return;
38613
41343
  try {
@@ -38679,6 +41409,11 @@ elements.skillEditorDialog?.addEventListener("keydown", (event) => {
38679
41409
  if (!elements.skillEditorSaveButton?.disabled) saveSkillEditor();
38680
41410
  });
38681
41411
  elements.skillEditorDialog?.querySelector("form")?.addEventListener("submit", (event) => event.preventDefault());
41412
+ elements.featureCategoryTag?.addEventListener("click", openFeatureDecisionDialog);
41413
+ elements.featureDecisionDialog?.addEventListener("close", () => {
41414
+ featureDecisionDialogTabId = null;
41415
+ if (elements.featureDecisionDialogOutput) elements.featureDecisionDialogOutput.textContent = "";
41416
+ });
38682
41417
  elements.sendFeedbackButton.addEventListener("click", () => submitQueuedActionFeedback());
38683
41418
  elements.composer.addEventListener("submit", (event) => {
38684
41419
  event.preventDefault();
@@ -38793,6 +41528,14 @@ elements.newTabChooseDirectoryButton?.addEventListener("click", () => createTerm
38793
41528
  elements.newTabWorktreeButton?.addEventListener("click", () => openBranchWorktreePicker());
38794
41529
  elements.splitTabButton?.addEventListener("click", () => splitActiveTerminalTab());
38795
41530
  elements.workspaceSaveButton?.addEventListener("click", () => saveWebuiWorkspace());
41531
+ const openActiveSessionSummary = () => {
41532
+ void openSessionSummaryForTab().catch((error) => addEvent(error.message || String(error), "error"));
41533
+ };
41534
+ elements.summaryHeaderButton?.addEventListener("click", openActiveSessionSummary);
41535
+ elements.summaryActionButton?.addEventListener("click", () => {
41536
+ setComposerActionsOpen(false);
41537
+ openActiveSessionSummary();
41538
+ });
38796
41539
  elements.terminalSplitCloseButton?.addEventListener("click", () => closeTerminalSplitView());
38797
41540
  elements.closeAllTabsButton.addEventListener("click", () => closeAllTerminalTabs());
38798
41541
  elements.commandPaletteButton?.addEventListener("click", () => openCommandPalette());
@@ -38954,6 +41697,7 @@ elements.optionsRemoteButton.addEventListener("click", () => runNativeCommandMen
38954
41697
  elements.optionsNameButton.addEventListener("click", () => runNativeCommandMenu("/name"));
38955
41698
  elements.optionsCloneButton.addEventListener("click", () => runNativeCommandMenu("/clone"));
38956
41699
  elements.optionsSettingsButton.addEventListener("click", () => runNativeCommandMenu("/settings"));
41700
+ elements.optionsSummarySetupButton?.addEventListener("click", () => runNativeCommandMenu("/summary-setup"));
38957
41701
  elements.optionsWorkflowSetupButton?.addEventListener("click", () => runNativeCommandMenu("/workflow-setup"));
38958
41702
  elements.optionsSafetyGuardSetupButton?.addEventListener("click", () => runNativeCommandMenu("/safety-guard-setup"));
38959
41703
  elements.optionsGitWorkflowSetupButton?.addEventListener("click", () => runNativeCommandMenu("/git-workflow-setup"));
@@ -38962,6 +41706,28 @@ elements.optionsForkButton.addEventListener("click", () => runNativeCommandMenu(
38962
41706
  elements.optionsTreeButton.addEventListener("click", () => runNativeCommandMenu("/tree"));
38963
41707
  elements.optionsStatsButton?.addEventListener("click", () => openStatsOverlay({ refresh: true }));
38964
41708
  elements.optionsFooterVisibilityButton?.addEventListener("click", openGitFooterVisibilityDialog);
41709
+ elements.sessionSummaryOverlayCloseButton?.addEventListener("click", () => closeSessionSummaryOverlay());
41710
+ elements.sessionSummaryOverlayCopyButton?.addEventListener("click", async () => {
41711
+ const state = sessionSummaryStateForTab(sessionSummaryOverlayTabId);
41712
+ if (!state?.summaryMarkdown) return;
41713
+ try {
41714
+ await copyText(state.summaryMarkdown);
41715
+ elements.sessionSummaryOverlayStatus.textContent = "Markdown copied to the clipboard.";
41716
+ } catch (error) {
41717
+ elements.sessionSummaryOverlayStatus.textContent = `Copy failed: ${error.message || String(error)}`;
41718
+ elements.sessionSummaryOverlayStatus.classList.add("error");
41719
+ }
41720
+ });
41721
+ elements.sessionSummaryOverlayRefreshButton?.addEventListener("click", () => {
41722
+ const tabId = sessionSummaryOverlayTabId;
41723
+ if (tabId) void requestSessionSummaryGeneration(tabId, { refresh: true }).catch(() => {});
41724
+ });
41725
+ document.addEventListener("keydown", (event) => {
41726
+ if (event.key !== "Escape" || elements.sessionSummaryOverlay?.hidden || document.querySelector("dialog[open]")) return;
41727
+ event.preventDefault();
41728
+ event.stopImmediatePropagation();
41729
+ closeSessionSummaryOverlay();
41730
+ }, true);
38965
41731
  elements.gitFooterVisibilitySelectAllButton?.addEventListener("click", () => setGitFooterVisibilitySelection(true));
38966
41732
  elements.gitFooterVisibilitySelectNoneButton?.addEventListener("click", () => setGitFooterVisibilitySelection(false));
38967
41733
  elements.gitFooterVisibilityCloseButton?.addEventListener("click", closeGitFooterVisibilityDialog);
@@ -39505,6 +42271,9 @@ if (elements.subagentOpenModeSelect) {
39505
42271
  setSubagentOpenMode(elements.subagentOpenModeSelect.value, { announce: true });
39506
42272
  });
39507
42273
  }
42274
+ elements.subagentsAutoClearButton?.addEventListener("click", () => {
42275
+ setSubagentAutoClearEnabled(!subagentAutoClearEnabled, { announce: true });
42276
+ });
39508
42277
  elements.subagentsClearFinishedButton?.addEventListener("click", () => {
39509
42278
  void clearFinishedSubagentRuns();
39510
42279
  });
@@ -39873,10 +42642,35 @@ window.addEventListener("storage", (event) => {
39873
42642
  if (event.key === OPTIONAL_FEATURES_STORAGE_KEY) reconcileDisabledOptionalFeaturesFromStorage();
39874
42643
  if (event.key === SIDE_PANEL_SECTION_VISIBILITY_STORAGE_KEY) restoreSidePanelSectionVisibility();
39875
42644
  if (event.key === SIDE_PANEL_SECTION_ORDER_STORAGE_KEY) restoreSidePanelSectionOrder();
42645
+ if (event.key === COMPOSER_ACTION_ORDER_STORAGE_KEY) restoreComposerActionOrder();
42646
+ if (event.key === COMPOSER_ACTION_LAYOUT_STORAGE_KEY) restoreComposerActionSlotLayout();
39876
42647
  if (event.key === SIDE_PANEL_WIDTH_STORAGE_KEY) {
39877
42648
  const width = readStoredSidePanelWidth();
39878
42649
  if (width && !isSidePanelOverlayView()) applySidePanelWidth(width);
39879
42650
  }
42651
+ // Another same-origin tab already saved these durable fields, so receiving
42652
+ // tabs only adopt the shared local cache without repeating the server write.
42653
+ if (event.key === SIDE_PANEL_SECTION_STORAGE_KEY) restoreSidePanelSectionState();
42654
+ if (event.key === SIDE_PANEL_STORAGE_KEY) restoreSidePanelState();
42655
+ if (event.key === TERMINAL_TABS_LAYOUT_STORAGE_KEY) restoreTerminalTabsLayoutSetting();
42656
+ if (event.key === TERMINAL_CUSTOM_GROUPS_STORAGE_KEY) {
42657
+ restoreTerminalCustomGroups();
42658
+ syncTerminalCustomGroupsWithTabs(tabs, { persist: false });
42659
+ renderTabs();
42660
+ }
42661
+ if (event.key === FOOTER_SCOPED_MODEL_ORDER_STORAGE_KEY) {
42662
+ footerScopedModels = orderedFooterScopedModels();
42663
+ renderFooter();
42664
+ }
42665
+ if (event.key === FILE_VIEWER_WIDTH_STORAGE_KEY) restoreFileViewerWidthPreference();
42666
+ });
42667
+ // Durable layout reconciliation runs on its own foreground/online lifecycle
42668
+ // listeners so retained dirty state retries without changing the existing
42669
+ // transcript/session reconciliation contracts.
42670
+ window.addEventListener("online", () => reconcileDurableUiLayout());
42671
+ window.addEventListener("pageshow", () => reconcileDurableUiLayout());
42672
+ document.addEventListener("visibilitychange", () => {
42673
+ if (document.visibilityState === "visible") reconcileDurableUiLayout();
39880
42674
  });
39881
42675
  window.addEventListener("resize", syncResizablePanelWidthsForViewport, { passive: true });
39882
42676
  window.addEventListener("keydown", (event) => {
@@ -40262,9 +43056,18 @@ elements.promptInput.addEventListener("blur", () => {
40262
43056
  }, 120);
40263
43057
  });
40264
43058
 
43059
+ elements.optionalFeatureMigrationCancelButton?.addEventListener("click", () => elements.optionalFeatureMigrationDialog?.close());
43060
+ elements.optionalFeatureMigrationLaterButton?.addEventListener("click", () => dismissOptionalFeatureMigration({ closeDialog: true }));
43061
+ elements.optionalFeatureMigrationConfirmButton?.addEventListener("click", migrateSelectedOptionalFeatures);
43062
+ elements.optionalFeatureMigrationDialog?.addEventListener("cancel", (event) => {
43063
+ event.preventDefault();
43064
+ elements.optionalFeatureMigrationDialog.close();
43065
+ });
43066
+
40265
43067
  installModalPrimitives();
40266
43068
  initializeIssueWizard();
40267
43069
  resizePromptInput();
43070
+ restoreDurableUiLayoutPendingJournal();
40268
43071
  restoreSidePanelWidthPreference();
40269
43072
  restoreFileViewerWidthPreference();
40270
43073
  focusPromptInput({ defer: true });
@@ -40273,6 +43076,7 @@ restoreBusyPromptBehaviorSetting();
40273
43076
  updateComposerModeButtons();
40274
43077
  installSessionSkillTagResizeHandling();
40275
43078
  updateOptionalFeatureAvailability();
43079
+ renderOptionalFeatureMigrationSurface();
40276
43080
  refreshOptionalFeaturePackageStatuses({ announce: true });
40277
43081
  renderAppRunnerControls();
40278
43082
  renderLoadedPromptListPreview();
@@ -40290,11 +43094,13 @@ restoreAgentDoneNotificationsSetting();
40290
43094
  restoreThinkingVisibilitySetting();
40291
43095
  restoreTerminalTabsLayoutSetting();
40292
43096
  restoreSubagentOpenModeSetting();
43097
+ restoreSubagentAutoClearSetting();
40293
43098
  restoreTerminalCustomGroups();
40294
43099
  restoreToolOutputExpansionSetting();
40295
43100
  restoreWorkspaceDashboardState();
40296
43101
  restoreInterfaceDensity();
40297
43102
  initializeTerminalHeaderTooltips();
43103
+ initializeComposerActionOrdering();
40298
43104
  restoreSidePanelSectionOrder();
40299
43105
  restoreSidePanelSectionVisibility();
40300
43106
  restoreSidePanelSectionState();