@firstpick/pi-package-webui 0.8.1 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +21 -3
  2. package/bin/pi-webui.mjs +287 -32
  3. package/lib/component-update-state.mjs +126 -0
  4. package/lib/git-workflow-preferences.mjs +246 -19
  5. package/lib/thinking-stream-recovery.mjs +156 -0
  6. package/lib/trust-boundaries.mjs +1 -0
  7. package/lib/ui-layout-settings.mjs +254 -0
  8. package/package.json +5 -3
  9. package/public/app.js +3072 -142
  10. package/public/index.html +188 -39
  11. package/public/service-worker.js +1 -1
  12. package/public/styles.css +1091 -39
  13. package/tests/boot-failure-diagnostics.test.mjs +63 -5
  14. package/tests/browser/composer-action-grid-reorder.spec.mjs +303 -0
  15. package/tests/browser/control-deck-component-updates.spec.mjs +180 -0
  16. package/tests/browser/feature-decision-output-popup.spec.mjs +156 -0
  17. package/tests/browser/interaction-continuity.spec.mjs +187 -0
  18. package/tests/browser/mobile-foundation.spec.mjs +11 -0
  19. package/tests/browser/persistent-ui-layout.spec.mjs +744 -0
  20. package/tests/browser/side-panel-section-reorder.spec.mjs +101 -0
  21. package/tests/browser/stats-overlay.spec.mjs +265 -0
  22. package/tests/codex-fast-mode-static.test.mjs +2 -2
  23. package/tests/component-update-api-static.test.mjs +67 -0
  24. package/tests/component-update-state.test.mjs +80 -0
  25. package/tests/composer-action-grid-reorder-static.test.mjs +63 -0
  26. package/tests/control-deck-component-updates-static.test.mjs +251 -0
  27. package/tests/fast-mode-client-static.test.mjs +2 -2
  28. package/tests/feature-decision-output-popup-static.test.mjs +172 -0
  29. package/tests/fixtures/fake-pi.mjs +180 -6
  30. package/tests/footer-provider-usage-visual-static.test.mjs +71 -0
  31. package/tests/git-workflow-preferences.test.mjs +4 -2
  32. package/tests/http-endpoints-harness.test.mjs +88 -1
  33. package/tests/interaction-state-stability-static.test.mjs +24 -4
  34. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  35. package/tests/mobile-foundation-static.test.mjs +6 -4
  36. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  37. package/tests/mobile-static.test.mjs +34 -16
  38. package/tests/native-parity-harness.test.mjs +2 -0
  39. package/tests/open-issue-wizard-static.test.mjs +1 -1
  40. package/tests/persistent-ui-layout-static.test.mjs +267 -0
  41. package/tests/questionnaire-dialog.test.mjs +511 -0
  42. package/tests/queue-edit-reorder-static.test.mjs +1 -0
  43. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  44. package/tests/side-panel-resize-static.test.mjs +1 -0
  45. package/tests/side-panel-section-reorder-static.test.mjs +68 -0
  46. package/tests/sse-backpressure-harness.test.mjs +51 -12
  47. package/tests/stats-dashboard-static.test.mjs +266 -0
  48. package/tests/subagent-launch-slots.test.mjs +1 -1
  49. package/tests/thinking-stream-recovery.test.mjs +88 -0
  50. package/tests/ui-layout-settings.test.mjs +92 -0
  51. package/tests/webui-settings-locking.test.mjs +159 -0
package/public/app.js CHANGED
@@ -91,6 +91,8 @@ const elements = {
91
91
  composerRow: $(".composer-row"),
92
92
  composerActionsButton: $("#composerActionsButton"),
93
93
  composerActionsPanel: $("#composerActionsPanel"),
94
+ composerActionGridGuide: $("#composerActionGridGuide"),
95
+ composerActionOrderStatus: $("#composerActionOrderStatus"),
94
96
  promptInput: $("#promptInput"),
95
97
  mobileFailedSendRecovery: $("#mobileFailedSendRecovery"),
96
98
  mobileFailedSendRetryButton: $("#mobileFailedSendRetryButton"),
@@ -106,6 +108,9 @@ const elements = {
106
108
  busyPromptBehaviorMenu: $("#busyPromptBehaviorMenu"),
107
109
  sessionSkillTags: $("#sessionSkillTags"),
108
110
  featureCategoryTag: $("#featureCategoryTag"),
111
+ featureDecisionDialog: $("#featureDecisionDialog"),
112
+ featureDecisionDialogOutput: $("#featureDecisionDialogOutput"),
113
+ featureDecisionDialogCloseButton: $("#featureDecisionDialogCloseButton"),
109
114
  conversationModeChip: $("#conversationModeChip"),
110
115
  workflowModeChip: $("#workflowModeChip"),
111
116
  skillEditorDialog: $("#skillEditorDialog"),
@@ -302,6 +307,7 @@ const elements = {
302
307
  issueWizardBotHint: $("#issueWizardBotHint"),
303
308
  stateDetails: $("#stateDetails"),
304
309
  subagentsStatus: $("#subagentsStatus"),
310
+ subagentsAutoClearButton: $("#subagentsAutoClearButton"),
305
311
  subagentsClearFinishedButton: $("#subagentsClearFinishedButton"),
306
312
  subagentsBox: $("#subagentsBox"),
307
313
  subagentCountBadge: $("#subagentCountBadge"),
@@ -388,6 +394,16 @@ const elements = {
388
394
  piReleaseNotesBody: $("#piReleaseNotesBody"),
389
395
  piReleaseNotesGithubLink: $("#piReleaseNotesGithubLink"),
390
396
  piReleaseNotesCloseButton: $("#piReleaseNotesCloseButton"),
397
+ piComponentUpdateStatus: $("#piComponentUpdateStatus"),
398
+ piComponentUpdateButton: $("#piComponentUpdateButton"),
399
+ webuiPackageDialog: $("#webuiPackageDialog"),
400
+ webuiPackageTitle: $("#webuiPackageTitle"),
401
+ webuiPackageCurrentVersion: $("#webuiPackageCurrentVersion"),
402
+ webuiPackageLatestVersion: $("#webuiPackageLatestVersion"),
403
+ webuiPackageNpmButton: $("#webuiPackageNpmButton"),
404
+ webuiPackageCloseButton: $("#webuiPackageCloseButton"),
405
+ webuiComponentUpdateStatus: $("#webuiComponentUpdateStatus"),
406
+ webuiComponentUpdateButton: $("#webuiComponentUpdateButton"),
391
407
  dialog: $("#extensionDialog"),
392
408
  dialogTitle: $("#dialogTitle"),
393
409
  dialogMessage: $("#dialogMessage"),
@@ -480,6 +496,15 @@ let fileViewerSearchTimer = null;
480
496
  let fileViewerSearchHighlightElement = null;
481
497
  let fileContextMenuState = null;
482
498
  let sidePanelContextMenuState = null;
499
+ let sidePanelSectionPointerDrag = null;
500
+ let sidePanelSectionLastDragOverKey = "";
501
+ let sidePanelSectionSuppressClickUntil = 0;
502
+ let composerActionPointerDrag = null;
503
+ let composerActionLastDragOverKey = "";
504
+ let composerActionSuppressClickUntil = 0;
505
+ let composerActionSlotLayout = new Map();
506
+ let composerActionLayoutColumns = 0;
507
+ let composerActionLayoutRestoreFrame = null;
483
508
  let fileTreeDragState = null;
484
509
  let fileViewerResizeState = null;
485
510
  let sidePanelResizeState = null;
@@ -547,6 +572,7 @@ const supervisorGapWarnings = new Set();
547
572
  const supervisorContinuityRefreshes = new Map();
548
573
  const supervisorEnvelopeWarnings = new Set();
549
574
  let activeDialog = null;
575
+ let activeDialogCancel = null;
550
576
  let activeConfirmationResolve = null;
551
577
  let activeWorkspaceReplacementResolve = null;
552
578
  let workspaceLoadPickerFocusReturn = null;
@@ -654,6 +680,7 @@ let latestSubagents = null;
654
680
  let subagentsError = null;
655
681
  let subagentsLoading = false;
656
682
  let subagentsClearingFinished = false;
683
+ let subagentAutoClearEnabled = false;
657
684
  let refreshSubagentsTimer = null;
658
685
  const dismissedSubagentGateKeys = new Set();
659
686
  let subagentOverlaySelection = null;
@@ -686,6 +713,8 @@ let updateRequestInProgress = false;
686
713
  let latestUpdateStatus = null;
687
714
  let updateStatusRefreshTimer = null;
688
715
  let updateNotificationHideTimer = null;
716
+ let componentUpdatePollTimer = null;
717
+ let componentUpdateStartInProgress = false;
689
718
  let backendOfflineNoticeShown = false;
690
719
  let latestMessages = [];
691
720
  let latestMessagesSessionKey = "";
@@ -792,6 +821,11 @@ const SIDE_PANEL_STORAGE_KEY = "pi-webui-side-panel-collapsed";
792
821
  const INTERFACE_DENSITY_STORAGE_KEY = "pi-webui-interface-density";
793
822
  const SIDE_PANEL_SECTION_STORAGE_KEY = "pi-webui-side-panel-sections-collapsed";
794
823
  const SIDE_PANEL_SECTION_VISIBILITY_STORAGE_KEY = "pi-webui-side-panel-sections-hidden";
824
+ const SIDE_PANEL_SECTION_ORDER_STORAGE_KEY = "pi-webui-side-panel-section-order-v1";
825
+ const SIDE_PANEL_SECTION_POINTER_DRAG_THRESHOLD_PX = 6;
826
+ const COMPOSER_ACTION_ORDER_STORAGE_KEY = "pi-webui-composer-action-order-v1";
827
+ const COMPOSER_ACTION_LAYOUT_STORAGE_KEY = "pi-webui-composer-action-layout-v2";
828
+ const COMPOSER_ACTION_POINTER_DRAG_THRESHOLD_PX = 6;
795
829
  const TAB_STORAGE_KEY = "pi-webui-active-tab";
796
830
  const PATH_FAST_PICKS_STORAGE_KEY = "pi-webui-path-fast-picks";
797
831
  const AGENT_DONE_NOTIFICATIONS_STORAGE_KEY = "pi-webui-agent-done-notifications";
@@ -807,6 +841,7 @@ const BUSY_PROMPT_BEHAVIOR_STORAGE_KEY = "pi-webui-busy-prompt-behavior";
807
841
  const SKILL_USAGE_STORAGE_KEY = "pi-webui-skill-usage-v1";
808
842
  const TERMINAL_TABS_LAYOUT_STORAGE_KEY = "pi-webui-terminal-tabs-layout";
809
843
  const SUBAGENT_OPEN_MODE_STORAGE_KEY = "pi-webui-subagent-open-mode";
844
+ const SUBAGENT_AUTO_CLEAR_STORAGE_KEY = "pi-webui-subagent-auto-clear";
810
845
  const TERMINAL_CUSTOM_GROUPS_STORAGE_KEY = "pi-webui-terminal-custom-groups-v1";
811
846
  const TERMINAL_TAB_DRAG_MIME = "application/x-pi-terminal-tab-id";
812
847
  const FOOTER_SCOPED_MODEL_ORDER_STORAGE_KEY = "pi-webui-footer-scoped-model-order-v1";
@@ -904,7 +939,10 @@ const WORKFLOW_INSPECTOR_PAYLOAD_PREFIX = "WORKFLOW_RPC_PAYLOAD ";
904
939
  const WORKFLOW_INSPECTOR_PAYLOAD_TYPE = "firstpick.pi-extension-workflows.inspector";
905
940
  const WORKFLOW_INSPECTOR_PAYLOAD_VERSION = 1;
906
941
  const WORKFLOW_MODE_STATUS_KEY = "workflow-mode";
942
+ const FEATURE_DECISION_OUTPUT_STATUS_KEY = "feature-decision-output";
907
943
  const FEATURE_CATEGORY_STATUS_KEY = "feature-category";
944
+ const FEATURE_DECISION_PAYLOAD_MAX_CHARS = 4096;
945
+ const FEATURE_DECISION_REASON_MAX_CHARS = 500;
908
946
  const WORKFLOW_MODE_RPC_WIDGET_KEY = "workflow-mode:rpc";
909
947
  const WORKFLOW_MODE_RPC_PAYLOAD_PREFIX = "WORKFLOW_MODE_RPC_PAYLOAD ";
910
948
  const WORKFLOW_MODE_RPC_PAYLOAD_TYPE = "firstpick.pi-extension-workflows.mode";
@@ -981,6 +1019,7 @@ const SUBAGENTS_IDLE_REFRESH_MS = 4000;
981
1019
  const SUBAGENTS_HIDDEN_REFRESH_MS = 10_000;
982
1020
  const SUBAGENT_OVERLAY_REFRESH_MS = 1000;
983
1021
  const UPDATE_STATUS_REFRESH_MS = 6 * 60 * 60 * 1000;
1022
+ const COMPONENT_UPDATE_POLL_MS = 1000;
984
1023
  const UPDATE_STATUS_INITIAL_DELAY_MS = 1800;
985
1024
  const RUN_INDICATOR_TICK_MS = 1000;
986
1025
  const RUN_INDICATOR_START_GRACE_MS = 2500;
@@ -2116,6 +2155,8 @@ function receiveMobileNavigationTarget(value) {
2116
2155
  syncMobileShellRoot();
2117
2156
  const statusEntries = new Map();
2118
2157
  const featureCategoryByTab = new Map();
2158
+ const featureDecisionOutputByTab = new Map();
2159
+ let featureDecisionDialogTabId = null;
2119
2160
  const widgets = new Map();
2120
2161
  const widgetsByTab = new Map();
2121
2162
  const todoProgressWidgetExpandedByTab = new Map();
@@ -2159,6 +2200,7 @@ const optionalFeatureAvailability = {
2159
2200
  todoProgressWidget: false,
2160
2201
  tuiToolsCommand: false,
2161
2202
  remoteWebui: false,
2203
+ questionnaire: false,
2162
2204
  naturalConversation: false,
2163
2205
  codexFastMode: false,
2164
2206
  themeBundle: false,
@@ -2258,6 +2300,14 @@ const OPTIONAL_FEATURES = [
2258
2300
  capabilityLabel: "/remote",
2259
2301
  description: "Trusted-LAN QR helper for opening the Web UI from mobile browsers.",
2260
2302
  },
2303
+ {
2304
+ id: "questionnaire",
2305
+ label: "Native questionnaires",
2306
+ packageName: "@firstpick/pi-package-questionnaire",
2307
+ capabilityLabel: "questionnaire tool in /tools",
2308
+ description: "Native TUI and WebUI single- or multi-select question series with Other answers and resumable clarification.",
2309
+ manageWith: "tools",
2310
+ },
2261
2311
  {
2262
2312
  id: "naturalConversation",
2263
2313
  label: "Natural Conversation",
@@ -2706,7 +2756,7 @@ const OPTIONAL_FEATURE_SECTIONS = [
2706
2756
  id: "widgets-native-parity",
2707
2757
  label: "UI widgets & native parity",
2708
2758
  description: "Status widgets, dashboards, themes, and browser access to terminal-native controls.",
2709
- featureIds: ["tuiSkillsCommand", "todoProgressWidget", "tuiToolsCommand", "gitFooterStatus", "statsCommand", "themeBundle"],
2759
+ featureIds: ["tuiSkillsCommand", "todoProgressWidget", "tuiToolsCommand", "questionnaire", "gitFooterStatus", "statsCommand", "themeBundle"],
2710
2760
  },
2711
2761
  {
2712
2762
  id: "conversation",
@@ -3382,6 +3432,132 @@ function sidePanelSectionRecords() {
3382
3432
  .filter((record) => record.id && record.button && record.content);
3383
3433
  }
3384
3434
 
3435
+ function readStoredSidePanelSectionOrder() {
3436
+ try {
3437
+ const parsed = JSON.parse(localStorage.getItem(SIDE_PANEL_SECTION_ORDER_STORAGE_KEY) || "[]");
3438
+ return Array.isArray(parsed) ? [...new Set(parsed.filter((id) => typeof id === "string" && id.trim()))] : [];
3439
+ } catch {
3440
+ return [];
3441
+ }
3442
+ }
3443
+
3444
+ function persistSidePanelSectionOrder() {
3445
+ try {
3446
+ localStorage.setItem(SIDE_PANEL_SECTION_ORDER_STORAGE_KEY, JSON.stringify(sidePanelSectionRecords().map(({ id }) => id)));
3447
+ } catch {
3448
+ // Ignore storage failures; ordering should still work for this page load.
3449
+ }
3450
+ markDurableUiLayoutDirty("sidePanel", "sectionOrder");
3451
+ }
3452
+
3453
+ function restoreSidePanelSectionOrder() {
3454
+ if (sidePanelSectionPointerDrag?.active) return;
3455
+ const records = sidePanelSectionRecords();
3456
+ const parent = records[0]?.section.parentElement;
3457
+ if (!parent || records.some(({ section }) => section.parentElement !== parent)) return;
3458
+ const rank = new Map(readStoredSidePanelSectionOrder().map((id, index) => [id, index]));
3459
+ records.sort((a, b) => {
3460
+ const aRank = rank.has(a.id) ? rank.get(a.id) : Number.MAX_SAFE_INTEGER;
3461
+ const bRank = rank.has(b.id) ? rank.get(b.id) : Number.MAX_SAFE_INTEGER;
3462
+ return aRank - bRank;
3463
+ });
3464
+ for (const { section } of records) parent.append(section);
3465
+ }
3466
+
3467
+ function visibleSidePanelSectionRecords() {
3468
+ return sidePanelSectionRecords().filter(({ section }) => !section.hidden);
3469
+ }
3470
+
3471
+ function clearSidePanelSectionDragMarkers() {
3472
+ for (const { section } of sidePanelSectionRecords()) {
3473
+ section.classList.remove("drag-over-before", "drag-over-after");
3474
+ }
3475
+ }
3476
+
3477
+ function moveSidePanelSectionRelative(fromId, targetRecord, insertBefore) {
3478
+ const sourceRecord = sidePanelSectionRecords().find(({ id }) => id === fromId);
3479
+ if (!sourceRecord || !targetRecord || sourceRecord.section === targetRecord.section) return false;
3480
+ const parent = sourceRecord.section.parentElement;
3481
+ if (!parent || targetRecord.section.parentElement !== parent) return false;
3482
+ clearSidePanelSectionDragMarkers();
3483
+ targetRecord.section.classList.add(insertBefore ? "drag-over-before" : "drag-over-after");
3484
+ sidePanelSectionLastDragOverKey = `${targetRecord.id}:${insertBefore ? "before" : "after"}`;
3485
+ if (insertBefore) parent.insertBefore(sourceRecord.section, targetRecord.section);
3486
+ else parent.insertBefore(sourceRecord.section, targetRecord.section.nextSibling);
3487
+ persistSidePanelSectionOrder();
3488
+ return true;
3489
+ }
3490
+
3491
+ function moveSidePanelSectionByOffset(sectionId, offset) {
3492
+ const records = visibleSidePanelSectionRecords();
3493
+ const fromIndex = records.findIndex(({ id }) => id === sectionId);
3494
+ const toIndex = fromIndex + offset;
3495
+ if (fromIndex < 0 || toIndex < 0 || toIndex >= records.length) return false;
3496
+ const targetRecord = records[toIndex];
3497
+ const moved = moveSidePanelSectionRelative(sectionId, targetRecord, offset < 0);
3498
+ clearSidePanelSectionDragMarkers();
3499
+ if (moved) queueMicrotask(() => sidePanelSectionRecords().find(({ id }) => id === sectionId)?.button.focus({ preventScroll: true }));
3500
+ return moved;
3501
+ }
3502
+
3503
+ function sidePanelSectionToggleFromPoint(clientX, clientY) {
3504
+ return document.elementFromPoint(clientX, clientY)?.closest?.("[data-side-panel-section-toggle]") || null;
3505
+ }
3506
+
3507
+ function beginSidePanelSectionPointerDrag(event, sectionId) {
3508
+ if (event.button !== 0 || !sectionId || sidePanelSectionPointerDrag) return;
3509
+ sidePanelSectionPointerDrag = { sectionId, pointerId: event.pointerId, startX: event.clientX, startY: event.clientY, active: false };
3510
+ window.addEventListener("pointermove", updateSidePanelSectionPointerDrag, { capture: true });
3511
+ window.addEventListener("pointerup", endSidePanelSectionPointerDrag, { capture: true });
3512
+ window.addEventListener("pointercancel", endSidePanelSectionPointerDrag, { capture: true });
3513
+ }
3514
+
3515
+ function updateSidePanelSectionPointerDrag(event) {
3516
+ const drag = sidePanelSectionPointerDrag;
3517
+ if (!drag || drag.pointerId !== event.pointerId) return;
3518
+ const distance = Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY);
3519
+ if (!drag.active && distance < SIDE_PANEL_SECTION_POINTER_DRAG_THRESHOLD_PX) return;
3520
+ event.preventDefault();
3521
+ if (!drag.active) {
3522
+ drag.active = true;
3523
+ sidePanelSectionLastDragOverKey = "";
3524
+ clearTimeout(pointerActivationTimeout);
3525
+ pointerActivationTimeout = null;
3526
+ activePointerActivation = null;
3527
+ const sourceRecord = sidePanelSectionRecords().find(({ id }) => id === drag.sectionId);
3528
+ sourceRecord?.section.classList.add("dragging");
3529
+ }
3530
+ const targetToggle = sidePanelSectionToggleFromPoint(event.clientX, event.clientY);
3531
+ const targetRecord = targetToggle
3532
+ ? sidePanelSectionRecords().find(({ button }) => button === targetToggle)
3533
+ : null;
3534
+ if (!targetRecord || targetRecord.id === drag.sectionId || targetRecord.section.hidden) return;
3535
+ const rect = targetToggle.getBoundingClientRect();
3536
+ const insertBefore = event.clientY < rect.top + rect.height / 2;
3537
+ const markerKey = `${targetRecord.id}:${insertBefore ? "before" : "after"}`;
3538
+ if (markerKey === sidePanelSectionLastDragOverKey) return;
3539
+ moveSidePanelSectionRelative(drag.sectionId, targetRecord, insertBefore);
3540
+ }
3541
+
3542
+ function endSidePanelSectionPointerDrag(event) {
3543
+ const drag = sidePanelSectionPointerDrag;
3544
+ if (!drag || drag.pointerId !== event.pointerId) return;
3545
+ window.removeEventListener("pointermove", updateSidePanelSectionPointerDrag, { capture: true });
3546
+ window.removeEventListener("pointerup", endSidePanelSectionPointerDrag, { capture: true });
3547
+ window.removeEventListener("pointercancel", endSidePanelSectionPointerDrag, { capture: true });
3548
+ const sourceRecord = sidePanelSectionRecords().find(({ id }) => id === drag.sectionId);
3549
+ sidePanelSectionPointerDrag = null;
3550
+ sidePanelSectionLastDragOverKey = "";
3551
+ clearSidePanelSectionDragMarkers();
3552
+ sourceRecord?.section.classList.remove("dragging");
3553
+ if (drag.active) {
3554
+ sidePanelSectionSuppressClickUntil = Date.now() + 250;
3555
+ event.preventDefault();
3556
+ persistSidePanelSectionOrder();
3557
+ queueMicrotask(() => sourceRecord?.button.focus({ preventScroll: true }));
3558
+ }
3559
+ }
3560
+
3385
3561
  function readStoredSidePanelSectionCollapsedIds() {
3386
3562
  try {
3387
3563
  const stored = localStorage.getItem(SIDE_PANEL_SECTION_STORAGE_KEY);
@@ -3402,6 +3578,7 @@ function persistSidePanelSectionState() {
3402
3578
  } catch {
3403
3579
  // Ignore storage failures; section toggles should still work for this page load.
3404
3580
  }
3581
+ markDurableUiLayoutDirty("sidePanel", "collapsedSectionIds");
3405
3582
  }
3406
3583
 
3407
3584
  function readStoredSidePanelSectionHiddenIds() {
@@ -3424,6 +3601,7 @@ function persistSidePanelSectionVisibility() {
3424
3601
  } catch {
3425
3602
  // Ignore storage failures; visibility toggles should still work for this page load.
3426
3603
  }
3604
+ markDurableUiLayoutDirty("sidePanel", "hiddenSectionIds");
3427
3605
  }
3428
3606
 
3429
3607
  function setSidePanelSectionVisible(record, visible, { persist = true } = {}) {
@@ -3450,7 +3628,7 @@ function setSidePanelSectionCollapsed(record, collapsed, { persist = true } = {}
3450
3628
  record.content.hidden = collapsed;
3451
3629
  record.button.setAttribute("aria-expanded", collapsed ? "false" : "true");
3452
3630
  record.button.setAttribute("aria-label", `${collapsed ? "Expand" : "Collapse"} ${label} section`);
3453
- record.button.setAttribute("title", `${collapsed ? "Expand" : "Collapse"} ${label} section`);
3631
+ record.button.setAttribute("title", `${collapsed ? "Expand" : "Collapse"} ${label} section · drag to reorder · Alt+↑/↓ moves`);
3454
3632
  if (!collapsed && record.id === "git" && !record.section.hidden) {
3455
3633
  queueMicrotask(() => {
3456
3634
  renderGitPanel();
@@ -3532,13 +3710,498 @@ function showSidePanelContextMenu(event) {
3532
3710
 
3533
3711
  function bindSidePanelSectionToggles() {
3534
3712
  for (const record of sidePanelSectionRecords()) {
3535
- record.button.addEventListener("click", () => {
3713
+ record.button.addEventListener("click", (event) => {
3714
+ if (Date.now() < sidePanelSectionSuppressClickUntil) {
3715
+ event.preventDefault();
3716
+ return;
3717
+ }
3536
3718
  if (record.section.classList.contains("collapsed")) {
3537
3719
  setOnlySidePanelSectionExpanded(record);
3538
3720
  } else {
3539
3721
  setSidePanelSectionCollapsed(record, true);
3540
3722
  }
3541
3723
  });
3724
+ record.button.addEventListener("keydown", (event) => {
3725
+ if (!event.altKey || (event.key !== "ArrowUp" && event.key !== "ArrowDown")) return;
3726
+ event.preventDefault();
3727
+ moveSidePanelSectionByOffset(record.id, event.key === "ArrowUp" ? -1 : 1);
3728
+ });
3729
+ record.button.addEventListener("pointerdown", (event) => beginSidePanelSectionPointerDrag(event, record.id));
3730
+ }
3731
+ }
3732
+
3733
+ function composerActionRecords() {
3734
+ return Array.from(elements.composerRow?.querySelectorAll("[data-composer-action-id]") || [])
3735
+ .map((root, domIndex) => {
3736
+ const id = root.dataset.composerActionId || "";
3737
+ const focusTarget = root.matches("button") ? root : root.querySelector("button");
3738
+ const rawStoredOrder = root.style.getPropertyValue("--composer-action-order");
3739
+ const storedOrder = Number(rawStoredOrder);
3740
+ const order = rawStoredOrder !== "" && Number.isFinite(storedOrder) ? storedOrder : domIndex;
3741
+ const span = Number(root.dataset.composerActionSpan) === 2 ? 2 : 1;
3742
+ return { id, root, focusTarget, domIndex, order, span };
3743
+ })
3744
+ .filter((record) => record.id && record.focusTarget);
3745
+ }
3746
+
3747
+ function orderedComposerActionRecords({ visibleOnly = false } = {}) {
3748
+ return composerActionRecords()
3749
+ .filter(({ root }) => !visibleOnly || (!root.hidden && root.getClientRects().length > 0))
3750
+ .sort((a, b) => a.order - b.order || a.domIndex - b.domIndex);
3751
+ }
3752
+
3753
+ function readStoredComposerActionOrder() {
3754
+ try {
3755
+ const parsed = JSON.parse(localStorage.getItem(COMPOSER_ACTION_ORDER_STORAGE_KEY) || "[]");
3756
+ return Array.isArray(parsed) ? [...new Set(parsed.filter((id) => typeof id === "string" && id.trim()))] : [];
3757
+ } catch {
3758
+ return [];
3759
+ }
3760
+ }
3761
+
3762
+ function applyComposerActionOrder(orderIds) {
3763
+ const records = composerActionRecords();
3764
+ const knownIds = new Set(records.map(({ id }) => id));
3765
+ const completeOrder = [
3766
+ ...new Set(orderIds.filter((id) => knownIds.has(id))),
3767
+ ...records.map(({ id }) => id).filter((id) => !orderIds.includes(id)),
3768
+ ];
3769
+ const rank = new Map(completeOrder.map((id, index) => [id, index]));
3770
+ for (const record of records) record.root.style.setProperty("--composer-action-order", String(rank.get(record.id)));
3771
+ return completeOrder;
3772
+ }
3773
+
3774
+ function restoreComposerActionOrder() {
3775
+ if (composerActionPointerDrag?.active) return;
3776
+ applyComposerActionOrder(readStoredComposerActionOrder());
3777
+ }
3778
+
3779
+ function persistComposerActionOrder() {
3780
+ try {
3781
+ localStorage.setItem(COMPOSER_ACTION_ORDER_STORAGE_KEY, JSON.stringify(orderedComposerActionRecords().map(({ id }) => id)));
3782
+ } catch {
3783
+ // Ignore storage failures; ordering should still work for this page load.
3784
+ }
3785
+ markDurableUiLayoutDirty("composerActions");
3786
+ }
3787
+
3788
+ function composerActionGridColumnCount() {
3789
+ const row = elements.composerRow;
3790
+ const style = getComputedStyle(row);
3791
+ const rawMinWidth = style.getPropertyValue("--composer-action-cell-min-width").trim();
3792
+ const numericMinWidth = Number.parseFloat(rawMinWidth);
3793
+ const rootFontSize = Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
3794
+ const rowFontSize = Number.parseFloat(style.fontSize) || rootFontSize;
3795
+ const minWidth = rawMinWidth.endsWith("rem")
3796
+ ? numericMinWidth * rootFontSize
3797
+ : rawMinWidth.endsWith("em")
3798
+ ? numericMinWidth * rowFontSize
3799
+ : numericMinWidth;
3800
+ const gap = Number.parseFloat(style.columnGap || style.gap) || 0;
3801
+ const availableWidth = row.clientWidth || row.getBoundingClientRect().width;
3802
+ if (!Number.isFinite(minWidth) || minWidth <= 0 || !Number.isFinite(availableWidth) || availableWidth <= 0) return 1;
3803
+ return Math.max(1, Math.floor((availableWidth + gap) / (minWidth + gap)));
3804
+ }
3805
+
3806
+ function readStoredComposerActionLayout() {
3807
+ try {
3808
+ const parsed = JSON.parse(localStorage.getItem(COMPOSER_ACTION_LAYOUT_STORAGE_KEY) || "null");
3809
+ if (!parsed || parsed.version !== 2 || !Number.isInteger(parsed.columns) || parsed.columns < 1 || !parsed.positions || typeof parsed.positions !== "object") return null;
3810
+ const positions = new Map();
3811
+ for (const [id, slot] of Object.entries(parsed.positions)) {
3812
+ if (typeof id === "string" && id && Number.isInteger(slot) && slot >= 0) positions.set(id, slot);
3813
+ }
3814
+ return { columns: parsed.columns, positions };
3815
+ } catch {
3816
+ return null;
3817
+ }
3818
+ }
3819
+
3820
+ function composerActionSlotCanFit(record, slot, layout = composerActionSlotLayout, columns = composerActionLayoutColumns) {
3821
+ if (!record || !Number.isInteger(slot) || slot < 0 || columns < 1) return false;
3822
+ const column = slot % columns;
3823
+ if (column + record.span > columns) return false;
3824
+ const row = Math.floor(slot / columns);
3825
+ for (const [otherId, otherSlot] of layout) {
3826
+ if (otherId === record.id) continue;
3827
+ const other = composerActionRecords().find(({ id, root }) => id === otherId && !root.hidden && root.getClientRects().length > 0);
3828
+ if (!other || Math.floor(otherSlot / columns) !== row) continue;
3829
+ const otherColumn = otherSlot % columns;
3830
+ if (column < otherColumn + other.span && otherColumn < column + record.span) return false;
3831
+ }
3832
+ return true;
3833
+ }
3834
+
3835
+ function applyComposerActionSlotLayout() {
3836
+ for (const record of composerActionRecords()) {
3837
+ const slot = composerActionSlotLayout.get(record.id);
3838
+ if (!Number.isInteger(slot) || composerActionLayoutColumns < 1 || record.root.hidden) {
3839
+ record.root.style.removeProperty("--composer-action-grid-column");
3840
+ record.root.style.removeProperty("--composer-action-grid-row");
3841
+ continue;
3842
+ }
3843
+ record.root.style.setProperty("--composer-action-grid-column", String((slot % composerActionLayoutColumns) + 1));
3844
+ record.root.style.setProperty("--composer-action-grid-row", String(Math.floor(slot / composerActionLayoutColumns) + 1));
3845
+ }
3846
+ }
3847
+
3848
+ function persistComposerActionSlotLayout() {
3849
+ if (composerActionLayoutColumns < 1 || !composerActionSlotLayout.size) return;
3850
+ try {
3851
+ localStorage.setItem(COMPOSER_ACTION_LAYOUT_STORAGE_KEY, JSON.stringify({
3852
+ version: 2,
3853
+ columns: composerActionLayoutColumns,
3854
+ positions: Object.fromEntries(composerActionSlotLayout),
3855
+ }));
3856
+ } catch {
3857
+ // Ignore storage failures; sparse placement should still work for this page load.
3858
+ }
3859
+ markDurableUiLayoutDirty("composerActions");
3860
+ }
3861
+
3862
+ function remapComposerActionSlot(record, slot, sourceColumns, targetColumns) {
3863
+ const sourceRow = Math.floor(slot / sourceColumns);
3864
+ const sourceColumn = slot % sourceColumns;
3865
+ const sourceMaxColumn = Math.max(0, sourceColumns - record.span);
3866
+ const targetMaxColumn = Math.max(0, targetColumns - record.span);
3867
+ const relativeColumn = sourceMaxColumn > 0 ? Math.min(sourceColumn, sourceMaxColumn) / sourceMaxColumn : 0;
3868
+ return sourceRow * targetColumns + Math.round(relativeColumn * targetMaxColumn);
3869
+ }
3870
+
3871
+ function nearestAvailableComposerActionSlot(record, preferredSlot, layout, columns) {
3872
+ if (record.span > columns) return null;
3873
+ const preferredRow = Math.floor(preferredSlot / columns);
3874
+ const preferredColumn = preferredSlot % columns;
3875
+ const maxColumn = columns - record.span;
3876
+ const columnsByDistance = Array.from({ length: maxColumn + 1 }, (_, column) => column)
3877
+ .sort((a, b) => Math.abs(a - preferredColumn) - Math.abs(b - preferredColumn) || a - b);
3878
+ const maxRow = preferredRow + composerActionRecords().length;
3879
+ for (let row = preferredRow; row <= maxRow; row += 1) {
3880
+ for (const column of columnsByDistance) {
3881
+ const candidate = row * columns + column;
3882
+ if (composerActionSlotCanFit(record, candidate, layout, columns)) return candidate;
3883
+ }
3884
+ }
3885
+ return null;
3886
+ }
3887
+
3888
+ function restoreComposerActionSlotLayout() {
3889
+ if (isMobileView()) return;
3890
+ const stored = readStoredComposerActionLayout();
3891
+ const columns = composerActionGridColumnCount();
3892
+ composerActionSlotLayout = new Map();
3893
+ composerActionLayoutColumns = columns;
3894
+ if (!stored) {
3895
+ applyComposerActionSlotLayout();
3896
+ return;
3897
+ }
3898
+ const records = new Map(composerActionRecords().map((record) => [record.id, record]));
3899
+ for (const [id, storedSlot] of [...stored.positions].sort((a, b) => a[1] - b[1])) {
3900
+ const record = records.get(id);
3901
+ if (!record || record.root.hidden || !record.root.getClientRects().length) continue;
3902
+ const preferredSlot = stored.columns === columns
3903
+ ? storedSlot
3904
+ : remapComposerActionSlot(record, storedSlot, stored.columns, columns);
3905
+ const slot = nearestAvailableComposerActionSlot(record, preferredSlot, composerActionSlotLayout, columns);
3906
+ if (slot !== null) composerActionSlotLayout.set(id, slot);
3907
+ }
3908
+ applyComposerActionSlotLayout();
3909
+ }
3910
+
3911
+ function scheduleComposerActionSlotLayoutRestore() {
3912
+ if (composerActionPointerDrag?.active || composerActionLayoutRestoreFrame !== null) return;
3913
+ const restore = () => {
3914
+ composerActionLayoutRestoreFrame = null;
3915
+ if (!composerActionPointerDrag?.active) restoreComposerActionSlotLayout();
3916
+ };
3917
+ composerActionLayoutRestoreFrame = typeof requestAnimationFrame === "function"
3918
+ ? requestAnimationFrame(restore)
3919
+ : setTimeout(restore, 0);
3920
+ }
3921
+
3922
+ function captureComposerActionSlotLayout() {
3923
+ const cells = Array.from(elements.composerActionGridGuide?.children || []);
3924
+ if (!cells.length) return;
3925
+ composerActionLayoutColumns = composerActionGridColumnCount();
3926
+ const nextLayout = new Map();
3927
+ for (const record of orderedComposerActionRecords({ visibleOnly: true })) {
3928
+ const actionRect = record.root.getBoundingClientRect();
3929
+ const slot = cells.findIndex((cell) => {
3930
+ const rect = cell.getBoundingClientRect();
3931
+ const centerX = rect.left + rect.width / 2;
3932
+ const centerY = rect.top + rect.height / 2;
3933
+ return centerX >= actionRect.left - 1 && centerX <= actionRect.right + 1 && centerY >= actionRect.top - 1 && centerY <= actionRect.bottom + 1;
3934
+ });
3935
+ if (slot >= 0) nextLayout.set(record.id, slot);
3936
+ }
3937
+ composerActionSlotLayout = nextLayout;
3938
+ applyComposerActionSlotLayout();
3939
+ }
3940
+
3941
+ function repackComposerActionSlotLayout() {
3942
+ if (composerActionLayoutColumns < 1) return;
3943
+ const nextLayout = new Map();
3944
+ let slot = 0;
3945
+ for (const record of orderedComposerActionRecords({ visibleOnly: true })) {
3946
+ const column = slot % composerActionLayoutColumns;
3947
+ if (column + record.span > composerActionLayoutColumns) slot += composerActionLayoutColumns - column;
3948
+ nextLayout.set(record.id, slot);
3949
+ slot += record.span;
3950
+ }
3951
+ composerActionSlotLayout = nextLayout;
3952
+ applyComposerActionSlotLayout();
3953
+ persistComposerActionSlotLayout();
3954
+ }
3955
+
3956
+ function syncComposerActionOrderFromSlots() {
3957
+ const visibleIds = orderedComposerActionRecords({ visibleOnly: true })
3958
+ .filter(({ id }) => composerActionSlotLayout.has(id))
3959
+ .sort((a, b) => composerActionSlotLayout.get(a.id) - composerActionSlotLayout.get(b.id))
3960
+ .map(({ id }) => id);
3961
+ const completeOrder = [
3962
+ ...visibleIds,
3963
+ ...orderedComposerActionRecords().map(({ id }) => id).filter((id) => !visibleIds.includes(id)),
3964
+ ];
3965
+ applyComposerActionOrder(completeOrder);
3966
+ persistComposerActionOrder();
3967
+ }
3968
+
3969
+ function moveComposerActionToGridCell(actionId, cell) {
3970
+ const record = composerActionRecords().find(({ id }) => id === actionId);
3971
+ const slot = Number(cell?.dataset.composerActionGridCell);
3972
+ if (!record || !Number.isInteger(slot)) return false;
3973
+ const nextLayout = new Map(composerActionSlotLayout);
3974
+ nextLayout.delete(actionId);
3975
+ if (!composerActionSlotCanFit(record, slot, nextLayout)) return false;
3976
+ nextLayout.set(actionId, slot);
3977
+ composerActionSlotLayout = nextLayout;
3978
+ applyComposerActionSlotLayout();
3979
+ syncComposerActionOrderFromSlots();
3980
+ clearComposerActionDragMarkers();
3981
+ cell.classList.add("composer-action-grid-cell-target");
3982
+ composerActionLastDragOverKey = `cell:${slot}`;
3983
+ persistComposerActionSlotLayout();
3984
+ return true;
3985
+ }
3986
+
3987
+ function clearComposerActionDragMarkers() {
3988
+ for (const { root } of composerActionRecords()) {
3989
+ root.classList.remove("composer-action-drag-before", "composer-action-drag-after");
3990
+ }
3991
+ for (const cell of elements.composerActionGridGuide?.children || []) {
3992
+ cell.classList.remove("composer-action-grid-cell-target");
3993
+ }
3994
+ }
3995
+
3996
+ function showComposerActionGridGuide() {
3997
+ const row = elements.composerRow;
3998
+ const guide = elements.composerActionGridGuide;
3999
+ if (!row || !guide) return;
4000
+ const columnCount = composerActionGridColumnCount();
4001
+ const rowTops = orderedComposerActionRecords({ visibleOnly: true })
4002
+ .map(({ root }) => root.getBoundingClientRect().top)
4003
+ .sort((a, b) => a - b)
4004
+ .reduce((groups, top) => {
4005
+ if (!groups.length || top - groups.at(-1) > 4) groups.push(top);
4006
+ return groups;
4007
+ }, []);
4008
+ const rowCount = Math.max(1, rowTops.length);
4009
+ const fragment = document.createDocumentFragment();
4010
+ for (let index = 0; index < columnCount * rowCount; index += 1) {
4011
+ const cell = document.createElement("span");
4012
+ cell.className = "composer-action-grid-cell";
4013
+ cell.dataset.composerActionGridCell = String(index);
4014
+ fragment.append(cell);
4015
+ }
4016
+ guide.style.setProperty("--composer-action-grid-rows", String(rowCount));
4017
+ guide.replaceChildren(fragment);
4018
+ guide.hidden = false;
4019
+ document.body.classList.add("composer-action-drag-active");
4020
+ }
4021
+
4022
+ function hideComposerActionGridGuide() {
4023
+ document.body.classList.remove("composer-action-drag-active");
4024
+ if (elements.composerActionGridGuide) elements.composerActionGridGuide.hidden = true;
4025
+ }
4026
+
4027
+ function composerActionGridCellFromPoint(clientX, clientY) {
4028
+ for (const cell of elements.composerActionGridGuide?.children || []) {
4029
+ const rect = cell.getBoundingClientRect();
4030
+ if (clientX >= rect.left && clientX <= rect.right && clientY >= rect.top && clientY <= rect.bottom) return cell;
4031
+ }
4032
+ return null;
4033
+ }
4034
+
4035
+ function moveComposerActionRelative(fromId, targetId, insertBefore) {
4036
+ if (!fromId || !targetId || fromId === targetId) return false;
4037
+ const order = orderedComposerActionRecords().map(({ id }) => id).filter((id) => id !== fromId);
4038
+ const targetIndex = order.indexOf(targetId);
4039
+ if (targetIndex < 0) return false;
4040
+ order.splice(targetIndex + (insertBefore ? 0 : 1), 0, fromId);
4041
+ applyComposerActionOrder(order);
4042
+ if (composerActionSlotLayout.size) repackComposerActionSlotLayout();
4043
+ clearComposerActionDragMarkers();
4044
+ const targetRecord = composerActionRecords().find(({ id }) => id === targetId);
4045
+ targetRecord?.root.classList.add(insertBefore ? "composer-action-drag-before" : "composer-action-drag-after");
4046
+ composerActionLastDragOverKey = `${targetId}:${insertBefore ? "before" : "after"}`;
4047
+ persistComposerActionOrder();
4048
+ return true;
4049
+ }
4050
+
4051
+ function composerActionLabel(record) {
4052
+ return record?.focusTarget?.getAttribute("aria-label")
4053
+ || record?.focusTarget?.textContent?.trim()
4054
+ || record?.focusTarget?.getAttribute("title")
4055
+ || record?.id
4056
+ || "Action";
4057
+ }
4058
+
4059
+ function announceComposerActionPosition(actionId) {
4060
+ if (!elements.composerActionOrderStatus) return;
4061
+ const records = orderedComposerActionRecords({ visibleOnly: true });
4062
+ const index = records.findIndex(({ id }) => id === actionId);
4063
+ const record = records[index];
4064
+ if (!record || index < 0) return;
4065
+ elements.composerActionOrderStatus.textContent = `${composerActionLabel(record)} moved to position ${index + 1} of ${records.length}.`;
4066
+ }
4067
+
4068
+ function moveComposerActionByOffset(actionId, offset) {
4069
+ const records = orderedComposerActionRecords({ visibleOnly: true });
4070
+ const fromIndex = records.findIndex(({ id }) => id === actionId);
4071
+ const toIndex = fromIndex + offset;
4072
+ if (fromIndex < 0 || toIndex < 0 || toIndex >= records.length) return false;
4073
+ const moved = moveComposerActionRelative(actionId, records[toIndex].id, offset < 0);
4074
+ clearComposerActionDragMarkers();
4075
+ if (moved) {
4076
+ announceComposerActionPosition(actionId);
4077
+ queueMicrotask(() => composerActionRecords().find(({ id }) => id === actionId)?.focusTarget.focus({ preventScroll: true }));
4078
+ }
4079
+ return moved;
4080
+ }
4081
+
4082
+ function composerActionRootFromPoint(clientX, clientY) {
4083
+ return document.elementFromPoint(clientX, clientY)?.closest?.("[data-composer-action-id]") || null;
4084
+ }
4085
+
4086
+ function beginComposerActionPointerDrag(event, actionId) {
4087
+ if (event.button !== 0 || isMobileView() || !actionId || composerActionPointerDrag) return;
4088
+ if (event.target?.closest?.(".composer-publish-menu-panel, input, select, textarea, a")) return;
4089
+ composerActionPointerDrag = { actionId, pointerId: event.pointerId, startX: event.clientX, startY: event.clientY, active: false };
4090
+ window.addEventListener("pointermove", updateComposerActionPointerDrag, { capture: true });
4091
+ window.addEventListener("pointerup", endComposerActionPointerDrag, { capture: true });
4092
+ window.addEventListener("pointercancel", endComposerActionPointerDrag, { capture: true });
4093
+ }
4094
+
4095
+ function updateComposerActionPointerDrag(event) {
4096
+ const drag = composerActionPointerDrag;
4097
+ if (!drag || drag.pointerId !== event.pointerId) return;
4098
+ const distance = Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY);
4099
+ if (!drag.active && distance < COMPOSER_ACTION_POINTER_DRAG_THRESHOLD_PX) return;
4100
+ event.preventDefault();
4101
+ if (!drag.active) {
4102
+ drag.active = true;
4103
+ composerActionLastDragOverKey = "";
4104
+ clearTimeout(pointerActivationTimeout);
4105
+ pointerActivationTimeout = null;
4106
+ activePointerActivation = null;
4107
+ composerActionRecords().find(({ id }) => id === drag.actionId)?.root.classList.add("composer-action-dragging");
4108
+ showComposerActionGridGuide();
4109
+ captureComposerActionSlotLayout();
4110
+ }
4111
+ const targetRoot = composerActionRootFromPoint(event.clientX, event.clientY);
4112
+ const targetRecord = targetRoot
4113
+ ? composerActionRecords().find(({ root }) => root === targetRoot)
4114
+ : null;
4115
+ if (targetRecord?.id === drag.actionId) {
4116
+ drag.pendingRelative = null;
4117
+ if (!composerActionLastDragOverKey.startsWith("cell:")) {
4118
+ clearComposerActionDragMarkers();
4119
+ composerActionLastDragOverKey = "";
4120
+ }
4121
+ return;
4122
+ }
4123
+ if (targetRecord && !targetRecord.root.hidden) {
4124
+ const rect = targetRoot.getBoundingClientRect();
4125
+ const insertBefore = event.clientX < rect.left + rect.width / 2;
4126
+ const markerKey = `${targetRecord.id}:${insertBefore ? "before" : "after"}`;
4127
+ if (markerKey === composerActionLastDragOverKey) return;
4128
+ clearComposerActionDragMarkers();
4129
+ targetRecord.root.classList.add(insertBefore ? "composer-action-drag-before" : "composer-action-drag-after");
4130
+ composerActionLastDragOverKey = markerKey;
4131
+ drag.pendingRelative = { targetId: targetRecord.id, insertBefore };
4132
+ return;
4133
+ }
4134
+ const gridCell = composerActionGridCellFromPoint(event.clientX, event.clientY);
4135
+ if (!gridCell) return;
4136
+ const markerKey = `cell:${gridCell.dataset.composerActionGridCell}`;
4137
+ if (markerKey === composerActionLastDragOverKey) return;
4138
+ drag.pendingRelative = null;
4139
+ moveComposerActionToGridCell(drag.actionId, gridCell);
4140
+ }
4141
+
4142
+ function endComposerActionPointerDrag(event) {
4143
+ const drag = composerActionPointerDrag;
4144
+ if (!drag || drag.pointerId !== event.pointerId) return;
4145
+ window.removeEventListener("pointermove", updateComposerActionPointerDrag, { capture: true });
4146
+ window.removeEventListener("pointerup", endComposerActionPointerDrag, { capture: true });
4147
+ window.removeEventListener("pointercancel", endComposerActionPointerDrag, { capture: true });
4148
+ const sourceRecord = composerActionRecords().find(({ id }) => id === drag.actionId);
4149
+ if (drag.active && event.type === "pointerup" && drag.pendingRelative) {
4150
+ moveComposerActionRelative(drag.actionId, drag.pendingRelative.targetId, drag.pendingRelative.insertBefore);
4151
+ }
4152
+ composerActionPointerDrag = null;
4153
+ composerActionLastDragOverKey = "";
4154
+ clearComposerActionDragMarkers();
4155
+ sourceRecord?.root.classList.remove("composer-action-dragging");
4156
+ hideComposerActionGridGuide();
4157
+ if (drag.active) {
4158
+ composerActionSuppressClickUntil = Date.now() + 250;
4159
+ event.preventDefault();
4160
+ persistComposerActionOrder();
4161
+ persistComposerActionSlotLayout();
4162
+ announceComposerActionPosition(drag.actionId);
4163
+ queueMicrotask(() => sourceRecord?.focusTarget.focus({ preventScroll: true }));
4164
+ }
4165
+ }
4166
+
4167
+ function syncComposerActionGridAvailability() {
4168
+ document.body.classList.toggle("composer-action-grid-enabled", !isMobileView());
4169
+ }
4170
+
4171
+ function initializeComposerActionOrdering() {
4172
+ syncComposerActionGridAvailability();
4173
+ restoreComposerActionOrder();
4174
+ restoreComposerActionSlotLayout();
4175
+ const layoutObserver = new MutationObserver((mutations) => {
4176
+ if (mutations.some((mutation) => mutation.type === "childList" || mutation.target.matches?.("[data-composer-action-id]"))) {
4177
+ scheduleComposerActionSlotLayoutRestore();
4178
+ }
4179
+ });
4180
+ layoutObserver.observe(elements.composerRow, { childList: true, subtree: true, attributes: true, attributeFilter: ["hidden"] });
4181
+ if (typeof ResizeObserver === "function") {
4182
+ let observedRowWidth = elements.composerRow.getBoundingClientRect().width;
4183
+ const rowResizeObserver = new ResizeObserver(([entry]) => {
4184
+ const nextWidth = entry?.contentRect?.width ?? elements.composerRow.getBoundingClientRect().width;
4185
+ if (Math.abs(nextWidth - observedRowWidth) < 0.5) return;
4186
+ observedRowWidth = nextWidth;
4187
+ scheduleComposerActionSlotLayoutRestore();
4188
+ });
4189
+ rowResizeObserver.observe(elements.composerRow);
4190
+ }
4191
+ window.addEventListener("resize", scheduleComposerActionSlotLayoutRestore);
4192
+ for (const record of composerActionRecords()) {
4193
+ record.focusTarget.setAttribute("aria-keyshortcuts", "Alt+ArrowLeft Alt+ArrowRight Alt+ArrowUp Alt+ArrowDown");
4194
+ record.focusTarget.addEventListener("keydown", (event) => {
4195
+ if (isMobileView() || !event.altKey || !["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) return;
4196
+ event.preventDefault();
4197
+ moveComposerActionByOffset(record.id, ["ArrowLeft", "ArrowUp"].includes(event.key) ? -1 : 1);
4198
+ });
4199
+ record.root.addEventListener("pointerdown", (event) => beginComposerActionPointerDrag(event, record.id));
4200
+ record.root.addEventListener("click", (event) => {
4201
+ if (Date.now() >= composerActionSuppressClickUntil) return;
4202
+ event.preventDefault();
4203
+ event.stopImmediatePropagation();
4204
+ }, { capture: true });
3542
4205
  }
3543
4206
  }
3544
4207
 
@@ -3660,6 +4323,7 @@ function persistTerminalTabsLayout(layout) {
3660
4323
  } catch {
3661
4324
  // Ignore storage failures; the layout control should still work for this page load.
3662
4325
  }
4326
+ markDurableUiLayoutDirty("terminalTabs", "layout");
3663
4327
  }
3664
4328
 
3665
4329
  function readStoredToolOutputExpanded() {
@@ -3753,6 +4417,36 @@ function restoreSubagentOpenModeSetting() {
3753
4417
  setSubagentOpenMode(readStoredSubagentOpenMode(), { persist: false });
3754
4418
  }
3755
4419
 
4420
+ function readStoredSubagentAutoClearEnabled() {
4421
+ try {
4422
+ return localStorage.getItem(SUBAGENT_AUTO_CLEAR_STORAGE_KEY) === "1";
4423
+ } catch {
4424
+ return false;
4425
+ }
4426
+ }
4427
+
4428
+ function persistSubagentAutoClearEnabled(enabled) {
4429
+ try {
4430
+ localStorage.setItem(SUBAGENT_AUTO_CLEAR_STORAGE_KEY, enabled ? "1" : "0");
4431
+ } catch {
4432
+ // Ignore storage failures; the preference still applies for this page load.
4433
+ }
4434
+ }
4435
+
4436
+ function setSubagentAutoClearEnabled(enabled, { persist = true, announce = false } = {}) {
4437
+ subagentAutoClearEnabled = Boolean(enabled);
4438
+ if (persist) persistSubagentAutoClearEnabled(subagentAutoClearEnabled);
4439
+ renderSubagents();
4440
+ if (announce) addEvent(`subagent auto-clear ${subagentAutoClearEnabled ? "enabled" : "disabled"}`, "info");
4441
+ if (subagentAutoClearEnabled && !subagentsLoading && !subagentsClearingFinished && finishedSubagentRunSelections().length) {
4442
+ void clearFinishedSubagentRuns({ automatic: true });
4443
+ }
4444
+ }
4445
+
4446
+ function restoreSubagentAutoClearSetting() {
4447
+ setSubagentAutoClearEnabled(readStoredSubagentAutoClearEnabled(), { persist: false });
4448
+ }
4449
+
3756
4450
  function normalizeTerminalCustomGroupTitle(value, fallback = "Custom group") {
3757
4451
  const title = String(value || "").replace(/\s+/g, " ").trim();
3758
4452
  return (title || fallback).slice(0, 40);
@@ -3814,6 +4508,7 @@ function persistTerminalCustomGroups() {
3814
4508
  } catch {
3815
4509
  // Ignore storage failures; custom tab groups still work for this page load.
3816
4510
  }
4511
+ markDurableUiLayoutDirty("terminalTabs", "customGroups");
3817
4512
  }
3818
4513
 
3819
4514
  function workspaceGroupsForSave() {
@@ -4693,22 +5388,134 @@ function normalizeFeatureCategory(value) {
4693
5388
  return value === "lightweight-feature" || value === "complex-feature" ? value : "";
4694
5389
  }
4695
5390
 
5391
+ function normalizeFeatureDecisionKind(value) {
5392
+ return value === "feature_lightweight" || value === "feature_complex" ? value : "";
5393
+ }
5394
+
5395
+ function normalizeFeatureDecisionReason(value) {
5396
+ if (typeof value !== "string") return "";
5397
+ return value
5398
+ .replace(/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, " ")
5399
+ .replace(/\s+/g, " ")
5400
+ .trim()
5401
+ .slice(0, FEATURE_DECISION_REASON_MAX_CHARS)
5402
+ .trimEnd();
5403
+ }
5404
+
5405
+ // Accepts the structured {kind,reason} classifier payload and the legacy exact label.
5406
+ // Every other payload fails closed so the popup stays unavailable.
5407
+ function parseFeatureDecisionPayload(value) {
5408
+ if (typeof value !== "string" || !value || value.length > FEATURE_DECISION_PAYLOAD_MAX_CHARS) return null;
5409
+ const legacyKind = normalizeFeatureDecisionKind(value);
5410
+ if (legacyKind) return { kind: legacyKind, reason: "" };
5411
+ if (!value.startsWith("{")) return null;
5412
+ let parsed;
5413
+ try {
5414
+ parsed = JSON.parse(value);
5415
+ } catch {
5416
+ return null;
5417
+ }
5418
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
5419
+ const keys = Object.keys(parsed);
5420
+ if (keys.length !== 2 || !keys.includes("kind") || !keys.includes("reason")) return null;
5421
+ if (typeof parsed.reason !== "string") return null;
5422
+ const kind = normalizeFeatureDecisionKind(parsed.kind);
5423
+ const reason = normalizeFeatureDecisionReason(parsed.reason);
5424
+ return kind && reason ? { kind, reason } : null;
5425
+ }
5426
+
5427
+ function featureDecisionKindLabel(kind) {
5428
+ return kind === "feature_complex" ? "Complex feature" : "Lightweight feature";
5429
+ }
5430
+
5431
+ function formatFeatureDecisionText(decision) {
5432
+ if (!decision) return "";
5433
+ const reason = decision.reason || `The classifier reported ${decision.kind} without a reason.`;
5434
+ return `Decision: ${featureDecisionKindLabel(decision.kind)} (${decision.kind})\nReason: ${reason}`;
5435
+ }
5436
+
5437
+ function featureDecisionForTab(tabId) {
5438
+ const category = normalizeFeatureCategory(featureCategoryByTab.get(tabId));
5439
+ const decision = featureDecisionOutputByTab.get(tabId) || null;
5440
+ if (!decision || !normalizeFeatureDecisionKind(decision.kind)) return null;
5441
+ if (category === "lightweight-feature" && decision.kind === "feature_lightweight") return decision;
5442
+ if (category === "complex-feature" && decision.kind === "feature_complex") return decision;
5443
+ return null;
5444
+ }
5445
+
5446
+ function featureDecisionOutputForTab(tabId) {
5447
+ return formatFeatureDecisionText(featureDecisionForTab(tabId));
5448
+ }
5449
+
5450
+ function closeFeatureDecisionDialog({ restoreFocus = true } = {}) {
5451
+ const dialog = elements.featureDecisionDialog;
5452
+ if (!dialog?.open) {
5453
+ featureDecisionDialogTabId = null;
5454
+ if (elements.featureDecisionDialogOutput) elements.featureDecisionDialogOutput.textContent = "";
5455
+ return;
5456
+ }
5457
+ if (!restoreFocus) modalSurfaceState.delete(dialog);
5458
+ dialog.close();
5459
+ }
5460
+
5461
+ function syncFeatureDecisionDialog() {
5462
+ const dialog = elements.featureDecisionDialog;
5463
+ if (!dialog?.open) return;
5464
+ const output = featureDecisionOutputForTab(featureDecisionDialogTabId);
5465
+ if (featureDecisionDialogTabId !== activeTabId || !output || elements.featureDecisionDialogOutput?.textContent !== output) {
5466
+ closeFeatureDecisionDialog({ restoreFocus: false });
5467
+ }
5468
+ }
5469
+
5470
+ function openFeatureDecisionDialog() {
5471
+ const tabId = activeTabId;
5472
+ const output = featureDecisionOutputForTab(tabId);
5473
+ const dialog = elements.featureDecisionDialog;
5474
+ if (!tabId || !output || !dialog || !elements.featureDecisionDialogOutput) return;
5475
+ featureDecisionDialogTabId = tabId;
5476
+ elements.featureDecisionDialogOutput.textContent = output;
5477
+ if (!dialog.open) dialog.showModal();
5478
+ queueMicrotask(() => elements.featureDecisionDialogCloseButton?.focus({ preventScroll: true }));
5479
+ }
5480
+
5481
+ function clearFeatureDecisionStateForTab(tabId, { render = false } = {}) {
5482
+ if (!tabId) return;
5483
+ featureCategoryByTab.delete(tabId);
5484
+ featureDecisionOutputByTab.delete(tabId);
5485
+ if (featureDecisionDialogTabId === tabId) closeFeatureDecisionDialog({ restoreFocus: false });
5486
+ if (render && tabId === activeTabId) renderFeatureCategoryTag(tabId);
5487
+ }
5488
+
4696
5489
  function renderFeatureCategoryTag(tabId = activeTabId) {
4697
5490
  const tag = elements.featureCategoryTag;
4698
5491
  if (!tag) return;
4699
5492
  const category = normalizeFeatureCategory(featureCategoryByTab.get(tabId));
5493
+ const output = featureDecisionOutputForTab(tabId);
4700
5494
  tag.hidden = !category;
5495
+ tag.disabled = !output;
4701
5496
  tag.textContent = category;
5497
+ tag.setAttribute("aria-label", output ? `Show classifier decision and reason for ${category}` : category || "Feature category");
4702
5498
  tag.classList.toggle("lightweight-feature", category === "lightweight-feature");
4703
5499
  tag.classList.toggle("complex-feature", category === "complex-feature");
5500
+ syncFeatureDecisionDialog();
5501
+ }
5502
+
5503
+ function handleFeatureDecisionOutputStatus(statusText, tabId = activeTabId) {
5504
+ if (!tabId) return;
5505
+ const decision = parseFeatureDecisionPayload(statusText);
5506
+ if (decision) featureDecisionOutputByTab.set(tabId, decision);
5507
+ else featureDecisionOutputByTab.delete(tabId);
5508
+ if (tabId === activeTabId) renderFeatureCategoryTag(tabId);
5509
+ else if (featureDecisionDialogTabId === tabId) syncFeatureDecisionDialog();
4704
5510
  }
4705
5511
 
4706
5512
  function handleFeatureCategoryStatus(statusText, tabId = activeTabId) {
4707
5513
  if (!tabId) return;
4708
5514
  const category = normalizeFeatureCategory(statusText);
4709
5515
  if (category) featureCategoryByTab.set(tabId, category);
4710
- else featureCategoryByTab.delete(tabId);
5516
+ else clearFeatureDecisionStateForTab(tabId);
4711
5517
  if (tabId === activeTabId) renderFeatureCategoryTag(tabId);
5518
+ else if (featureDecisionDialogTabId === tabId) syncFeatureDecisionDialog();
4712
5519
  }
4713
5520
 
4714
5521
  function trackSkillUsage(tabId, skillName, kind = "used", source = "", details = {}) {
@@ -5094,6 +5901,7 @@ function updateComposerModeButtons() {
5094
5901
  }
5095
5902
  renderBusyPromptBehaviorTag();
5096
5903
  document.body.classList.toggle("pi-run-active", runActive || abortAvailable);
5904
+ scheduleComposerActionSlotLayoutRestore();
5097
5905
  }
5098
5906
 
5099
5907
  function scheduleComposerModeButtonsUpdate() {
@@ -5419,6 +6227,7 @@ function setSidePanelCollapsed(collapsed, { persist = true, focusPanel = false }
5419
6227
  } catch {
5420
6228
  // Ignore storage failures; the toggle should still work for this page load.
5421
6229
  }
6230
+ markDurableUiLayoutDirty("sidePanel", "collapsed");
5422
6231
  }
5423
6232
 
5424
6233
  function restoreSidePanelState() {
@@ -5428,7 +6237,7 @@ function restoreSidePanelState() {
5428
6237
  return;
5429
6238
  }
5430
6239
  const stored = readStoredSidePanelCollapsed();
5431
- setSidePanelCollapsed(stored ?? false, { persist: stored !== null });
6240
+ setSidePanelCollapsed(stored ?? false, { persist: false });
5432
6241
  }
5433
6242
 
5434
6243
  function readStoredWorkspaceDashboardCollapsed() {
@@ -5496,6 +6305,7 @@ function bindMobileViewChanges() {
5496
6305
  if (!mobileViewMedia) return;
5497
6306
  const syncForViewport = (event) => {
5498
6307
  applyMobileShellViewport();
6308
+ syncComposerActionGridAvailability();
5499
6309
  if (isMobileShellV2Active()) return;
5500
6310
  setComposerActionsOpen(false);
5501
6311
  setMobileFooterExpanded(false);
@@ -6111,9 +6921,14 @@ function renderPiVersionButton() {
6111
6921
  const label = formatWebuiVersion(piVersion);
6112
6922
  button.hidden = !label;
6113
6923
  button.textContent = label ? `Pi ${label}` : "";
6924
+ const state = componentUpdateTagState("pi");
6925
+ const stateText = componentUpdateTagStateText(state);
6926
+ if (state) button.dataset.updateState = state;
6927
+ else delete button.dataset.updateState;
6114
6928
  if (label) {
6115
- button.title = `View Pi ${label} release notes`;
6116
- button.setAttribute("aria-label", `View Pi ${label} release notes`);
6929
+ const base = `View Pi ${label} release notes`;
6930
+ button.title = stateText ? `${base} — ${stateText}` : base;
6931
+ button.setAttribute("aria-label", stateText ? `${base}, ${stateText}` : base);
6117
6932
  }
6118
6933
  }
6119
6934
 
@@ -6123,9 +6938,14 @@ function renderWebuiVersionButton() {
6123
6938
  const label = formatWebuiVersion(webuiVersion);
6124
6939
  button.hidden = !label;
6125
6940
  button.textContent = label ? `Web UI ${label}` : "";
6941
+ const state = componentUpdateTagState("webui");
6942
+ const stateText = componentUpdateTagStateText(state);
6943
+ if (state) button.dataset.updateState = state;
6944
+ else delete button.dataset.updateState;
6126
6945
  if (label) {
6127
- button.title = `Open Pi Web UI ${label} on npm`;
6128
- button.setAttribute("aria-label", `Open Pi Web UI ${label} package page`);
6946
+ const base = `Open Pi Web UI ${label} package and update details`;
6947
+ button.title = stateText ? `${base} — ${stateText}` : base;
6948
+ button.setAttribute("aria-label", stateText ? `${base}, ${stateText}` : base);
6129
6949
  }
6130
6950
  }
6131
6951
 
@@ -6217,7 +7037,9 @@ async function openPiReleaseNotes() {
6217
7037
  elements.piReleaseNotesBody.setAttribute("aria-busy", "true");
6218
7038
  elements.piReleaseNotesBody.replaceChildren(make("p", "muted", "Loading…"));
6219
7039
  setPiReleaseNotesLink(piReleasePageUrl(requestedVersion));
7040
+ renderComponentUpdateDialogs();
6220
7041
  if (!dialog.open) dialog.showModal();
7042
+ refreshUpdateStatus({ notify: false }).catch((error) => addEvent(`Pi/Web UI update check failed: ${error.message || String(error)}`, "warn"));
6221
7043
 
6222
7044
  try {
6223
7045
  const response = await api("/api/pi-release-notes", { scoped: false });
@@ -6348,6 +7170,9 @@ async function refreshUpdateStatus({ force = false, notify = true } = {}) {
6348
7170
  const response = await api(path, { scoped: false });
6349
7171
  latestUpdateStatus = response.data || null;
6350
7172
  if (notify) renderUpdateNotification(latestUpdateStatus);
7173
+ renderComponentUpdateIndicators();
7174
+ renderComponentUpdateDialogs();
7175
+ syncComponentUpdatePolling();
6351
7176
  return latestUpdateStatus;
6352
7177
  }
6353
7178
 
@@ -6360,6 +7185,189 @@ function scheduleUpdateStatusRefresh() {
6360
7185
  }, UPDATE_STATUS_REFRESH_MS);
6361
7186
  }
6362
7187
 
7188
+ const COMPONENT_UPDATE_TARGETS = ["pi", "webui"];
7189
+
7190
+ function componentUpdateLabel(target) {
7191
+ return target === "pi" ? "Pi" : "Web UI";
7192
+ }
7193
+
7194
+ function componentUpdateJob(target) {
7195
+ const job = latestUpdateStatus?.componentUpdates?.[target];
7196
+ return job && typeof job === "object" ? job : null;
7197
+ }
7198
+
7199
+ function componentUpdateTagState(target) {
7200
+ const job = componentUpdateJob(target);
7201
+ if (job?.state === "running") return "running";
7202
+ if (job?.state === "failed") return "failed";
7203
+ if (job?.state === "succeeded") return "succeeded";
7204
+ if (latestUpdateStatus?.[target]?.updateAvailable) return "available";
7205
+ return "";
7206
+ }
7207
+
7208
+ function componentUpdateTagStateText(state) {
7209
+ switch (state) {
7210
+ case "running": return "update running";
7211
+ case "failed": return "update failed";
7212
+ case "succeeded": return "update succeeded";
7213
+ case "available": return "update available";
7214
+ default: return "";
7215
+ }
7216
+ }
7217
+
7218
+ function anyComponentUpdateRunning() {
7219
+ return COMPONENT_UPDATE_TARGETS.some((target) => componentUpdateJob(target)?.state === "running");
7220
+ }
7221
+
7222
+ function renderComponentUpdateIndicators() {
7223
+ renderPiVersionButton();
7224
+ renderWebuiVersionButton();
7225
+ }
7226
+
7227
+ function componentUpdateStatusText(target) {
7228
+ const label = componentUpdateLabel(target);
7229
+ const job = componentUpdateJob(target);
7230
+ const pkg = latestUpdateStatus?.[target] || {};
7231
+ const current = formatWebuiVersion(pkg.currentVersion || (target === "pi" ? piVersion : webuiVersion) || "");
7232
+ const latest = formatWebuiVersion(pkg.latestVersion || "");
7233
+ if (job?.state === "running") return { text: job.message || `Updating ${label}…`, level: "warn" };
7234
+ if (job?.state === "succeeded") {
7235
+ const activation = target === "pi"
7236
+ ? "New or reloaded Pi sessions use the update; already-running tabs keep their current runtime until restarted."
7237
+ : "Restart the Web UI server to use the update; it is not restarted automatically.";
7238
+ return { text: `${job.message || `${label} update completed.`} ${activation}`, level: "success" };
7239
+ }
7240
+ if (job?.state === "failed") {
7241
+ const detail = job.error ? ` ${job.error}` : "";
7242
+ return { text: `${job.message || `${label} update failed.`}${detail} You can retry the update.`, level: "error" };
7243
+ }
7244
+ const availability = pkg.updateAvailable
7245
+ ? (latest ? `${label} ${current || "current"} → ${latest} is available.` : `${label} update is available.`)
7246
+ : "";
7247
+ if (job && job.canStart === false && job.unavailableReason) {
7248
+ return { text: [availability, job.unavailableReason].filter(Boolean).join(" "), level: "warn" };
7249
+ }
7250
+ if (availability) return { text: availability, level: "info" };
7251
+ if (pkg.checked && latest) return { text: `${label} is up to date.`, level: "info" };
7252
+ if (pkg.skippedReason) return { text: `Update check skipped: ${pkg.skippedReason}.`, level: "info" };
7253
+ return { text: "", level: "info" };
7254
+ }
7255
+
7256
+ function componentUpdateButtonState(target) {
7257
+ const label = componentUpdateLabel(target);
7258
+ const job = componentUpdateJob(target);
7259
+ const pkg = latestUpdateStatus?.[target] || {};
7260
+ if (job?.state === "running") return { disabled: true, label: "Updating…" };
7261
+ if (job && job.canStart === false) return { disabled: true, label: `Update ${label}` };
7262
+ if (componentUpdateStartInProgress || updateRequestInProgress || latestUpdateStatus?.updateInProgress || anyComponentUpdateRunning()) {
7263
+ return { disabled: true, label: `Update ${label}` };
7264
+ }
7265
+ if (job?.state === "failed") return { disabled: false, label: `Retry ${label} update` };
7266
+ if (pkg.checked && !pkg.updateAvailable) return { disabled: true, label: "Up to date" };
7267
+ return { disabled: false, label: `Update ${label}` };
7268
+ }
7269
+
7270
+ function renderComponentUpdatePanel(target, statusElement, buttonElement) {
7271
+ if (!statusElement || !buttonElement) return;
7272
+ const { text, level } = componentUpdateStatusText(target);
7273
+ statusElement.hidden = false;
7274
+ statusElement.textContent = text;
7275
+ statusElement.dataset.level = level;
7276
+ const buttonState = componentUpdateButtonState(target);
7277
+ buttonElement.disabled = buttonState.disabled;
7278
+ buttonElement.textContent = buttonState.label;
7279
+ }
7280
+
7281
+ function renderComponentUpdateDialogs() {
7282
+ renderComponentUpdatePanel("pi", elements.piComponentUpdateStatus, elements.piComponentUpdateButton);
7283
+ const pkg = latestUpdateStatus?.webui || {};
7284
+ if (elements.webuiPackageCurrentVersion) {
7285
+ elements.webuiPackageCurrentVersion.textContent = formatWebuiVersion(pkg.currentVersion || webuiVersion || "") || "Unknown";
7286
+ }
7287
+ if (elements.webuiPackageLatestVersion) {
7288
+ elements.webuiPackageLatestVersion.textContent = formatWebuiVersion(pkg.latestVersion || "") || (pkg.checked ? "Unknown" : "Not checked");
7289
+ }
7290
+ renderComponentUpdatePanel("webui", elements.webuiComponentUpdateStatus, elements.webuiComponentUpdateButton);
7291
+ }
7292
+
7293
+ function syncComponentUpdatePolling() {
7294
+ if (anyComponentUpdateRunning()) {
7295
+ if (componentUpdatePollTimer === null) {
7296
+ componentUpdatePollTimer = setTimeout(() => {
7297
+ componentUpdatePollTimer = null;
7298
+ refreshUpdateStatus({ notify: false }).catch((error) => {
7299
+ addEvent(`Component update status check failed: ${error.message || String(error)}`, "warn");
7300
+ if (anyComponentUpdateRunning()) syncComponentUpdatePolling();
7301
+ });
7302
+ }, COMPONENT_UPDATE_POLL_MS);
7303
+ }
7304
+ } else if (componentUpdatePollTimer !== null) {
7305
+ clearTimeout(componentUpdatePollTimer);
7306
+ componentUpdatePollTimer = null;
7307
+ }
7308
+ }
7309
+
7310
+ function componentUpdateConfirmationText(target) {
7311
+ const pkg = latestUpdateStatus?.[target] || {};
7312
+ const versionText = pkg.updateAvailable ? `\n\nDetected update: ${packageUpdateText(componentUpdateLabel(target), pkg)}.` : "";
7313
+ if (target === "pi") {
7314
+ return `Update Pi in the background now?${versionText}\n\nThis runs the existing "pi update --self" resolution on the Web UI host. The Web UI server and running Pi tabs are not restarted; new or reloaded Pi sessions use the updated Pi.`;
7315
+ }
7316
+ return `Update the Web UI package in the background now?${versionText}\n\nThis installs @firstpick/pi-package-webui@latest into the installation that started this server. The Web UI server is not restarted automatically; restart it afterwards to use the new version.`;
7317
+ }
7318
+
7319
+ async function startComponentUpdate(target) {
7320
+ if (componentUpdateStartInProgress) return;
7321
+ const label = componentUpdateLabel(target);
7322
+ const job = componentUpdateJob(target);
7323
+ if (job?.state === "running" || anyComponentUpdateRunning() || updateRequestInProgress || latestUpdateStatus?.updateInProgress) return;
7324
+ if (job && job.canStart === false) {
7325
+ addEvent(job.unavailableReason || `${label} update is currently unavailable.`, "warn");
7326
+ renderComponentUpdateDialogs();
7327
+ return;
7328
+ }
7329
+ const confirmed = await appConfirmText(componentUpdateConfirmationText(target), {
7330
+ affected: target === "pi" ? "The Pi installation on the Web UI host" : "The Web UI package installation on this host",
7331
+ confirmLabel: job?.state === "failed" ? `Retry ${label} update` : `Update ${label}`,
7332
+ danger: false,
7333
+ });
7334
+ if (!confirmed) return;
7335
+ componentUpdateStartInProgress = true;
7336
+ renderComponentUpdateDialogs();
7337
+ try {
7338
+ const response = await api("/api/component-update", { method: "POST", body: { target }, scoped: false });
7339
+ const accepted = response?.data;
7340
+ if (accepted && typeof accepted === "object") {
7341
+ latestUpdateStatus = {
7342
+ ...(latestUpdateStatus || {}),
7343
+ updateInProgress: true,
7344
+ componentUpdates: { ...(latestUpdateStatus?.componentUpdates || {}), [target]: accepted },
7345
+ };
7346
+ }
7347
+ addEvent(`${label} update started in the background`, "info");
7348
+ } catch (error) {
7349
+ addEvent(error.message || String(error), "error");
7350
+ if (error?.statusCode === 409) await refreshUpdateStatus({ notify: false }).catch(() => {});
7351
+ } finally {
7352
+ componentUpdateStartInProgress = false;
7353
+ renderComponentUpdateIndicators();
7354
+ renderComponentUpdateDialogs();
7355
+ syncComponentUpdatePolling();
7356
+ }
7357
+ }
7358
+
7359
+ async function openWebuiPackageDialog() {
7360
+ const dialog = elements.webuiPackageDialog;
7361
+ if (!dialog) return;
7362
+ renderComponentUpdateDialogs();
7363
+ if (!dialog.open) dialog.showModal();
7364
+ try {
7365
+ await refreshUpdateStatus({ notify: false });
7366
+ } catch (error) {
7367
+ addEvent(`Pi/Web UI update check failed: ${error.message || String(error)}`, "warn");
7368
+ }
7369
+ }
7370
+
6363
7371
  function initializeUpdateNotifications() {
6364
7372
  setTimeout(() => {
6365
7373
  refreshUpdateStatus().catch((error) => addEvent(`Pi/Web UI update check failed: ${error.message || String(error)}`, "warn"));
@@ -8709,7 +9717,10 @@ function activeTabContext(tabId = activeTabId) {
8709
9717
 
8710
9718
  function setActiveTabId(tabId, { remember = false } = {}) {
8711
9719
  const nextTabId = tabId || null;
8712
- if (nextTabId !== activeTabId) activeTabGeneration += 1;
9720
+ if (nextTabId !== activeTabId) {
9721
+ activeTabGeneration += 1;
9722
+ closeFeatureDecisionDialog({ restoreFocus: false });
9723
+ }
8713
9724
  activeTabId = nextTabId;
8714
9725
  bindGitWorkflowToActiveTab();
8715
9726
  renderFeatureCategoryTag(nextTabId);
@@ -9750,6 +10761,594 @@ async function moveFileTreeEntry(entry = fileContextMenuState?.entry) {
9750
10761
  await moveFileTreeEntryToDestination(entry, destinationPath, { confirmMove: true });
9751
10762
  }
9752
10763
 
10764
+ // --- Durable UI layout settings -------------------------------------------
10765
+ // Browser storage stays the immediate, offline-capable cache while the durable
10766
+ // per-user layout lives in the WebUI settings file behind
10767
+ // GET/PUT /api/interface-preferences. Local writes always apply first; server
10768
+ // reconciliation is non-blocking, coalesced, and revision guarded.
10769
+ const UI_LAYOUT_SCHEMA_VERSION = 1;
10770
+ const UI_LAYOUT_ENDPOINT = "/api/interface-preferences";
10771
+ const UI_LAYOUT_SAVE_DEBOUNCE_MS = 250;
10772
+ const UI_LAYOUT_MAX_CONFLICT_RETRIES = 1;
10773
+ const UI_LAYOUT_FIELDS = ["sidePanel", "composerActions", "footerScopedModelOrder", "terminalTabs", "fileViewerWidth"];
10774
+ const UI_LAYOUT_SIDE_PANEL_FIELDS = ["sectionOrder", "collapsedSectionIds", "hiddenSectionIds", "collapsed"];
10775
+ const UI_LAYOUT_COMPOSER_FIELDS = ["order", "grid"];
10776
+ const UI_LAYOUT_TERMINAL_FIELDS = ["layout", "customGroups"];
10777
+ const UI_LAYOUT_PENDING_STORAGE_PREFIX = "pi-webui-ui-layout-pending-v3:";
10778
+ const UI_LAYOUT_PENDING_WRITER_ID = globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random().toString(16).slice(2)}`;
10779
+ let durableLayoutPendingMutationSerial = 0;
10780
+ const UI_LAYOUT_ID_MAX_LENGTH = 256;
10781
+ const UI_LAYOUT_TITLE_MAX_LENGTH = 160;
10782
+ const UI_LAYOUT_LIST_MAX_ITEMS = 128;
10783
+ const UI_LAYOUT_GROUP_MAX_COUNT = 32;
10784
+ const UI_LAYOUT_GRID_MAX_COLUMNS = 24;
10785
+ const UI_LAYOUT_GRID_MAX_SLOTS = 4096;
10786
+ const UI_LAYOUT_FILE_VIEWER_WIDTH_MAX_PX = 4096;
10787
+ const UI_LAYOUT_UNSAFE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
10788
+ const UI_LAYOUT_CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/;
10789
+
10790
+ let durableLayoutRevision = null;
10791
+ const durableLayoutGenerations = new Map();
10792
+ const durableLayoutDirtyFields = new Map();
10793
+ let durableLayoutSaveTimer = null;
10794
+ let durableLayoutSaveInFlight = false;
10795
+ let durableLayoutConflictAttempts = 0;
10796
+ let durableLayoutWarned = false;
10797
+ let durableLayoutReadEpoch = 0;
10798
+ let durableLayoutAppliedReadEpoch = 0;
10799
+ let durableLayoutWriteFenceReadEpoch = 0;
10800
+
10801
+ function readDurableLayoutCache(key) {
10802
+ try {
10803
+ return localStorage.getItem(key);
10804
+ } catch {
10805
+ return null;
10806
+ }
10807
+ }
10808
+
10809
+ function writeDurableLayoutCache(key, value) {
10810
+ try {
10811
+ localStorage.setItem(key, value);
10812
+ } catch {
10813
+ // Browser storage is only the local cache for the durable layout settings.
10814
+ }
10815
+ }
10816
+
10817
+ function durableLayoutIdList(value) {
10818
+ if (!Array.isArray(value)) return null;
10819
+ const ids = [];
10820
+ const seen = new Set();
10821
+ for (const item of value) {
10822
+ if (typeof item !== "string") continue;
10823
+ const id = item.trim();
10824
+ if (!id || id.length > UI_LAYOUT_ID_MAX_LENGTH || UI_LAYOUT_CONTROL_CHARACTERS.test(id) || seen.has(id)) continue;
10825
+ seen.add(id);
10826
+ ids.push(id);
10827
+ if (ids.length >= UI_LAYOUT_LIST_MAX_ITEMS) break;
10828
+ }
10829
+ return ids;
10830
+ }
10831
+
10832
+ function durableLayoutStoredIdList(key) {
10833
+ const raw = readDurableLayoutCache(key);
10834
+ if (raw === null) return null;
10835
+ try {
10836
+ return durableLayoutIdList(JSON.parse(raw));
10837
+ } catch {
10838
+ return null;
10839
+ }
10840
+ }
10841
+
10842
+ function collectDurableSidePanelLayout() {
10843
+ const collapsed = readStoredSidePanelCollapsed();
10844
+ return {
10845
+ sectionOrder: durableLayoutStoredIdList(SIDE_PANEL_SECTION_ORDER_STORAGE_KEY),
10846
+ collapsedSectionIds: durableLayoutStoredIdList(SIDE_PANEL_SECTION_STORAGE_KEY),
10847
+ hiddenSectionIds: durableLayoutStoredIdList(SIDE_PANEL_SECTION_VISIBILITY_STORAGE_KEY),
10848
+ collapsed: typeof collapsed === "boolean" ? collapsed : null,
10849
+ };
10850
+ }
10851
+
10852
+ function collectDurableComposerActionsLayout() {
10853
+ const stored = readStoredComposerActionLayout();
10854
+ let grid = null;
10855
+ if (stored && Number.isInteger(stored.columns) && stored.columns >= 1 && stored.columns <= UI_LAYOUT_GRID_MAX_COLUMNS) {
10856
+ const positions = {};
10857
+ const usedSlots = new Set();
10858
+ let count = 0;
10859
+ for (const [rawId, slot] of stored.positions) {
10860
+ const id = typeof rawId === "string" ? rawId.trim() : "";
10861
+ if (!id || id.length > UI_LAYOUT_ID_MAX_LENGTH || UI_LAYOUT_CONTROL_CHARACTERS.test(id) || UI_LAYOUT_UNSAFE_KEYS.has(id)) continue;
10862
+ if (!Number.isInteger(slot) || slot < 0 || slot >= UI_LAYOUT_GRID_MAX_SLOTS || usedSlots.has(slot)) continue;
10863
+ usedSlots.add(slot);
10864
+ positions[id] = slot;
10865
+ count += 1;
10866
+ if (count >= UI_LAYOUT_LIST_MAX_ITEMS) break;
10867
+ }
10868
+ grid = { version: 2, columns: stored.columns, positions };
10869
+ }
10870
+ // Composer order and sparse grid always travel together as one logical update.
10871
+ return { order: durableLayoutStoredIdList(COMPOSER_ACTION_ORDER_STORAGE_KEY), grid };
10872
+ }
10873
+
10874
+ function collectDurableTerminalTabsLayout() {
10875
+ const rawLayout = readDurableLayoutCache(TERMINAL_TABS_LAYOUT_STORAGE_KEY);
10876
+ const rawGroups = readDurableLayoutCache(TERMINAL_CUSTOM_GROUPS_STORAGE_KEY);
10877
+ let customGroups = null;
10878
+ if (rawGroups !== null) {
10879
+ let parsed = null;
10880
+ try {
10881
+ parsed = JSON.parse(rawGroups);
10882
+ } catch {
10883
+ parsed = null;
10884
+ }
10885
+ const records = Array.isArray(parsed?.groups) ? parsed.groups : Array.isArray(parsed) ? parsed : [];
10886
+ const groups = [];
10887
+ const groupIds = new Set();
10888
+ const claimedTabIds = new Set();
10889
+ for (const record of records) {
10890
+ const id = String(record?.id || "").trim();
10891
+ if (!id || id.length > UI_LAYOUT_ID_MAX_LENGTH || UI_LAYOUT_CONTROL_CHARACTERS.test(id) || groupIds.has(id)) continue;
10892
+ const title = normalizeTerminalCustomGroupTitle(record?.title).slice(0, UI_LAYOUT_TITLE_MAX_LENGTH).trim();
10893
+ const tabIds = (durableLayoutIdList(normalizeTerminalCustomGroupTabIds(record?.tabIds)) || []).filter((tabId) => {
10894
+ if (claimedTabIds.has(tabId)) return false;
10895
+ claimedTabIds.add(tabId);
10896
+ return true;
10897
+ });
10898
+ if (!title || tabIds.length < 2) continue;
10899
+ groupIds.add(id);
10900
+ groups.push({ id, title, tabIds });
10901
+ if (groups.length >= UI_LAYOUT_GROUP_MAX_COUNT) break;
10902
+ }
10903
+ customGroups = { version: 1, groups };
10904
+ }
10905
+ return { layout: TERMINAL_TABS_LAYOUTS.has(rawLayout) ? rawLayout : null, customGroups };
10906
+ }
10907
+
10908
+ function collectDurableFileViewerWidth() {
10909
+ const width = readStoredFileViewerWidth();
10910
+ if (!Number.isFinite(width)) return null;
10911
+ const rounded = Math.round(width);
10912
+ return rounded >= FILE_VIEWER_WIDTH_MIN_PX && rounded <= UI_LAYOUT_FILE_VIEWER_WIDTH_MAX_PX ? rounded : null;
10913
+ }
10914
+
10915
+ function collectDurableUiLayoutField(field) {
10916
+ switch (field) {
10917
+ case "sidePanel":
10918
+ return collectDurableSidePanelLayout();
10919
+ case "composerActions":
10920
+ return collectDurableComposerActionsLayout();
10921
+ case "footerScopedModelOrder":
10922
+ return durableLayoutStoredIdList(FOOTER_SCOPED_MODEL_ORDER_STORAGE_KEY);
10923
+ case "terminalTabs":
10924
+ return collectDurableTerminalTabsLayout();
10925
+ case "fileViewerWidth":
10926
+ return collectDurableFileViewerWidth();
10927
+ default:
10928
+ return null;
10929
+ }
10930
+ }
10931
+
10932
+ function durableUiLayoutSubFields(field) {
10933
+ if (field === "sidePanel") return UI_LAYOUT_SIDE_PANEL_FIELDS;
10934
+ if (field === "composerActions") return UI_LAYOUT_COMPOSER_FIELDS;
10935
+ if (field === "terminalTabs") return UI_LAYOUT_TERMINAL_FIELDS;
10936
+ return null;
10937
+ }
10938
+
10939
+ function durableUiLayoutValuePresent(value) {
10940
+ return value !== null && value !== undefined;
10941
+ }
10942
+
10943
+ function durableUiLayoutMutationValue(field, subfield = null) {
10944
+ const value = collectDurableUiLayoutField(field);
10945
+ return subfield ? value?.[subfield] ?? null : value;
10946
+ }
10947
+
10948
+ function durableUiLayoutEntryPatch(field, entry) {
10949
+ if (!entry?.subfields?.size) return entry?.value ?? null;
10950
+ return Object.fromEntries([...entry.subfields].map((subfield) => [subfield, entry.value?.[subfield] ?? null]));
10951
+ }
10952
+
10953
+ function durableUiLayoutPendingMutationRecords() {
10954
+ const records = [];
10955
+ try {
10956
+ for (let index = 0; index < localStorage.length; index += 1) {
10957
+ const key = localStorage.key(index);
10958
+ if (!key?.startsWith(UI_LAYOUT_PENDING_STORAGE_PREFIX)) continue;
10959
+ let value;
10960
+ try {
10961
+ value = JSON.parse(localStorage.getItem(key) || "null");
10962
+ } catch {
10963
+ continue;
10964
+ }
10965
+ if (!value || value.version !== 3 || !UI_LAYOUT_FIELDS.includes(value.field)) continue;
10966
+ const allowedSubfields = durableUiLayoutSubFields(value.field);
10967
+ const subfield = typeof value.subfield === "string" ? value.subfield : null;
10968
+ if (subfield && !allowedSubfields?.includes(subfield)) continue;
10969
+ if (allowedSubfields && value.field !== "composerActions" && !subfield) continue;
10970
+ records.push({
10971
+ key,
10972
+ field: value.field,
10973
+ subfield,
10974
+ value: value.value,
10975
+ updatedAt: Number(value.updatedAt) || 0,
10976
+ });
10977
+ }
10978
+ } catch {
10979
+ return [];
10980
+ }
10981
+ return records;
10982
+ }
10983
+
10984
+ function writeDurableUiLayoutPendingMutation(field, subfield, value) {
10985
+ try {
10986
+ durableLayoutPendingMutationSerial += 1;
10987
+ const key = `${UI_LAYOUT_PENDING_STORAGE_PREFIX}${UI_LAYOUT_PENDING_WRITER_ID}:${Date.now().toString(36)}:${durableLayoutPendingMutationSerial.toString(36)}`;
10988
+ localStorage.setItem(key, JSON.stringify({
10989
+ version: 3,
10990
+ field,
10991
+ subfield,
10992
+ value,
10993
+ updatedAt: Date.now(),
10994
+ }));
10995
+ return key;
10996
+ } catch {
10997
+ return null;
10998
+ }
10999
+ }
11000
+
11001
+ function removeDurableUiLayoutPendingMutation(key) {
11002
+ if (!key) return;
11003
+ try {
11004
+ localStorage.removeItem(key);
11005
+ } catch {
11006
+ // A later startup can retry an immutable mutation record that remains.
11007
+ }
11008
+ }
11009
+
11010
+ function clearAcknowledgedDurableUiLayoutPendingMutations(snapshot) {
11011
+ for (const entry of snapshot.values()) {
11012
+ if (entry.subfieldMutationIds?.size) {
11013
+ for (const mutationId of entry.subfieldMutationIds.values()) removeDurableUiLayoutPendingMutation(mutationId);
11014
+ } else {
11015
+ removeDurableUiLayoutPendingMutation(entry.mutationId);
11016
+ }
11017
+ }
11018
+ }
11019
+
11020
+ function restoreDurableUiLayoutPendingJournal() {
11021
+ const records = durableUiLayoutPendingMutationRecords();
11022
+ const candidates = new Map();
11023
+ for (const record of records) {
11024
+ const path = record.subfield ? `${record.field}.${record.subfield}` : record.field;
11025
+ const previous = candidates.get(path);
11026
+ if (!previous || record.updatedAt > previous.updatedAt || (record.updatedAt === previous.updatedAt && record.key > previous.key)) {
11027
+ candidates.set(path, record);
11028
+ }
11029
+ }
11030
+ // Mutation records are immutable. Once a newer record exists for the same
11031
+ // path, older records are safely superseded and can never be rewritten.
11032
+ for (const record of records) {
11033
+ const path = record.subfield ? `${record.field}.${record.subfield}` : record.field;
11034
+ if (candidates.get(path)?.key !== record.key) removeDurableUiLayoutPendingMutation(record.key);
11035
+ }
11036
+
11037
+ for (const field of UI_LAYOUT_FIELDS) {
11038
+ const allowedSubfields = durableUiLayoutSubFields(field);
11039
+ const fieldCandidates = allowedSubfields && field !== "composerActions"
11040
+ ? allowedSubfields.map((subfield) => candidates.get(`${field}.${subfield}`)).filter(Boolean)
11041
+ : [candidates.get(field)].filter(Boolean);
11042
+ if (!fieldCandidates.length) continue;
11043
+ const patch = allowedSubfields && field !== "composerActions"
11044
+ ? Object.fromEntries(fieldCandidates.map((candidate) => [candidate.subfield, candidate.value]))
11045
+ : fieldCandidates[0].value;
11046
+ applyDurableUiLayoutField(field, patch);
11047
+ const generation = durableUiLayoutGeneration(field) + 1;
11048
+ const subfields = allowedSubfields && field !== "composerActions"
11049
+ ? new Set(fieldCandidates.map((candidate) => candidate.subfield))
11050
+ : null;
11051
+ const subfieldGenerations = subfields
11052
+ ? new Map([...subfields].map((subfield) => [subfield, generation]))
11053
+ : null;
11054
+ const subfieldMutationIds = subfields
11055
+ ? new Map(fieldCandidates.map((candidate) => [candidate.subfield, candidate.key]))
11056
+ : null;
11057
+ durableLayoutGenerations.set(field, generation);
11058
+ durableLayoutDirtyFields.set(field, {
11059
+ generation,
11060
+ value: collectDurableUiLayoutField(field),
11061
+ subfields,
11062
+ subfieldGenerations,
11063
+ subfieldMutationIds,
11064
+ mutationId: subfields ? null : fieldCandidates[0].key,
11065
+ });
11066
+ }
11067
+ if (durableLayoutDirtyFields.size) scheduleDurableUiLayoutSave();
11068
+ }
11069
+
11070
+ function applyDurableSidePanelLayout(value) {
11071
+ if (!value) return;
11072
+ if (Array.isArray(value.sectionOrder)) {
11073
+ writeDurableLayoutCache(SIDE_PANEL_SECTION_ORDER_STORAGE_KEY, JSON.stringify(value.sectionOrder));
11074
+ restoreSidePanelSectionOrder();
11075
+ }
11076
+ if (Array.isArray(value.hiddenSectionIds)) {
11077
+ writeDurableLayoutCache(SIDE_PANEL_SECTION_VISIBILITY_STORAGE_KEY, JSON.stringify(value.hiddenSectionIds));
11078
+ restoreSidePanelSectionVisibility();
11079
+ }
11080
+ if (Array.isArray(value.collapsedSectionIds)) {
11081
+ writeDurableLayoutCache(SIDE_PANEL_SECTION_STORAGE_KEY, JSON.stringify(value.collapsedSectionIds));
11082
+ restoreSidePanelSectionState();
11083
+ }
11084
+ if (typeof value.collapsed === "boolean") {
11085
+ writeDurableLayoutCache(SIDE_PANEL_STORAGE_KEY, value.collapsed ? "1" : "0");
11086
+ restoreSidePanelState();
11087
+ }
11088
+ }
11089
+
11090
+ function applyDurableComposerActionsLayout(value) {
11091
+ if (!value) return;
11092
+ if (Array.isArray(value.order)) {
11093
+ writeDurableLayoutCache(COMPOSER_ACTION_ORDER_STORAGE_KEY, JSON.stringify(value.order));
11094
+ restoreComposerActionOrder();
11095
+ }
11096
+ if (value.grid && value.grid.version === 2) {
11097
+ // Keep the saved geometry as the canonical layout. Restore projects its
11098
+ // horizontal positions into the current responsive grid without rewriting
11099
+ // the source slots, so resizing back restores the exact original cells.
11100
+ writeDurableLayoutCache(COMPOSER_ACTION_LAYOUT_STORAGE_KEY, JSON.stringify(value.grid));
11101
+ restoreComposerActionSlotLayout();
11102
+ }
11103
+ }
11104
+
11105
+ function applyDurableFooterScopedModelOrder(value) {
11106
+ if (!Array.isArray(value)) return;
11107
+ writeDurableLayoutCache(FOOTER_SCOPED_MODEL_ORDER_STORAGE_KEY, JSON.stringify(value));
11108
+ footerScopedModels = orderedFooterScopedModels();
11109
+ renderFooter();
11110
+ }
11111
+
11112
+ function applyDurableTerminalTabsLayout(value) {
11113
+ if (!value) return;
11114
+ if (TERMINAL_TABS_LAYOUTS.has(value.layout)) {
11115
+ writeDurableLayoutCache(TERMINAL_TABS_LAYOUT_STORAGE_KEY, value.layout);
11116
+ setTerminalTabsLayout(value.layout, { persist: false });
11117
+ }
11118
+ if (value.customGroups && value.customGroups.version === 1) {
11119
+ writeDurableLayoutCache(TERMINAL_CUSTOM_GROUPS_STORAGE_KEY, JSON.stringify(value.customGroups));
11120
+ restoreTerminalCustomGroups();
11121
+ syncTerminalCustomGroupsWithTabs(tabs, { persist: false });
11122
+ renderTabs();
11123
+ }
11124
+ }
11125
+
11126
+ function applyDurableFileViewerWidth(value) {
11127
+ if (!Number.isFinite(value)) return;
11128
+ const width = Math.round(value);
11129
+ if (width < FILE_VIEWER_WIDTH_MIN_PX) return;
11130
+ writeDurableLayoutCache(FILE_VIEWER_WIDTH_STORAGE_KEY, String(width));
11131
+ restoreFileViewerWidthPreference();
11132
+ if (activeFileViewer && !isSidePanelOverlayView()) applyFileViewerWidth(width);
11133
+ }
11134
+
11135
+ function applyDurableUiLayoutField(field, value) {
11136
+ if (field === "sidePanel") applyDurableSidePanelLayout(value);
11137
+ else if (field === "composerActions") applyDurableComposerActionsLayout(value);
11138
+ else if (field === "footerScopedModelOrder") applyDurableFooterScopedModelOrder(value);
11139
+ else if (field === "terminalTabs") applyDurableTerminalTabsLayout(value);
11140
+ else if (field === "fileViewerWidth") applyDurableFileViewerWidth(value);
11141
+ }
11142
+
11143
+ function durableUiLayoutInteractionActive(field = null) {
11144
+ const activeByField = {
11145
+ sidePanel: Boolean(sidePanelSectionPointerDrag?.active),
11146
+ composerActions: Boolean(composerActionPointerDrag?.active),
11147
+ footerScopedModelOrder: Boolean(footerScopedModelPointerDrag?.active),
11148
+ terminalTabs: Boolean(terminalTabDragId),
11149
+ fileViewerWidth: Boolean(fileViewerResizeState),
11150
+ };
11151
+ return field ? activeByField[field] === true : Object.values(activeByField).some(Boolean);
11152
+ }
11153
+
11154
+ function durableUiLayoutGeneration(field) {
11155
+ return durableLayoutGenerations.get(field) || 0;
11156
+ }
11157
+
11158
+ function warnDurableUiLayoutOnce(message) {
11159
+ if (durableLayoutWarned) return;
11160
+ durableLayoutWarned = true;
11161
+ addEvent(message, "warn");
11162
+ }
11163
+
11164
+ function scheduleDurableUiLayoutSave(delay = UI_LAYOUT_SAVE_DEBOUNCE_MS) {
11165
+ // One coalescing writer: repeated drag-over commits only reset this timer.
11166
+ if (durableLayoutSaveTimer !== null) clearTimeout(durableLayoutSaveTimer);
11167
+ durableLayoutSaveTimer = setTimeout(() => {
11168
+ durableLayoutSaveTimer = null;
11169
+ flushDurableUiLayoutSave();
11170
+ }, delay);
11171
+ }
11172
+
11173
+ function markDurableUiLayoutDirty(field, subfield = null) {
11174
+ if (!UI_LAYOUT_FIELDS.includes(field)) return;
11175
+ const allowedSubfields = durableUiLayoutSubFields(field);
11176
+ if (subfield && !allowedSubfields?.includes(subfield)) return;
11177
+ const generation = durableUiLayoutGeneration(field) + 1;
11178
+ const previous = durableLayoutDirtyFields.get(field);
11179
+ const value = collectDurableUiLayoutField(field);
11180
+ let subfields = null;
11181
+ let subfieldGenerations = null;
11182
+ let subfieldMutationIds = null;
11183
+ let mutationId = null;
11184
+ if (allowedSubfields && field !== "composerActions") {
11185
+ subfields = new Set(previous?.subfields || []);
11186
+ subfieldGenerations = new Map(previous?.subfieldGenerations || []);
11187
+ subfieldMutationIds = new Map(previous?.subfieldMutationIds || []);
11188
+ const changedSubfields = subfield ? [subfield] : allowedSubfields;
11189
+ for (const key of changedSubfields) {
11190
+ const nextMutationId = writeDurableUiLayoutPendingMutation(field, key, value?.[key] ?? null);
11191
+ if (nextMutationId) {
11192
+ removeDurableUiLayoutPendingMutation(subfieldMutationIds.get(key));
11193
+ subfieldMutationIds.set(key, nextMutationId);
11194
+ }
11195
+ subfields.add(key);
11196
+ subfieldGenerations.set(key, generation);
11197
+ }
11198
+ } else {
11199
+ mutationId = writeDurableUiLayoutPendingMutation(field, null, value);
11200
+ if (mutationId) removeDurableUiLayoutPendingMutation(previous?.mutationId);
11201
+ else mutationId = previous?.mutationId || null;
11202
+ }
11203
+ durableLayoutGenerations.set(field, generation);
11204
+ durableLayoutDirtyFields.set(field, {
11205
+ generation,
11206
+ value,
11207
+ subfields,
11208
+ subfieldGenerations,
11209
+ subfieldMutationIds,
11210
+ mutationId,
11211
+ });
11212
+ durableLayoutConflictAttempts = 0;
11213
+ scheduleDurableUiLayoutSave();
11214
+ }
11215
+
11216
+ function applyDurableUiLayoutSnapshot(data, { generations = null, readEpoch = 0 } = {}) {
11217
+ if (!data || typeof data !== "object") return false;
11218
+ if (readEpoch && readEpoch <= durableLayoutWriteFenceReadEpoch) return false;
11219
+ if (readEpoch && readEpoch < durableLayoutAppliedReadEpoch) return false;
11220
+ if (readEpoch) durableLayoutAppliedReadEpoch = readEpoch;
11221
+ if (typeof data.layoutRevision === "string" && data.layoutRevision) durableLayoutRevision = data.layoutRevision;
11222
+ const layout = data.layout && typeof data.layout === "object" ? data.layout : null;
11223
+ if (!layout || layout.version !== UI_LAYOUT_SCHEMA_VERSION) return Boolean(durableLayoutRevision);
11224
+ for (const field of UI_LAYOUT_FIELDS) {
11225
+ const requestedGeneration = generations ? generations.get(field) ?? 0 : durableUiLayoutGeneration(field);
11226
+ const generationChanged = durableUiLayoutGeneration(field) !== requestedGeneration;
11227
+ const dirtyEntry = durableLayoutDirtyFields.get(field);
11228
+ const serverValue = layout[field] ?? null;
11229
+ const localValue = collectDurableUiLayoutField(field);
11230
+ const subfields = durableUiLayoutSubFields(field);
11231
+ const dirtySubfields = dirtyEntry?.subfields;
11232
+
11233
+ if (subfields && field !== "composerActions") {
11234
+ const applicable = {};
11235
+ let hasApplicable = false;
11236
+ for (const subfield of subfields) {
11237
+ const isDirty = dirtySubfields?.has(subfield) === true;
11238
+ const remote = serverValue?.[subfield] ?? null;
11239
+ const local = localValue?.[subfield] ?? null;
11240
+ if (!isDirty && !generationChanged && !durableUiLayoutInteractionActive(field) && durableUiLayoutValuePresent(remote)) {
11241
+ applicable[subfield] = remote;
11242
+ hasApplicable = true;
11243
+ }
11244
+ if (!isDirty && !durableUiLayoutValuePresent(remote) && durableUiLayoutValuePresent(local)) {
11245
+ markDurableUiLayoutDirty(field, subfield);
11246
+ }
11247
+ }
11248
+ if (hasApplicable) applyDurableUiLayoutField(field, applicable);
11249
+ continue;
11250
+ }
11251
+
11252
+ if (!dirtyEntry && !generationChanged && !durableUiLayoutInteractionActive(field) && durableUiLayoutValuePresent(serverValue)) {
11253
+ applyDurableUiLayoutField(field, serverValue);
11254
+ }
11255
+ if (!dirtyEntry && !durableUiLayoutValuePresent(serverValue) && durableUiLayoutValuePresent(localValue)) {
11256
+ markDurableUiLayoutDirty(field);
11257
+ }
11258
+ }
11259
+ return true;
11260
+ }
11261
+
11262
+ async function refreshDurableUiLayoutFromServer() {
11263
+ const generations = new Map(UI_LAYOUT_FIELDS.map((field) => [field, durableUiLayoutGeneration(field)]));
11264
+ const readEpoch = ++durableLayoutReadEpoch;
11265
+ try {
11266
+ const response = await api(UI_LAYOUT_ENDPOINT, { scoped: false });
11267
+ return applyDurableUiLayoutSnapshot(response.data, { generations, readEpoch });
11268
+ } catch {
11269
+ // Keep the local cache authoritative until the settings file is reachable.
11270
+ return false;
11271
+ }
11272
+ }
11273
+
11274
+ async function flushDurableUiLayoutSave() {
11275
+ if (durableLayoutSaveInFlight || !durableLayoutDirtyFields.size) return;
11276
+ if ([...durableLayoutDirtyFields.keys()].some((field) => durableUiLayoutInteractionActive(field))) {
11277
+ scheduleDurableUiLayoutSave();
11278
+ return;
11279
+ }
11280
+ if (typeof navigator !== "undefined" && navigator.onLine === false) return;
11281
+ durableLayoutSaveInFlight = true;
11282
+ let snapshot = new Map();
11283
+ let retryImmediately = false;
11284
+ try {
11285
+ if (!durableLayoutRevision) await refreshDurableUiLayoutFromServer();
11286
+ if (!durableLayoutRevision || !durableLayoutDirtyFields.size) return;
11287
+ snapshot = new Map([...durableLayoutDirtyFields].map(([field, entry]) => [field, {
11288
+ ...entry,
11289
+ subfields: entry.subfields ? new Set(entry.subfields) : null,
11290
+ subfieldGenerations: entry.subfieldGenerations ? new Map(entry.subfieldGenerations) : null,
11291
+ subfieldMutationIds: entry.subfieldMutationIds ? new Map(entry.subfieldMutationIds) : null,
11292
+ }]));
11293
+ const patch = { version: UI_LAYOUT_SCHEMA_VERSION };
11294
+ for (const [field, entry] of snapshot) patch[field] = durableUiLayoutEntryPatch(field, entry);
11295
+ const response = await api(UI_LAYOUT_ENDPOINT, {
11296
+ method: "PUT",
11297
+ scoped: false,
11298
+ body: { layout: patch, expectedLayoutRevision: durableLayoutRevision },
11299
+ });
11300
+ // A successful write is newer than every GET that began before this
11301
+ // acknowledgement, even if one of those reads completes afterward.
11302
+ durableLayoutWriteFenceReadEpoch = Math.max(durableLayoutWriteFenceReadEpoch, durableLayoutReadEpoch);
11303
+ if (typeof response.data?.layoutRevision === "string" && response.data.layoutRevision) durableLayoutRevision = response.data.layoutRevision;
11304
+ for (const [field, entry] of snapshot) {
11305
+ const current = durableLayoutDirtyFields.get(field);
11306
+ if (!current) continue;
11307
+ if (entry.subfields?.size) {
11308
+ for (const subfield of entry.subfields) {
11309
+ if (current.subfieldGenerations?.get(subfield) !== entry.subfieldGenerations?.get(subfield)) continue;
11310
+ if (current.subfieldMutationIds?.get(subfield) !== entry.subfieldMutationIds?.get(subfield)) continue;
11311
+ current.subfields.delete(subfield);
11312
+ current.subfieldGenerations.delete(subfield);
11313
+ current.subfieldMutationIds.delete(subfield);
11314
+ }
11315
+ if (!current.subfields.size) durableLayoutDirtyFields.delete(field);
11316
+ else current.value = collectDurableUiLayoutField(field);
11317
+ } else if (current.generation === entry.generation && current.mutationId === entry.mutationId) {
11318
+ durableLayoutDirtyFields.delete(field);
11319
+ }
11320
+ }
11321
+ clearAcknowledgedDurableUiLayoutPendingMutations(snapshot);
11322
+ durableLayoutConflictAttempts = 0;
11323
+ durableLayoutWarned = false;
11324
+ } catch (error) {
11325
+ const status = Number(error?.statusCode) || 0;
11326
+ if (status === 409) {
11327
+ durableLayoutConflictAttempts += 1;
11328
+ await refreshDurableUiLayoutFromServer();
11329
+ if (durableLayoutConflictAttempts <= UI_LAYOUT_MAX_CONFLICT_RETRIES) retryImmediately = durableLayoutDirtyFields.size > 0;
11330
+ else warnDurableUiLayoutOnce("Durable layout changes stayed in this browser because the saved layout kept changing elsewhere.");
11331
+ } else if (status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 429) {
11332
+ // Keep the pending journal for recovery, but do not retry a rejected
11333
+ // payload until another user/lifecycle event supplies a new opportunity.
11334
+ warnDurableUiLayoutOnce(`Could not save the durable UI layout: ${error?.message || String(error)}`);
11335
+ }
11336
+ // Offline and server failures keep the newest dirty state for the next
11337
+ // mutation, online event, or foreground reconciliation.
11338
+ } finally {
11339
+ durableLayoutSaveInFlight = false;
11340
+ }
11341
+ const hasNewerMutation = [...durableLayoutDirtyFields].some(([field, entry]) => snapshot.get(field)?.generation !== entry.generation);
11342
+ if (retryImmediately || hasNewerMutation) scheduleDurableUiLayoutSave(retryImmediately ? 0 : UI_LAYOUT_SAVE_DEBOUNCE_MS);
11343
+ }
11344
+
11345
+ function reconcileDurableUiLayout() {
11346
+ if (durableUiLayoutInteractionActive()) return;
11347
+ refreshDurableUiLayoutFromServer().then((ready) => {
11348
+ if (ready && durableLayoutDirtyFields.size) scheduleDurableUiLayoutSave(0);
11349
+ });
11350
+ }
11351
+
9753
11352
  function readStoredSidePanelWidth() {
9754
11353
  try {
9755
11354
  const width = Number.parseFloat(localStorage.getItem(SIDE_PANEL_WIDTH_STORAGE_KEY) || "");
@@ -9833,8 +11432,13 @@ async function restoreSidePanelWidthPreference() {
9833
11432
  else updateSidePanelResizeHandle(localWidth || SIDE_PANEL_WIDTH_DEFAULT_PX);
9834
11433
 
9835
11434
  const restoreRevision = sidePanelWidthPreferenceRevision;
11435
+ const layoutGenerations = new Map(UI_LAYOUT_FIELDS.map((field) => [field, durableUiLayoutGeneration(field)]));
11436
+ const readEpoch = ++durableLayoutReadEpoch;
9836
11437
  try {
11438
+ // One non-blocking unscoped read hydrates both the width preference and the
11439
+ // durable layout after the synchronous local-cache startup pass.
9837
11440
  const response = await api("/api/interface-preferences", { scoped: false });
11441
+ applyDurableUiLayoutSnapshot(response.data, { generations: layoutGenerations, readEpoch });
9838
11442
  if (restoreRevision !== sidePanelWidthPreferenceRevision) return;
9839
11443
  const userWidth = Number(response.data?.preferences?.sidePanelWidth);
9840
11444
  if (Number.isFinite(userWidth) && userWidth >= SIDE_PANEL_WIDTH_MIN_PX) {
@@ -9902,7 +11506,10 @@ function syncSidePanelWidthForViewport() {
9902
11506
  updateSidePanelResizeHandle();
9903
11507
  return;
9904
11508
  }
9905
- applySidePanelWidth(currentSidePanelWidth());
11509
+ // Keep viewport/layout reconciliation anchored to the durable preference.
11510
+ // Reading the rendered width here can capture an in-progress CSS transition
11511
+ // during hard-reset startup and permanently freeze the panel below its saved width.
11512
+ applySidePanelWidth(readStoredSidePanelWidth() || currentSidePanelWidth());
9906
11513
  }
9907
11514
 
9908
11515
  function readStoredFileViewerWidth() {
@@ -9920,6 +11527,7 @@ function persistFileViewerWidth(width) {
9920
11527
  } catch {
9921
11528
  // Ignore storage failures; resizing should still work for this page load.
9922
11529
  }
11530
+ markDurableUiLayoutDirty("fileViewerWidth");
9923
11531
  }
9924
11532
 
9925
11533
  function fileViewerMaxWidth() {
@@ -10825,7 +12433,7 @@ function syncTabMetadata(nextTabs = []) {
10825
12433
  suppressPendingAgentDoneNotificationsForTab(tabId, { markSeen: false });
10826
12434
  actionFeedbackByTab.delete(tabId);
10827
12435
  skillUsageByTab.delete(tabId);
10828
- featureCategoryByTab.delete(tabId);
12436
+ clearFeatureDecisionStateForTab(tabId);
10829
12437
  tabMessagesCache.delete(tabId);
10830
12438
  widgetsByTab.delete(tabId);
10831
12439
  appRunnerDataByTab.delete(tabId);
@@ -11151,6 +12759,7 @@ function cancelPendingDialogs() {
11151
12759
  }).catch((error) => console.warn("failed to cancel stale extension dialog", error));
11152
12760
  }
11153
12761
  activeDialog = null;
12762
+ activeDialogCancel = null;
11154
12763
  if (elements.dialog.open) elements.dialog.close();
11155
12764
  }
11156
12765
 
@@ -12771,7 +14380,7 @@ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs", all
12771
14380
  tabDrafts.delete(id);
12772
14381
  clearAttachments(id);
12773
14382
  clearGitWorkflowForTab(id);
12774
- featureCategoryByTab.delete(id);
14383
+ clearFeatureDecisionStateForTab(id);
12775
14384
  commandCatalogsByTab.delete(id);
12776
14385
  appRunnerDataByTab.delete(id);
12777
14386
  tabMessagesCache.delete(id);
@@ -12824,6 +14433,10 @@ async function closeAllTerminalTabs() {
12824
14433
 
12825
14434
  async function initializeTabs() {
12826
14435
  const loadedTabs = await refreshTabs({ selectStored: true });
14436
+ // Durable groups can arrive before the initial tab catalog. Rehydrate them
14437
+ // after tabs load so valid memberships are not filtered against an empty set.
14438
+ restoreTerminalCustomGroups();
14439
+ syncTerminalCustomGroupsWithTabs(tabs, { persist: false });
12827
14440
  restoreMobileContinuityState();
12828
14441
  resetActiveTabUi();
12829
14442
  renderTabs();
@@ -13848,6 +15461,27 @@ function applyFooterContextUsage(node, contextUsage) {
13848
15461
  return node;
13849
15462
  }
13850
15463
 
15464
+ // Dedicated Usage visual apply path: sets two independent lane widths (top =
15465
+ // primary/first window, bottom = secondary/second window) plus a max-window
15466
+ // active foreground/glow reusing the Context color interpolation. Clamps
15467
+ // defensively to 0..100; exact text and tooltip remain untouched.
15468
+ function applyFooterUsageWindows(node, usageWindows) {
15469
+ node.classList.add("footer-usage-card");
15470
+ const primaryPercent = typeof usageWindows?.primaryPercent === "number" ? usageWindows.primaryPercent : Number.NaN;
15471
+ const secondaryPercent = typeof usageWindows?.secondaryPercent === "number" ? usageWindows.secondaryPercent : Number.NaN;
15472
+ if (Number.isFinite(primaryPercent) && Number.isFinite(secondaryPercent)) {
15473
+ const clampedPrimary = Math.min(100, Math.max(0, primaryPercent));
15474
+ const clampedSecondary = Math.min(100, Math.max(0, secondaryPercent));
15475
+ const activeColor = contextUsageActiveColor(Math.max(clampedPrimary, clampedSecondary));
15476
+ node.classList.add("has-usage-windows");
15477
+ node.style.setProperty("--usage-primary", `${clampedPrimary.toFixed(1)}%`);
15478
+ node.style.setProperty("--usage-secondary", `${clampedSecondary.toFixed(1)}%`);
15479
+ node.style.setProperty("--usage-active-color", activeColor.color);
15480
+ node.style.setProperty("--usage-active-glow", activeColor.glow);
15481
+ }
15482
+ return node;
15483
+ }
15484
+
13851
15485
  const FOOTER_MIDDLE_TRUNCATION_END_CHARS = 16;
13852
15486
  const FOOTER_MIDDLE_TRUNCATION_MIN_START_CHARS = 6;
13853
15487
 
@@ -13935,6 +15569,7 @@ const GIT_FOOTER_TOOLTIP_COPY = {
13935
15569
  speed: "Assistant streaming speed. Shows live output tokens for the current reply and current or last tokens per second.",
13936
15570
  cost: "Estimated session cost. sub means subscription-backed provider; api means metered API usage.",
13937
15571
  context: "Context window pressure. Shows percent used over the model limit; auto means auto-compaction is enabled.",
15572
+ usage: "Provider subscription usage. Shows the used share of the provider-reported primary and secondary rate windows.",
13938
15573
  cwd: "Active working directory for this Web UI tab.",
13939
15574
  git: "Current Git branch. detached means HEAD is not on a branch; no repo means the cwd is outside a Git work tree.",
13940
15575
  "git-state": "Active Git operation or detached state. Finish or abort rebase/merge/cherry-pick/revert/bisect before normal commits.",
@@ -14313,6 +15948,13 @@ function normalizeFooterPayloadChip(value, index) {
14313
15948
  contextWindow: Number.isFinite(contextWindow) ? contextWindow : 0,
14314
15949
  };
14315
15950
  }
15951
+ if (value.usageWindows && typeof value.usageWindows === "object") {
15952
+ const primaryPercent = typeof value.usageWindows.primaryPercent === "number" ? value.usageWindows.primaryPercent : Number.NaN;
15953
+ const secondaryPercent = typeof value.usageWindows.secondaryPercent === "number" ? value.usageWindows.secondaryPercent : Number.NaN;
15954
+ if (Number.isFinite(primaryPercent) && Number.isFinite(secondaryPercent)) {
15955
+ chip.usageWindows = { primaryPercent, secondaryPercent };
15956
+ }
15957
+ }
14316
15958
  return chip;
14317
15959
  }
14318
15960
 
@@ -14615,7 +16257,9 @@ function renderGitFooterPayloadMetric(chip, payload) {
14615
16257
  const action = piAction || contextAction;
14616
16258
  options.title = gitFooterPayloadTooltip(chip, { action });
14617
16259
  const node = footerMetric(chip.icon || "•", chip.label, chip.value, chip.tone ? `tone-${chip.tone}` : "", options);
14618
- return chip.contextUsage ? applyFooterContextUsage(node, chip.contextUsage) : node;
16260
+ if (chip.contextUsage) applyFooterContextUsage(node, chip.contextUsage);
16261
+ if (chip.usageWindows) applyFooterUsageWindows(node, chip.usageWindows);
16262
+ return node;
14619
16263
  }
14620
16264
 
14621
16265
  function gitFooterSyncOutgoingCount(value) {
@@ -14744,7 +16388,9 @@ function renderGitFooterPayloadMeta(chip, tab, payload) {
14744
16388
  node.setAttribute("aria-haspopup", "listbox");
14745
16389
  node.setAttribute("aria-expanded", footerBranchPickerOpen ? "true" : "false");
14746
16390
  }
14747
- return chip.contextUsage ? applyFooterContextUsage(node, chip.contextUsage) : node;
16391
+ if (chip.contextUsage) applyFooterContextUsage(node, chip.contextUsage);
16392
+ if (chip.usageWindows) applyFooterUsageWindows(node, chip.usageWindows);
16393
+ return node;
14748
16394
  }
14749
16395
 
14750
16396
  // Shape key for a footer chip with the frequently-changing fields removed, so
@@ -14754,10 +16400,17 @@ function gitFooterChipShapeKey(chip) {
14754
16400
  const shape = {};
14755
16401
  for (const [key, value] of Object.entries(chip || {})) {
14756
16402
  if (key === "value") continue;
16403
+ // Usage percentages/reset details make its title dynamic. The fast path
16404
+ // refreshes the complete tooltip and aria-label in place below.
16405
+ if (key === "title" && chip?.key === "usage") continue;
14757
16406
  if (key === "contextUsage") {
14758
16407
  shape.contextUsage = value ? true : false;
14759
16408
  continue;
14760
16409
  }
16410
+ if (key === "usageWindows") {
16411
+ shape.usageWindows = value ? true : false;
16412
+ continue;
16413
+ }
14761
16414
  shape[key] = value;
14762
16415
  }
14763
16416
  return JSON.stringify(shape);
@@ -14794,9 +16447,12 @@ function updateGitFooterChipNodeValue(node, chip, valueSelector) {
14794
16447
  }
14795
16448
  const previousTooltip = node.getAttribute("data-tooltip");
14796
16449
  if (previousTooltip) {
14797
- const nextTooltip = previousTooltip.replace(/Current: [^\n]*/u, `Current: ${cleanFooterPayloadText(chip.value, "—")}`);
16450
+ const nextTooltip = chip.key === "usage"
16451
+ ? gitFooterPayloadTooltip(chip)
16452
+ : previousTooltip.replace(/Current: [^\n]*/u, `Current: ${cleanFooterPayloadText(chip.value, "—")}`);
14798
16453
  if (nextTooltip !== previousTooltip) {
14799
16454
  node.setAttribute("data-tooltip", nextTooltip);
16455
+ node.setAttribute("aria-label", nextTooltip.replace(/\s+/g, " "));
14800
16456
  if (footerTooltipTarget === node && footerTooltipNode && !footerTooltipNode.hidden) {
14801
16457
  footerTooltipNode.textContent = nextTooltip;
14802
16458
  positionFooterTooltip(node);
@@ -14804,6 +16460,7 @@ function updateGitFooterChipNodeValue(node, chip, valueSelector) {
14804
16460
  }
14805
16461
  }
14806
16462
  if (chip.contextUsage) applyFooterContextUsage(node, chip.contextUsage);
16463
+ if (chip.usageWindows) applyFooterUsageWindows(node, chip.usageWindows);
14807
16464
  }
14808
16465
 
14809
16466
  let gitFooterRenderCache = null;
@@ -17887,6 +19544,7 @@ function writeFooterScopedModelOrder(order) {
17887
19544
  try {
17888
19545
  localStorage.setItem(FOOTER_SCOPED_MODEL_ORDER_STORAGE_KEY, JSON.stringify([...new Set(order.filter(Boolean))]));
17889
19546
  } catch {}
19547
+ markDurableUiLayoutDirty("footerScopedModelOrder");
17890
19548
  }
17891
19549
 
17892
19550
  function orderedFooterScopedModels() {
@@ -19359,7 +21017,7 @@ function finishedSubagentRunSelections(data = latestSubagents) {
19359
21017
  ));
19360
21018
  }
19361
21019
 
19362
- async function clearFinishedSubagentRuns() {
21020
+ async function clearFinishedSubagentRuns({ automatic = false } = {}) {
19363
21021
  if (subagentsClearingFinished || subagentsLoading) return;
19364
21022
  const selections = finishedSubagentRunSelections();
19365
21023
  if (!selections.length) return;
@@ -19387,8 +21045,8 @@ async function clearFinishedSubagentRuns() {
19387
21045
  renderSubagents();
19388
21046
  scheduleRefreshSubagents();
19389
21047
  }
19390
- if (dismissed) addEvent(`cleared ${dismissed} finished subagent ${dismissed === 1 ? "run" : "runs"}`, "info");
19391
- if (failures.length) addEvent(`could not clear ${failures.length} finished subagent ${failures.length === 1 ? "run" : "runs"}`, "warn");
21048
+ if (dismissed) addEvent(`${automatic ? "auto-cleared" : "cleared"} ${dismissed} finished subagent ${dismissed === 1 ? "run" : "runs"}`, "info");
21049
+ if (failures.length) addEvent(`could not ${automatic ? "auto-clear" : "clear"} ${failures.length} finished subagent ${failures.length === 1 ? "run" : "runs"}`, "warn");
19392
21050
  }
19393
21051
 
19394
21052
  function subagentOverlayTranscriptMessages(data = subagentOverlayData) {
@@ -20401,6 +22059,13 @@ function renderSubagents() {
20401
22059
  elements.subagentCountBadge.textContent = String(totalAgents);
20402
22060
  elements.subagentCountBadge.hidden = totalAgents === 0;
20403
22061
  }
22062
+ if (elements.subagentsAutoClearButton) {
22063
+ elements.subagentsAutoClearButton.setAttribute("aria-pressed", subagentAutoClearEnabled ? "true" : "false");
22064
+ elements.subagentsAutoClearButton.classList.toggle("selected", subagentAutoClearEnabled);
22065
+ elements.subagentsAutoClearButton.title = subagentAutoClearEnabled
22066
+ ? "Auto-Clear is on: finished subagent runs are removed automatically"
22067
+ : "Auto-Clear is off: keep finished subagent runs until they are cleared manually";
22068
+ }
20404
22069
  if (elements.subagentsClearFinishedButton) {
20405
22070
  elements.subagentsClearFinishedButton.disabled = subagentsLoading || subagentsClearingFinished || finishedRuns.length === 0;
20406
22071
  elements.subagentsClearFinishedButton.textContent = subagentsClearingFinished ? "Clearing…" : "Clear finished";
@@ -20431,6 +22096,7 @@ function renderSubagents() {
20431
22096
 
20432
22097
  async function refreshSubagents() {
20433
22098
  if (subagentsLoading) return;
22099
+ let refreshed = false;
20434
22100
  let subagentViewsChanged = false;
20435
22101
  let materializedTerminalViews = false;
20436
22102
  subagentsLoading = true;
@@ -20442,6 +22108,7 @@ async function refreshSubagents() {
20442
22108
  subagentViewsChanged = syncSubagentTerminalViewsFromOverview();
20443
22109
  materializedTerminalViews = materializeRetainedSubagentTerminalViews();
20444
22110
  subagentsError = null;
22111
+ refreshed = true;
20445
22112
  } catch (error) {
20446
22113
  subagentsError = error;
20447
22114
  } finally {
@@ -20454,6 +22121,9 @@ async function refreshSubagents() {
20454
22121
  }
20455
22122
  if (subagentViewsChanged || materializedTerminalViews) renderTabs();
20456
22123
  }
22124
+ if (refreshed && subagentAutoClearEnabled && finishedSubagentRunSelections().length) {
22125
+ await clearFinishedSubagentRuns({ automatic: true });
22126
+ }
20457
22127
  }
20458
22128
 
20459
22129
  function scheduleRefreshSubagents(delay) {
@@ -21066,6 +22736,166 @@ function releaseDialogLineClass(plainLine, section) {
21066
22736
  return "";
21067
22737
  }
21068
22738
 
22739
+ // Enter inside a native input dialog must never fall through to the browser's
22740
+ // implicit `method="dialog"` submission. "ignore" leaves IME composition alone,
22741
+ // "suppress" only blocks the implicit close, and "submit" sends one response.
22742
+ function dialogInputEnterIntent(event) {
22743
+ if (!event || event.key !== "Enter") return "ignore";
22744
+ if (event.isComposing || event.keyCode === 229) return "ignore";
22745
+ if (event.repeat) return "suppress";
22746
+ if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return "suppress";
22747
+ return "submit";
22748
+ }
22749
+
22750
+ const QUESTIONNAIRE_TITLE_PATTERN = /^Question\s+([1-9]\d*)\s+of\s+([1-9]\d*):\s+\S.*$/;
22751
+ const QUESTIONNAIRE_ROW_PATTERN = /^(\d{2})\.\s(.*)$/;
22752
+ const QUESTIONNAIRE_STATE_PATTERN = /^(\[ \]|\[x\]|\[selected\])\s(.*)$/;
22753
+ const QUESTIONNAIRE_MAX_QUESTIONS = 20;
22754
+ const QUESTIONNAIRE_MAX_OPTIONS = 50;
22755
+
22756
+ function isQuestionnaireChangeOtherAction(value) {
22757
+ const prefix = "Change Other… (currently ";
22758
+ if (!value.startsWith(prefix) || !value.endsWith(")")) return false;
22759
+ const encoded = value.slice(prefix.length, -1);
22760
+ try {
22761
+ const other = JSON.parse(encoded);
22762
+ return typeof other === "string" && JSON.stringify(other) === encoded;
22763
+ } catch {
22764
+ return false;
22765
+ }
22766
+ }
22767
+
22768
+ // Bounded, presentation-only grammar for the native questionnaire runtime's
22769
+ // action strings. Anything outside this list stays a generic option.
22770
+ function questionnaireContinueCount(text) {
22771
+ const match = String(text || "").match(/^Continue with (0|[1-9]\d*) selection\(s\)$/);
22772
+ if (!match) return null;
22773
+ const count = Number(match[1]);
22774
+ return Number.isSafeInteger(count) && count <= QUESTIONNAIRE_MAX_OPTIONS + 1 ? count : null;
22775
+ }
22776
+
22777
+ function questionnaireActionKind(text) {
22778
+ const value = String(text || "");
22779
+ if (value === "Cancel questionnaire") return "cancel";
22780
+ if (value === "Ask Pi to clarify…") return "clarify";
22781
+ if (value === "Remove Other answer") return "remove-other";
22782
+ if (value === "Other… (enter a custom answer)" || value === "Add Other…") return "other";
22783
+ if (isQuestionnaireChangeOtherAction(value)) return "other";
22784
+ if (questionnaireContinueCount(value) !== null) return "continue";
22785
+ return null;
22786
+ }
22787
+
22788
+ // Parses one native option string for presentation only; the caller always
22789
+ // transports the untouched original string back to the extension.
22790
+ function parseQuestionnaireOption(text) {
22791
+ const value = String(text || "");
22792
+ const action = questionnaireActionKind(value);
22793
+ if (action) return { kind: "action", action, value };
22794
+
22795
+ const row = value.match(QUESTIONNAIRE_ROW_PATTERN);
22796
+ if (!row) return null;
22797
+ const number = row[1];
22798
+ const state = row[2].match(QUESTIONNAIRE_STATE_PATTERN);
22799
+ const marker = state ? (state[1] === "[ ]" ? "unselected" : "selected") : "none";
22800
+ const body = state ? state[2] : row[2];
22801
+ if (!body.trim()) return null;
22802
+
22803
+ const separator = body.indexOf(" — ");
22804
+ const label = separator === -1 ? body : body.slice(0, separator);
22805
+ const description = separator === -1 ? "" : body.slice(separator + 3);
22806
+ if (!label.trim()) return null;
22807
+ return { kind: "option", marker, number, label, description, value };
22808
+ }
22809
+
22810
+ function questionnaireActionSequenceMatches(mode, actionRows) {
22811
+ const values = actionRows.map((row) => row.value);
22812
+ if (mode === "single") {
22813
+ const expected = values[0] === "Other… (enter a custom answer)"
22814
+ ? ["Other… (enter a custom answer)", "Ask Pi to clarify…", "Cancel questionnaire"]
22815
+ : ["Ask Pi to clarify…", "Cancel questionnaire"];
22816
+ return values.length === expected.length && values.every((value, index) => value === expected[index]);
22817
+ }
22818
+
22819
+ let index = 0;
22820
+ if (values[index] === "Add Other…") {
22821
+ index += 1;
22822
+ } else if (isQuestionnaireChangeOtherAction(values[index] || "")) {
22823
+ index += 1;
22824
+ if (values[index] !== "Remove Other answer") return false;
22825
+ index += 1;
22826
+ }
22827
+ if (values[index] !== "Ask Pi to clarify…") return false;
22828
+ index += 1;
22829
+ if (questionnaireContinueCount(values[index]) === null) return false;
22830
+ index += 1;
22831
+ return values[index] === "Cancel questionnaire" && index === values.length - 1;
22832
+ }
22833
+
22834
+ // Detection requires the complete runtime title, contiguous numbered rows, one
22835
+ // consistent state-marker mode, and the exact ordered action tail. This keeps
22836
+ // lookalike extension selects on the generic renderer.
22837
+ function questionnaireSelectParts(prompt, options) {
22838
+ if (!Array.isArray(options) || options.length < 3 || options.length > QUESTIONNAIRE_MAX_OPTIONS + 5) return null;
22839
+ const title = stripAnsi(prompt?.title || "").trim();
22840
+ const titleMatch = title.match(QUESTIONNAIRE_TITLE_PATTERN);
22841
+ if (!titleMatch) return null;
22842
+ const current = Number(titleMatch[1]);
22843
+ const total = Number(titleMatch[2]);
22844
+ if (current > total || total > QUESTIONNAIRE_MAX_QUESTIONS) return null;
22845
+
22846
+ const rows = [];
22847
+ for (const option of options) {
22848
+ const parsed = parseQuestionnaireOption(String(option));
22849
+ if (!parsed) return null;
22850
+ rows.push(parsed);
22851
+ }
22852
+
22853
+ const firstAction = rows.findIndex((row) => row.kind === "action");
22854
+ if (firstAction < 1 || firstAction > QUESTIONNAIRE_MAX_OPTIONS) return null;
22855
+ const optionRows = rows.slice(0, firstAction);
22856
+ const actionRows = rows.slice(firstAction);
22857
+ if (actionRows.some((row) => row.kind !== "action")) return null;
22858
+ if (!optionRows.every((row, index) => row.kind === "option" && row.number === String(index + 1).padStart(2, "0"))) return null;
22859
+
22860
+ const single = optionRows.every((row) => row.marker === "none");
22861
+ const multi = optionRows.every((row) => row.marker !== "none");
22862
+ if (!single && !multi) return null;
22863
+ const mode = multi ? "multi" : "single";
22864
+ if (!questionnaireActionSequenceMatches(mode, actionRows)) return null;
22865
+ return { rows, mode };
22866
+ }
22867
+
22868
+ function renderQuestionnaireOptionButton(row, mode) {
22869
+ const classNames = ["questionnaire-option", `questionnaire-option-${mode}`];
22870
+ if (row.marker === "selected") classNames.push("is-selected");
22871
+ const button = make("button", classNames.join(" "));
22872
+ button.type = "button";
22873
+ // The visible text is split into semantic parts, so the accessible name keeps
22874
+ // the exact native string that click transport sends back.
22875
+ button.setAttribute("aria-label", row.value);
22876
+ if (row.marker !== "none") button.setAttribute("aria-pressed", String(row.marker === "selected"));
22877
+
22878
+ button.append(make("span", "questionnaire-option-number", row.number));
22879
+ if (row.marker !== "none") {
22880
+ const state = make("span", "questionnaire-option-state", row.marker === "selected" ? "✓" : "");
22881
+ state.setAttribute("aria-hidden", "true");
22882
+ button.append(state);
22883
+ }
22884
+ const text = make("span", "questionnaire-option-text");
22885
+ text.append(make("span", "questionnaire-option-label", row.label));
22886
+ if (row.description) text.append(make("span", "questionnaire-option-description", row.description));
22887
+ button.append(text);
22888
+ return button;
22889
+ }
22890
+
22891
+ function renderQuestionnaireActionButton(row) {
22892
+ const classNames = ["questionnaire-action", `questionnaire-action-${row.action}`];
22893
+ if (row.action === "continue") classNames.push("primary");
22894
+ const button = make("button", classNames.join(" "), row.value);
22895
+ button.type = "button";
22896
+ return button;
22897
+ }
22898
+
21069
22899
  function renderReleaseDialogMessage(parent, text) {
21070
22900
  parent.replaceChildren();
21071
22901
  let section = "";
@@ -22924,6 +24754,7 @@ function renderAppRunnerControls() {
22924
24754
  item.append(label, command);
22925
24755
  panel.append(item);
22926
24756
  }
24757
+ scheduleComposerActionSlotLayoutRestore();
22927
24758
  }
22928
24759
 
22929
24760
  function renderAppRunnerInfoDialog() {
@@ -23118,6 +24949,117 @@ function formatStatsPercent(value) {
23118
24949
  return `${statsNumber(value).toFixed(1)}%`;
23119
24950
  }
23120
24951
 
24952
+ function statsArray(value) {
24953
+ return Array.isArray(value) ? value : [];
24954
+ }
24955
+
24956
+ function statsNullableNumber(value) {
24957
+ const number = Number(value);
24958
+ return Number.isFinite(number) ? number : null;
24959
+ }
24960
+
24961
+ function formatStatsNullablePercent(value) {
24962
+ const number = statsNullableNumber(value);
24963
+ return number === null ? "n/a" : `${number.toFixed(1)}%`;
24964
+ }
24965
+
24966
+ function formatStatsNullableCost(value) {
24967
+ const number = statsNullableNumber(value);
24968
+ return number === null ? "n/a" : formatStatsCost(number);
24969
+ }
24970
+
24971
+ function formatStatsNullableTokens(value) {
24972
+ const number = statsNullableNumber(value);
24973
+ return number === null ? "n/a" : `${formatStatsTokens(number)} tok`;
24974
+ }
24975
+
24976
+ function formatStatsSignedCost(value) {
24977
+ const number = statsNullableNumber(value);
24978
+ if (number === null) return "n/a";
24979
+ const sign = number > 0 ? "+" : number < 0 ? "−" : "";
24980
+ return `${sign}${formatStatsCost(Math.abs(number))}`;
24981
+ }
24982
+
24983
+ function statsSummaryHas(summary, key) {
24984
+ return !!summary && typeof summary === "object" && key in summary;
24985
+ }
24986
+
24987
+ function statsCostShareOf(cost, totalCost) {
24988
+ const total = statsNumber(totalCost);
24989
+ return total > 0 ? (statsNumber(cost) / total) * 100 : null;
24990
+ }
24991
+
24992
+ function statsCachedInputShare(summary, totals) {
24993
+ if (statsSummaryHas(summary, "cachedInputShare")) return statsNullableNumber(summary.cachedInputShare);
24994
+ // Legacy v1 payload fallback: compute the cached-input share client-side.
24995
+ const denominator = statsNumber(totals?.input) + statsNumber(totals?.cacheRead) + statsNumber(totals?.cacheWrite);
24996
+ return denominator > 0 ? (statsNumber(totals?.cacheRead) / denominator) * 100 : null;
24997
+ }
24998
+
24999
+ function statsPromptSideTokens(summary, totals) {
25000
+ if (statsSummaryHas(summary, "promptSideTokens")) return statsNumber(summary.promptSideTokens);
25001
+ return statsNumber(totals?.input) + statsNumber(totals?.cacheRead) + statsNumber(totals?.cacheWrite);
25002
+ }
25003
+
25004
+ function statsEffectiveCostRate(summary, totals) {
25005
+ if (statsSummaryHas(summary, "effectiveCostPerMillionTokens")) return statsNullableNumber(summary.effectiveCostPerMillionTokens);
25006
+ // Legacy v1 payload fallback: blended cost per million total tokens.
25007
+ return statsNumber(totals?.total) > 0 ? (statsNumber(totals?.cost) / statsNumber(totals.total)) * 1_000_000 : null;
25008
+ }
25009
+
25010
+ function statsScopedSessionCount(payload) {
25011
+ const scoped = statsNullableNumber(payload?.scopedSessionCount);
25012
+ if (scoped !== null) return scoped;
25013
+ // Legacy v1 payload fallback: only the session-file count is available.
25014
+ return statsNullableNumber(payload?.sessionCount);
25015
+ }
25016
+
25017
+ function statsAverageCostPerSession(summary, payload) {
25018
+ if (statsSummaryHas(summary, "averageCostPerSession")) return statsNullableNumber(summary.averageCostPerSession);
25019
+ const sessions = statsScopedSessionCount(payload);
25020
+ return sessions && sessions > 0 ? statsNumber(payload?.totals?.cost) / sessions : null;
25021
+ }
25022
+
25023
+ function statsAverageTokensPerSession(summary, payload) {
25024
+ if (statsSummaryHas(summary, "averageTokensPerSession")) return statsNullableNumber(summary.averageTokensPerSession);
25025
+ const sessions = statsScopedSessionCount(payload);
25026
+ return sessions && sessions > 0 ? statsNumber(payload?.totals?.total) / sessions : null;
25027
+ }
25028
+
25029
+ function statsSpendComparison(summary) {
25030
+ const comparison = statsSummaryHas(summary, "spendComparison") ? summary.spendComparison : null;
25031
+ if (!comparison || typeof comparison !== "object") return null;
25032
+ const windowDays = statsNumber(comparison.windowDays);
25033
+ if (windowDays <= 0) return null;
25034
+ return {
25035
+ windowDays,
25036
+ recentStartDay: typeof comparison.recentStartDay === "string" ? comparison.recentStartDay : "",
25037
+ recentEndDay: typeof comparison.recentEndDay === "string" ? comparison.recentEndDay : "",
25038
+ recentCost: statsNumber(comparison.recentCost),
25039
+ priorCost: statsNumber(comparison.priorCost),
25040
+ changeCost: statsNullableNumber(comparison.changeCost),
25041
+ changePercent: statsNullableNumber(comparison.changePercent),
25042
+ };
25043
+ }
25044
+
25045
+ function statsModelDriverEntries(payload) {
25046
+ const totalCost = statsNumber(payload?.totals?.cost);
25047
+ return statsArray(payload?.models).map((model) => ({
25048
+ name: model?.model || "unknown",
25049
+ cost: statsNumber(model?.cost),
25050
+ share: statsCostShareOf(model?.cost, totalCost),
25051
+ }));
25052
+ }
25053
+
25054
+ function statsSessionDriverEntries(payload) {
25055
+ const totalCost = statsNumber(payload?.totals?.cost);
25056
+ return statsArray(payload?.expensiveSessions).map((session) => ({
25057
+ name: session?.displayName || session?.sessionId || "unknown",
25058
+ cost: statsNumber(session?.cost),
25059
+ share: statsCostShareOf(session?.cost, totalCost),
25060
+ }));
25061
+ }
25062
+
23121
25063
  function parseStatsWebuiPayloadRaw(raw) {
23122
25064
  if (!raw) return null;
23123
25065
  try {
@@ -23192,13 +25134,18 @@ function statsLineBlock(lines = []) {
23192
25134
  return pre;
23193
25135
  }
23194
25136
 
23195
- function renderStatsTable(headers, rows, emptyText = "No data.") {
25137
+ function renderStatsTable(headers, rows, emptyText = "No data.", caption = "") {
23196
25138
  if (!rows.length) return make("p", "stats-overlay-empty muted", emptyText);
23197
25139
  const wrapper = make("div", "stats-overlay-table-wrap");
23198
25140
  const table = make("table", "stats-overlay-table");
25141
+ if (caption) table.append(make("caption", "stats-overlay-table-caption", caption));
23199
25142
  const thead = make("thead");
23200
25143
  const headRow = make("tr");
23201
- for (const header of headers) headRow.append(make("th", undefined, header));
25144
+ for (const header of headers) {
25145
+ const th = make("th", undefined, header);
25146
+ th.scope = "col";
25147
+ headRow.append(th);
25148
+ }
23202
25149
  thead.append(headRow);
23203
25150
  const tbody = make("tbody");
23204
25151
  for (const row of rows) {
@@ -23211,18 +25158,57 @@ function renderStatsTable(headers, rows, emptyText = "No data.") {
23211
25158
  return wrapper;
23212
25159
  }
23213
25160
 
25161
+ const STATS_CHART_POINT_LIMIT = 31;
25162
+
25163
+ function statsChartWindow(rows = []) {
25164
+ const list = statsArray(rows);
25165
+ const capped = list.length > STATS_CHART_POINT_LIMIT ? list.slice(-STATS_CHART_POINT_LIMIT) : list;
25166
+ return { capped, total: list.length, truncated: list.length > capped.length };
25167
+ }
25168
+
25169
+ function statsChartWindowNote({ total, truncated }, noun = "days") {
25170
+ if (!truncated) return null;
25171
+ return make("p", "stats-overlay-chart-note muted", `Showing the latest ${STATS_CHART_POINT_LIMIT} of ${total} ${noun}; the Daily tab lists every recorded day.`);
25172
+ }
25173
+
25174
+ function statsLegendItem(seriesClass, label) {
25175
+ const item = make("span", "stats-overlay-legend-item");
25176
+ item.append(make("span", `stats-overlay-legend-swatch ${seriesClass}`), label);
25177
+ return item;
25178
+ }
25179
+
23214
25180
  function renderStatsBarRows(daily = []) {
23215
- const rows = daily.filter((row) => statsNumber(row.total) > 0 || statsNumber(row.cost) > 0);
25181
+ const rows = statsArray(daily).filter((row) => statsNumber(row?.total) > 0 || statsNumber(row?.cost) > 0);
23216
25182
  if (!rows.length) return make("p", "stats-overlay-empty muted", "No non-zero usage in this range.");
23217
- const maxTokens = Math.max(1, ...rows.map((row) => statsNumber(row.total)));
25183
+ const windowed = statsChartWindow(rows);
25184
+ const capped = windowed.capped;
25185
+ const maxTokens = Math.max(1, ...capped.map((row) => statsNumber(row.total)));
25186
+ const maxCost = Math.max(0.0001, ...capped.map((row) => statsNumber(row.cost)));
25187
+ const peakTokens = capped.reduce((best, row) => (statsNumber(row.total) > statsNumber(best?.total) ? row : best), capped[0]);
25188
+ const peakCost = capped.reduce((best, row) => (statsNumber(row.cost) > statsNumber(best?.cost) ? row : best), capped[0]);
25189
+ const wrapper = make("div", "stats-overlay-bars-panel");
25190
+ const legend = make("p", "stats-overlay-legend");
25191
+ legend.append(
25192
+ statsLegendItem("tokens", "Tokens"),
25193
+ statsLegendItem("cost", "Cost"),
25194
+ make("span", "stats-overlay-legend-note muted", "token and cost bars use independent scales"),
25195
+ );
23218
25196
  const list = make("div", "stats-overlay-bars");
23219
- for (const row of rows) {
23220
- const tokenRatio = Math.max(0.015, statsNumber(row.total) / maxTokens);
25197
+ for (const row of capped) {
25198
+ const tokenRatio = Math.min(100, Math.max(statsNumber(row.total) > 0 ? 1.5 : 0, (statsNumber(row.total) / maxTokens) * 100));
25199
+ const costRatio = Math.min(100, Math.max(statsNumber(row.cost) > 0 ? 1.5 : 0, (statsNumber(row.cost) / maxCost) * 100));
23221
25200
  const item = make("div", "stats-overlay-bar-row");
23222
25201
  const bar = make("span", "stats-overlay-bar");
23223
- const fill = make("span", "stats-overlay-bar-fill");
23224
- fill.style.width = `${Math.min(100, tokenRatio * 100)}%`;
23225
- bar.append(fill);
25202
+ bar.setAttribute("aria-hidden", "true");
25203
+ const tokenLane = make("span", "stats-overlay-bar-lane");
25204
+ const tokenFill = make("span", "stats-overlay-bar-fill");
25205
+ tokenFill.style.width = `${tokenRatio}%`;
25206
+ tokenLane.append(tokenFill);
25207
+ const costLane = make("span", "stats-overlay-bar-lane");
25208
+ const costFill = make("span", "stats-overlay-bar-fill cost");
25209
+ costFill.style.width = `${costRatio}%`;
25210
+ costLane.append(costFill);
25211
+ bar.append(tokenLane, costLane);
23226
25212
  item.append(
23227
25213
  make("span", "stats-overlay-bar-day", row.day || "—"),
23228
25214
  bar,
@@ -23231,33 +25217,144 @@ function renderStatsBarRows(daily = []) {
23231
25217
  );
23232
25218
  list.append(item);
23233
25219
  }
25220
+ wrapper.append(
25221
+ legend,
25222
+ list,
25223
+ make("p", "stats-overlay-chart-caption muted", `${capped[0]?.day || "—"} → ${capped.at(-1)?.day || "—"} · peak ${formatStatsTokens(peakTokens?.total)} tok on ${peakTokens?.day || "—"} · peak spend ${formatStatsCost(peakCost?.cost)} on ${peakCost?.day || "—"}`),
25224
+ );
25225
+ const note = statsChartWindowNote(windowed, "active days");
25226
+ if (note) wrapper.append(note);
25227
+ return wrapper;
25228
+ }
25229
+
25230
+ function renderStatsSpendChart(daily = []) {
25231
+ const rows = statsArray(daily).map((row) => ({ day: String(row?.day || "—"), cost: Math.max(0, statsNumber(row?.cost)) }));
25232
+ if (!rows.length) return make("p", "stats-overlay-empty muted", "No daily usage in this range.");
25233
+ const windowed = statsChartWindow(rows);
25234
+ const capped = windowed.capped;
25235
+ const maxCost = Math.max(0, ...capped.map((row) => row.cost));
25236
+ const total = capped.reduce((acc, row) => acc + row.cost, 0);
25237
+ if (total <= 0) return make("p", "stats-overlay-empty muted", "No spend recorded in this range.");
25238
+ const peak = capped.reduce((best, row) => (row.cost > (best?.cost ?? -1) ? row : best), null);
25239
+ const wrapper = make("div", "stats-overlay-spend");
25240
+ const chart = make("div", "stats-overlay-spend-chart");
25241
+ chart.setAttribute("role", "img");
25242
+ chart.setAttribute("aria-label", `Daily spend bar chart from ${capped[0].day} to ${capped.at(-1).day}. Total ${formatStatsCost(total)}; peak ${formatStatsCost(peak?.cost)} on ${peak?.day}.`);
25243
+ for (const row of capped) {
25244
+ const col = make("span", "stats-overlay-spend-col");
25245
+ const bar = make("span", "stats-overlay-spend-bar");
25246
+ const height = maxCost > 0 ? Math.min(100, Math.max(row.cost > 0 ? 3 : 0, (row.cost / maxCost) * 100)) : 0;
25247
+ bar.style.height = `${height}%`;
25248
+ col.title = `${row.day}: ${formatStatsCost(row.cost)}`;
25249
+ col.append(bar);
25250
+ chart.append(col);
25251
+ }
25252
+ const caption = make("p", "stats-overlay-chart-caption muted", `Daily spend ${capped[0].day} → ${capped.at(-1).day} · total ${formatStatsCost(total)} · peak ${formatStatsCost(peak?.cost ?? 0)} on ${peak?.day ?? "—"}${windowed.truncated ? ` · latest ${capped.length} of ${windowed.total} days` : ""}`);
25253
+ wrapper.append(chart, caption);
25254
+ return wrapper;
25255
+ }
25256
+
25257
+ function renderStatsComposition(totals = {}) {
25258
+ const segments = [
25259
+ { key: "seg-input", label: "Input", value: Math.max(0, statsNumber(totals.input)) },
25260
+ { key: "seg-output", label: "Output", value: Math.max(0, statsNumber(totals.output)) },
25261
+ { key: "seg-cache-read", label: "Cache read", value: Math.max(0, statsNumber(totals.cacheRead)) },
25262
+ { key: "seg-cache-write", label: "Cache write", value: Math.max(0, statsNumber(totals.cacheWrite)) },
25263
+ ];
25264
+ const total = segments.reduce((acc, segment) => acc + segment.value, 0);
25265
+ if (total <= 0) return make("p", "stats-overlay-empty muted", "No token usage in this range.");
25266
+ const shareText = (value) => `${((value / total) * 100).toFixed(1)}%`;
25267
+ const wrapper = make("div", "stats-overlay-composition");
25268
+ const track = make("div", "stats-overlay-composition-track");
25269
+ track.setAttribute("role", "img");
25270
+ track.setAttribute("aria-label", `Token composition: ${segments.map((segment) => `${segment.label} ${shareText(segment.value)}`).join(", ")}.`);
25271
+ for (const segment of segments) {
25272
+ if (segment.value <= 0) continue;
25273
+ const node = make("span", `stats-overlay-composition-segment ${segment.key}`);
25274
+ node.style.width = `${Math.min(100, Math.max(0, (segment.value / total) * 100))}%`;
25275
+ node.title = `${segment.label}: ${formatStatsTokens(segment.value)} tok (${shareText(segment.value)})`;
25276
+ track.append(node);
25277
+ }
25278
+ const legend = make("ul", "stats-overlay-legend stats-overlay-composition-legend");
25279
+ for (const segment of segments) {
25280
+ const item = make("li", "stats-overlay-legend-item");
25281
+ item.append(make("span", `stats-overlay-legend-swatch ${segment.key}`), `${segment.label} ${formatStatsTokens(segment.value)} tok · ${shareText(segment.value)}`);
25282
+ legend.append(item);
25283
+ }
25284
+ wrapper.append(track, legend);
25285
+ return wrapper;
25286
+ }
25287
+
25288
+ function renderStatsDriverList(entries = [], emptyText = "No cost drivers in this range.") {
25289
+ const rows = statsArray(entries)
25290
+ .map((entry) => ({ name: entry?.name || "unknown", cost: Math.max(0, statsNumber(entry?.cost)), share: statsNullableNumber(entry?.share) }))
25291
+ .filter((entry) => entry.cost > 0)
25292
+ .slice(0, 8);
25293
+ if (!rows.length) return make("p", "stats-overlay-empty muted", emptyText);
25294
+ const maxCost = Math.max(...rows.map((entry) => entry.cost));
25295
+ const list = make("div", "stats-overlay-driver-list");
25296
+ for (const [index, entry] of rows.entries()) {
25297
+ const ratio = maxCost > 0 ? Math.min(100, Math.max(2, (entry.cost / maxCost) * 100)) : 0;
25298
+ const row = make("div", "stats-overlay-driver-row");
25299
+ const bar = make("span", "stats-overlay-driver-bar");
25300
+ bar.setAttribute("aria-hidden", "true");
25301
+ const fill = make("span", "stats-overlay-driver-bar-fill");
25302
+ fill.style.width = `${ratio}%`;
25303
+ bar.append(fill);
25304
+ row.append(
25305
+ make("span", "stats-overlay-driver-rank", String(index + 1)),
25306
+ make("span", "stats-overlay-driver-name", entry.name),
25307
+ bar,
25308
+ make("span", "stats-overlay-driver-value", `${formatStatsCost(entry.cost)} · ${formatStatsNullablePercent(entry.share)}`),
25309
+ );
25310
+ list.append(row);
25311
+ }
23234
25312
  return list;
23235
25313
  }
23236
25314
 
25315
+ function renderStatsDriverSection(title, entries, emptyText) {
25316
+ const section = make("section", "stats-overlay-driver-section");
25317
+ section.append(make("h4", undefined, title), renderStatsDriverList(entries, emptyText));
25318
+ return section;
25319
+ }
25320
+
25321
+ function renderStatsTopDrivers(payload) {
25322
+ const grid = make("div", "stats-overlay-drivers");
25323
+ grid.append(
25324
+ renderStatsDriverSection("Models by spend", statsModelDriverEntries(payload), "No model spend in this range."),
25325
+ renderStatsDriverSection("Sessions by spend", statsSessionDriverEntries(payload), "No session spend in this range."),
25326
+ );
25327
+ return grid;
25328
+ }
25329
+
23237
25330
  function renderStatsOverview(payload) {
23238
25331
  const node = make("div", "stats-overlay-pane stats-overlay-overview");
23239
25332
  const totals = payload?.totals || {};
23240
25333
  const summary = payload?.summary || {};
23241
25334
  const highest = summary.highestDay;
25335
+ const scopedSessions = statsNullableNumber(payload?.scopedSessionCount);
25336
+ const sessionDetail = scopedSessions !== null ? `${scopedSessions} sessions in range` : `${payload?.sessionCount ?? 0} session files`;
25337
+ const cachedShare = statsCachedInputShare(summary, totals);
23242
25338
  const cards = make("div", "stats-overlay-cards");
23243
25339
  cards.append(
23244
25340
  statsMetricCard("Total tokens", formatStatsTokens(totals.total), `↑${formatStatsTokens(totals.input)} ↓${formatStatsTokens(totals.output)}`, "tone-blue"),
23245
25341
  statsMetricCard("Cost", formatStatsCost(totals.cost), `projected 30d ${formatStatsCost(summary.projected30DayCost)}`, "tone-green"),
23246
- statsMetricCard("Messages", String(statsNumber(totals.messages)), `${payload?.sessionCount ?? 0} sessions`, "tone-mauve"),
25342
+ statsMetricCard("Effective $/1M", formatStatsNullableCost(statsEffectiveCostRate(summary, totals)), "blended rate, not provider list pricing", "tone-sky"),
25343
+ statsMetricCard("Messages", String(statsNumber(totals.messages)), sessionDetail, "tone-mauve"),
23247
25344
  statsMetricCard("PI initial prompt", `~${formatStatsTokens(payload?.promptEstimate?.total)} tok`, `${statsPromptEstimateSourceLabel(payload?.promptEstimate)} · ${payload?.promptEstimate?.confidence || "estimate"}`, "tone-yellow"),
23248
- statsMetricCard("Cache hit", formatStatsPercent(summary.cacheHitRate), `reads ${formatStatsTokens(totals.cacheRead)} · writes ${formatStatsTokens(totals.cacheWrite)}`, "tone-teal"),
25345
+ statsMetricCard("Cached-input share", formatStatsNullablePercent(cachedShare), `reads ${formatStatsTokens(totals.cacheRead)} · writes ${formatStatsTokens(totals.cacheWrite)} of ${formatStatsTokens(statsPromptSideTokens(summary, totals))} prompt-side tok`, "tone-teal"),
23249
25346
  statsMetricCard("Active days", `${payload?.activeDayCount ?? 0}/${payload?.dayCount ?? 0}`, highest ? `peak ${highest.day} · ${formatStatsCost(highest.cost)}` : "no peak yet", "tone-pink"),
23250
25347
  );
23251
- node.append(cards, make("h3", undefined, "Daily usage"), renderStatsBarRows(payload?.daily || []));
25348
+ node.append(cards, make("h3", undefined, "Daily usage"), renderStatsBarRows(payload?.daily));
23252
25349
  return node;
23253
25350
  }
23254
25351
 
23255
25352
  function renderStatsDaily(payload) {
23256
25353
  const node = make("div", "stats-overlay-pane");
23257
- node.append(make("h3", undefined, "Daily token and cost trend"), renderStatsBarRows(payload?.daily || []));
25354
+ node.append(make("h3", undefined, "Daily token and cost trend"), renderStatsBarRows(payload?.daily));
23258
25355
  node.append(renderStatsTable(
23259
25356
  ["Day", "Tokens", "Cost", "Input", "Output", "Cache R/W", "Msgs"],
23260
- (payload?.daily || []).map((row) => [
25357
+ statsArray(payload?.daily).map((row) => [
23261
25358
  row.day || "—",
23262
25359
  formatStatsTokens(row.total),
23263
25360
  formatStatsCost(row.cost),
@@ -23266,14 +25363,21 @@ function renderStatsDaily(payload) {
23266
25363
  `${formatStatsTokens(row.cacheRead)} / ${formatStatsTokens(row.cacheWrite)}`,
23267
25364
  String(statsNumber(row.messages)),
23268
25365
  ]),
25366
+ "No data.",
25367
+ "Daily tokens and cost by UTC day",
23269
25368
  ));
23270
25369
  return node;
23271
25370
  }
23272
25371
 
23273
25372
  function renderStatsModels(payload) {
23274
- return renderStatsTable(
25373
+ const node = make("div", "stats-overlay-pane");
25374
+ node.append(
25375
+ make("h3", undefined, "Model spend ranks"),
25376
+ renderStatsDriverList(statsModelDriverEntries(payload), "No model spend in this range."),
25377
+ );
25378
+ node.append(renderStatsTable(
23275
25379
  ["Model", "Tokens", "Token %", "Cost", "Spend %", "$/1M", "Avg out", "Msgs"],
23276
- (payload?.models || []).map((model) => [
25380
+ statsArray(payload?.models).map((model) => [
23277
25381
  model.model || "unknown",
23278
25382
  formatStatsTokens(model.tokens),
23279
25383
  formatStatsPercent(model.percent),
@@ -23284,13 +25388,20 @@ function renderStatsModels(payload) {
23284
25388
  String(statsNumber(model.messages)),
23285
25389
  ]),
23286
25390
  "No model usage in this range.",
23287
- );
25391
+ "Model token and cost comparison",
25392
+ ));
25393
+ return node;
23288
25394
  }
23289
25395
 
23290
25396
  function renderStatsSessions(payload) {
23291
- return renderStatsTable(
25397
+ const node = make("div", "stats-overlay-pane");
25398
+ node.append(
25399
+ make("h3", undefined, "Session spend ranks"),
25400
+ renderStatsDriverList(statsSessionDriverEntries(payload), "No session spend in this range."),
25401
+ );
25402
+ node.append(renderStatsTable(
23292
25403
  ["Day", "Session", "Cost", "Tokens", "Model"],
23293
- (payload?.expensiveSessions || []).map((session) => [
25404
+ statsArray(payload?.expensiveSessions).map((session) => [
23294
25405
  session.day || "—",
23295
25406
  session.displayName || session.sessionId || "unknown",
23296
25407
  formatStatsCost(session.cost),
@@ -23298,21 +25409,43 @@ function renderStatsSessions(payload) {
23298
25409
  session.model || "unknown",
23299
25410
  ]),
23300
25411
  "No session usage in this range.",
23301
- );
25412
+ "Most expensive sessions in the selected range",
25413
+ ));
25414
+ return node;
23302
25415
  }
23303
25416
 
23304
25417
  function renderStatsCostCache(payload) {
23305
25418
  const node = make("div", "stats-overlay-pane");
23306
25419
  const totals = payload?.totals || {};
23307
25420
  const summary = payload?.summary || {};
25421
+ const comparison = statsSpendComparison(summary);
25422
+ const scopedSessions = statsNullableNumber(payload?.scopedSessionCount);
25423
+ const sessionDetail = scopedSessions !== null ? `per session in range (${scopedSessions})` : "per session file (legacy count)";
23308
25424
  const cards = make("div", "stats-overlay-cards compact");
23309
25425
  cards.append(
23310
25426
  statsMetricCard("Avg/day", formatStatsCost(summary.calendarAvgCost), "calendar average", "tone-green"),
23311
25427
  statsMetricCard("Active avg", formatStatsCost(summary.activeAvgCost), "per active day", "tone-teal"),
23312
- statsMetricCard("Non-cache", formatStatsTokens(summary.nonCacheTokens), `${formatStatsTokens(totals.total)} total`, "tone-blue"),
23313
- statsMetricCard("Cache hit", formatStatsPercent(summary.cacheHitRate), `${formatStatsTokens(totals.cacheRead)} read tokens`, "tone-yellow"),
25428
+ statsMetricCard("Effective $/1M", formatStatsNullableCost(statsEffectiveCostRate(summary, totals)), "blended rate, not provider list pricing", "tone-blue"),
25429
+ statsMetricCard("Cached-input share", formatStatsNullablePercent(statsCachedInputShare(summary, totals)), `reads ${formatStatsTokens(totals.cacheRead)} of ${formatStatsTokens(statsPromptSideTokens(summary, totals))} prompt-side tok`, "tone-yellow"),
25430
+ statsMetricCard("Avg cost/session", formatStatsNullableCost(statsAverageCostPerSession(summary, payload)), `${formatStatsNullableTokens(statsAverageTokensPerSession(summary, payload))} · ${sessionDetail}`, "tone-mauve"),
25431
+ statsMetricCard(
25432
+ "Recent spend",
25433
+ comparison ? formatStatsCost(comparison.recentCost) : "n/a",
25434
+ comparison
25435
+ ? `${comparison.recentStartDay} → ${comparison.recentEndDay} (${comparison.windowDays}d) vs prior ${comparison.windowDays}d ${formatStatsCost(comparison.priorCost)} · ${formatStatsSignedCost(comparison.changeCost)} (${formatStatsNullablePercent(comparison.changePercent)})`
25436
+ : "requires the latest stats extension",
25437
+ "tone-pink",
25438
+ ),
25439
+ );
25440
+ node.append(
25441
+ cards,
25442
+ make("h3", undefined, "Daily spend"),
25443
+ renderStatsSpendChart(payload?.daily),
25444
+ make("h3", undefined, "Token & cache composition"),
25445
+ renderStatsComposition(totals),
25446
+ make("h3", undefined, "Top cost drivers"),
25447
+ renderStatsTopDrivers(payload),
23314
25448
  );
23315
- node.append(cards, make("h3", undefined, "Cost trend"), statsLineBlock(payload?.lines?.costTrend), make("h3", undefined, "Cache efficiency"), statsLineBlock(payload?.lines?.cache));
23316
25449
  return node;
23317
25450
  }
23318
25451
 
@@ -23343,24 +25476,429 @@ function renderStatsCalibrationPanel(payload) {
23343
25476
  return panel;
23344
25477
  }
23345
25478
 
23346
- function renderStatsPrompt(payload) {
23347
- const node = make("div", "stats-overlay-pane");
23348
- const cards = make("div", "stats-overlay-cards compact");
25479
+ const STATS_PROMPT_SOURCE_LIMIT = 24;
25480
+ const STATS_PROMPT_TOOL_LIMIT = 12;
25481
+ const STATS_PROMPT_TOOL_ENTRY_LIMIT = 24;
25482
+ const STATS_PROMPT_SKILL_LIMIT = 10;
25483
+ const STATS_PROMPT_CONTEXT_FILE_LIMIT = 8;
25484
+ const STATS_PROMPT_SOURCE_KINDS = new Set([
25485
+ "system-prompt", "tools-prompt", "custom-prompt", "append-system", "context-file", "skills",
25486
+ "tool-schemas", "framing", "user-messages", "assistant-messages", "assistant-tool-calls",
25487
+ "tool-results", "other",
25488
+ ]);
25489
+
25490
+ function statsPromptRecord(value) {
25491
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
25492
+ }
25493
+
25494
+ function statsPromptText(value, maxLength = 240) {
25495
+ if (typeof value !== "string" || !value.trim()) return null;
25496
+ return value.trim().slice(0, maxLength);
25497
+ }
25498
+
25499
+ function statsPromptNullableText(value, maxLength = 240) {
25500
+ if (value === null) return null;
25501
+ return typeof value === "string" ? value.trim().slice(0, maxLength) : undefined;
25502
+ }
25503
+
25504
+ function statsPromptMetric(value, { integer = false, signed = false } = {}) {
25505
+ if (typeof value !== "number" || !Number.isFinite(value) || (!signed && value < 0)) return null;
25506
+ if (integer && !Number.isInteger(value)) return null;
25507
+ return value;
25508
+ }
25509
+
25510
+ function statsPromptNullableMetric(value, options = {}) {
25511
+ if (value === null) return null;
25512
+ const metric = statsPromptMetric(value, options);
25513
+ return metric === null ? undefined : metric;
25514
+ }
25515
+
25516
+ function statsPromptPercent(value) {
25517
+ const percent = statsPromptNullableMetric(value);
25518
+ return percent === undefined || (percent !== null && percent > 100) ? undefined : percent;
25519
+ }
25520
+
25521
+ function formatStatsPromptNullablePercent(value) {
25522
+ return value === null ? "n/a" : `${value.toFixed(1)}%`;
25523
+ }
25524
+
25525
+ function formatStatsPromptNullableTokens(value) {
25526
+ return value === null ? "n/a" : `${formatStatsTokens(value)} tok`;
25527
+ }
25528
+
25529
+ function statsPromptList(value, limit, normalize) {
25530
+ if (!Array.isArray(value)) return null;
25531
+ const result = [];
25532
+ for (const entry of value.slice(0, limit)) {
25533
+ const normalized = normalize(entry);
25534
+ if (!normalized) return null;
25535
+ result.push(normalized);
25536
+ }
25537
+ return result;
25538
+ }
25539
+
25540
+ function normalizeStatsPromptSource(value, tokenKey, { charsNullable = false } = {}) {
25541
+ const source = statsPromptRecord(value);
25542
+ if (!source) return null;
25543
+ const id = statsPromptText(source.id, 120);
25544
+ const kind = statsPromptText(source.kind, 80);
25545
+ const label = statsPromptText(source.label, 240);
25546
+ const chars = charsNullable ? statsPromptNullableMetric(source.chars) : statsPromptMetric(source.chars);
25547
+ const tokens = statsPromptMetric(source[tokenKey]);
25548
+ const percent = statsPromptPercent(source.percent);
25549
+ if (!id || !kind || !STATS_PROMPT_SOURCE_KINDS.has(kind) || !label || chars === undefined || tokens === null || percent === undefined) return null;
25550
+ return { id, kind, label, chars, [tokenKey]: tokens, percent };
25551
+ }
25552
+
25553
+ function normalizeStatsPromptInitial(value) {
25554
+ const section = statsPromptRecord(value);
25555
+ if (!section) return null;
25556
+ const totalTokens = statsPromptMetric(section.totalTokens);
25557
+ const lowTokens = statsPromptMetric(section.lowTokens);
25558
+ const highTokens = statsPromptMetric(section.highTokens);
25559
+ const confidence = statsPromptText(section.confidence, 80);
25560
+ const source = statsPromptText(section.source, 80);
25561
+ const warning = statsPromptNullableText(section.warning, 360);
25562
+ const estimateMethod = statsPromptText(section.estimateMethod, 160);
25563
+ const components = statsPromptList(section.components, STATS_PROMPT_SOURCE_LIMIT, (entry) => {
25564
+ const component = normalizeStatsPromptSource(entry, "tokens", { charsNullable: true });
25565
+ if (!component) return null;
25566
+ const uncalibratedTokens = statsPromptMetric(entry.uncalibratedTokens);
25567
+ return uncalibratedTokens === null ? null : { ...component, uncalibratedTokens };
25568
+ });
25569
+ if (totalTokens === null || lowTokens === null || highTokens === null || !confidence || !source || warning === undefined || !estimateMethod || !components) return null;
25570
+ const componentTotal = components.reduce((sum, component) => sum + component.tokens, 0);
25571
+ if (componentTotal !== totalTokens) return null;
25572
+ return { totalTokens, lowTokens, highTokens, confidence, source, warning, estimateMethod, components };
25573
+ }
25574
+
25575
+ function normalizeStatsPromptInventory(value, limit, itemKey, normalizeItem) {
25576
+ const inventory = statsPromptRecord(value);
25577
+ if (!inventory) return null;
25578
+ const totalCount = statsPromptMetric(inventory.totalCount, { integer: true });
25579
+ const omittedCount = statsPromptMetric(inventory.omittedCount, { integer: true });
25580
+ const items = statsPromptList(inventory[itemKey], limit, normalizeItem);
25581
+ if (totalCount === null || omittedCount === null || !items) return null;
25582
+ return { totalCount, omittedCount, items };
25583
+ }
25584
+
25585
+ function normalizeStatsPromptSnapshot(value) {
25586
+ const section = statsPromptRecord(value);
25587
+ const estimates = statsPromptRecord(section?.estimateComponents);
25588
+ const calibration = statsPromptRecord(estimates?.calibration);
25589
+ const metadata = statsPromptRecord(section?.metadata);
25590
+ if (!section || !estimates || !calibration || !metadata) return null;
25591
+
25592
+ const source = statsPromptText(section.source, 80);
25593
+ const settled = typeof section.settled === "boolean" ? section.settled : null;
25594
+ const attempts = statsPromptMetric(section.attempts, { integer: true });
25595
+ const warning = statsPromptNullableText(section.warning, 360);
25596
+ const systemPromptChars = statsPromptMetric(section.systemPromptChars, { integer: true });
25597
+ const promptText = statsPromptMetric(estimates.promptText);
25598
+ const toolSchemas = statsPromptMetric(estimates.toolSchemas);
25599
+ const framing = statsPromptMetric(estimates.framing);
25600
+ const multiplier = statsPromptMetric(calibration.multiplier);
25601
+ const samples = statsPromptMetric(calibration.samples, { integer: true });
25602
+ const currentDate = statsPromptNullableText(metadata.currentDate, 120);
25603
+ const cwdDisplay = statsPromptNullableText(metadata.cwdDisplay, 120);
25604
+ const extraGuidelineCount = statsPromptMetric(metadata.extraGuidelineCount, { integer: true });
25605
+
25606
+ const tools = normalizeStatsPromptInventory(section.tools, STATS_PROMPT_TOOL_LIMIT, "items", (value) => {
25607
+ const item = statsPromptRecord(value);
25608
+ if (!item) return null;
25609
+ const name = statsPromptText(item.name, 120);
25610
+ const description = statsPromptNullableText(item.description, 360);
25611
+ const parameterSummary = statsPromptText(item.parameterSummary, 120);
25612
+ const estimatedTokens = statsPromptMetric(item.estimatedTokens);
25613
+ return !name || description === undefined || !parameterSummary || estimatedTokens === null
25614
+ ? null
25615
+ : { name, description, parameterSummary, estimatedTokens };
25616
+ });
25617
+ const toolPromptEntries = normalizeStatsPromptInventory(section.toolPromptEntries, STATS_PROMPT_TOOL_ENTRY_LIMIT, "names", (name) => {
25618
+ const normalized = statsPromptText(name, 120);
25619
+ return normalized ? { name: normalized } : null;
25620
+ });
25621
+ const skills = normalizeStatsPromptInventory(section.skills, STATS_PROMPT_SKILL_LIMIT, "items", (value) => {
25622
+ const item = statsPromptRecord(value);
25623
+ if (!item) return null;
25624
+ const name = statsPromptText(item.name, 120);
25625
+ const description = statsPromptNullableText(item.description, 360);
25626
+ return !name || description === undefined ? null : { name, description };
25627
+ });
25628
+ const contextFiles = normalizeStatsPromptInventory(section.contextFiles, STATS_PROMPT_CONTEXT_FILE_LIMIT, "items", (value) => {
25629
+ const item = statsPromptRecord(value);
25630
+ if (!item) return null;
25631
+ const displayPath = statsPromptText(item.displayPath, 240);
25632
+ const chars = statsPromptNullableMetric(item.chars);
25633
+ return !displayPath || chars === undefined ? null : { displayPath, chars };
25634
+ });
25635
+
25636
+ if (!source || settled === null || attempts === null || warning === undefined || systemPromptChars === null
25637
+ || promptText === null || toolSchemas === null || framing === null || multiplier === null || samples === null
25638
+ || currentDate === undefined || cwdDisplay === undefined || extraGuidelineCount === null
25639
+ || !tools || !toolPromptEntries || !skills || !contextFiles) return null;
25640
+ return {
25641
+ source, settled, attempts, warning, systemPromptChars,
25642
+ estimateComponents: { promptText, toolSchemas, framing, calibration: { multiplier, samples } },
25643
+ metadata: { currentDate, cwdDisplay, extraGuidelineCount },
25644
+ tools, toolPromptEntries, skills, contextFiles,
25645
+ };
25646
+ }
25647
+
25648
+ function normalizeStatsPromptCurrent(value) {
25649
+ const section = statsPromptRecord(value);
25650
+ const usage = statsPromptRecord(section?.usage);
25651
+ const breakdown = statsPromptRecord(section?.breakdown);
25652
+ if (!section || !usage || !breakdown) return null;
25653
+ const tokens = statsPromptNullableMetric(usage.tokens);
25654
+ const contextWindow = statsPromptNullableMetric(usage.contextWindow);
25655
+ const percent = statsPromptNullableMetric(usage.percent);
25656
+ const estimateMethod = statsPromptText(breakdown.estimateMethod, 160);
25657
+ const reconstruction = statsPromptText(breakdown.reconstruction, 40);
25658
+ const estimatedTotalTokens = statsPromptMetric(breakdown.estimatedTotalTokens);
25659
+ const actualMinusEstimatedTokens = statsPromptNullableMetric(breakdown.actualMinusEstimatedTokens, { signed: true });
25660
+ const sources = statsPromptList(breakdown.sources, STATS_PROMPT_SOURCE_LIMIT, (entry) => normalizeStatsPromptSource(entry, "estimatedTokens"));
25661
+ if (tokens === undefined || contextWindow === undefined || percent === undefined || !estimateMethod
25662
+ || !["complete", "unavailable"].includes(reconstruction) || estimatedTotalTokens === null
25663
+ || actualMinusEstimatedTokens === undefined || !sources) return null;
25664
+ return { usage: { tokens, contextWindow, percent }, breakdown: { estimateMethod, reconstruction, estimatedTotalTokens, actualMinusEstimatedTokens, sources } };
25665
+ }
25666
+
25667
+ function statsPromptKindLabel(kind) {
25668
+ return ({
25669
+ "system-prompt": "System prompt", "tools-prompt": "Tools prompt", "custom-prompt": "Custom prompt",
25670
+ "append-system": "Append system", "context-file": "Context file", skills: "Skills",
25671
+ "tool-schemas": "Tool schemas", framing: "Framing", "user-messages": "User messages",
25672
+ "assistant-messages": "Assistant messages", "assistant-tool-calls": "Assistant + tool calls",
25673
+ "tool-results": "Tool results", other: "Other",
25674
+ })[kind] || kind;
25675
+ }
25676
+
25677
+ function statsPromptSectionHeading(title, eyebrow) {
25678
+ const header = make("div", "stats-prompt-section-heading");
25679
+ const text = make("div");
25680
+ text.append(make("span", "stats-prompt-eyebrow", eyebrow), make("h3", undefined, title));
25681
+ header.append(text);
25682
+ return header;
25683
+ }
25684
+
25685
+ function statsPromptLegacyFallback(title, lines) {
25686
+ const section = make("section", "stats-prompt-section stats-prompt-legacy-fallback");
25687
+ const heading = statsPromptSectionHeading(title, "Legacy fallback");
25688
+ heading.append(make("span", "stats-prompt-badge warning", "Structured data unavailable"));
25689
+ section.append(heading, make("p", "stats-prompt-note muted", "Showing the matching legacy command output for this section."), statsLineBlock(lines));
25690
+ return section;
25691
+ }
25692
+
25693
+ function statsPromptCompositionTrack(rows, tokenKey, totalTokens, label) {
25694
+ const figure = make("figure", "stats-prompt-composition");
25695
+ const track = make("div", "stats-prompt-composition-track");
25696
+ const describedRows = rows.slice(0, 6);
25697
+ const described = describedRows.map((row) => `${row.label} ${formatStatsPromptNullablePercent(row.percent)}`).join(", ");
25698
+ const remaining = rows.length - describedRows.length;
25699
+ track.setAttribute("role", "img");
25700
+ track.setAttribute("aria-label", `${label}: ${described || "no estimated tokens"}${remaining > 0 ? `, and ${remaining} more sources` : ""}.`);
25701
+ for (const row of rows) {
25702
+ if (row[tokenKey] <= 0 || row.percent === null) continue;
25703
+ const segment = make("span", "stats-prompt-composition-segment");
25704
+ segment.dataset.promptKind = row.kind;
25705
+ segment.style.width = `${Math.min(100, row.percent)}%`;
25706
+ segment.title = `${row.label}: ${formatStatsTokens(row[tokenKey])} tok (${formatStatsPromptNullablePercent(row.percent)})`;
25707
+ track.append(segment);
25708
+ }
25709
+ figure.append(track, make("figcaption", "stats-prompt-note muted", `${formatStatsTokens(totalTokens)} estimated tokens · numeric values are repeated in the table below.`));
25710
+ return figure;
25711
+ }
25712
+
25713
+ function statsPromptTable(headers, rows, caption) {
25714
+ const wrapper = make("div", "stats-overlay-table-wrap stats-prompt-table-wrap");
25715
+ const table = make("table", "stats-overlay-table stats-prompt-table");
25716
+ table.append(make("caption", "stats-overlay-table-caption", caption));
25717
+ const thead = make("thead");
25718
+ const headRow = make("tr");
25719
+ for (const header of headers) {
25720
+ const th = make("th", undefined, header);
25721
+ th.scope = "col";
25722
+ headRow.append(th);
25723
+ }
25724
+ thead.append(headRow);
25725
+ const tbody = make("tbody");
25726
+ for (const row of rows) {
25727
+ const tr = make("tr");
25728
+ row.forEach((value, index) => {
25729
+ const cell = make("td", undefined, value);
25730
+ cell.dataset.label = headers[index];
25731
+ tr.append(cell);
25732
+ });
25733
+ tbody.append(tr);
25734
+ }
25735
+ table.append(thead, tbody);
25736
+ wrapper.append(table);
25737
+ return wrapper;
25738
+ }
25739
+
25740
+ function renderStatsPromptInitial(section) {
25741
+ const node = make("section", "stats-prompt-section stats-prompt-initial");
25742
+ const heading = statsPromptSectionHeading("Initial prompt composition", "Calibrated estimate");
25743
+ heading.append(make("span", "stats-prompt-badge", `${formatStatsTokens(section.totalTokens)} tok`));
25744
+ const summary = make("p", "stats-prompt-note muted", `Range ${formatStatsTokens(section.lowTokens)}–${formatStatsTokens(section.highTokens)} tok · ${section.confidence} · ${statsPromptEstimateSourceLabel(section)}`);
25745
+ node.append(heading, summary);
25746
+ if (section.warning) node.append(make("p", "stats-prompt-warning", section.warning));
25747
+ node.append(
25748
+ statsPromptCompositionTrack(section.components, "tokens", section.totalTokens, "Initial prompt composition"),
25749
+ statsPromptTable(
25750
+ ["Rank", "Source", "Kind", "Chars", "Uncalibrated", "Tokens", "Share"],
25751
+ section.components.map((component, index) => [
25752
+ String(index + 1), component.label, statsPromptKindLabel(component.kind),
25753
+ component.chars === null ? "n/a" : component.chars.toLocaleString(),
25754
+ `${formatStatsTokens(component.uncalibratedTokens)} tok`, `${formatStatsTokens(component.tokens)} tok`,
25755
+ formatStatsPromptNullablePercent(component.percent),
25756
+ ]),
25757
+ "Ranked initial-prompt token composition. Calibrated component tokens sum to the displayed total.",
25758
+ ),
25759
+ );
25760
+ return node;
25761
+ }
25762
+
25763
+ function statsPromptInventoryDetails(title, inventory, renderBody) {
25764
+ const details = make("details", "stats-prompt-inventory-details");
25765
+ const shown = inventory.items.length;
25766
+ const count = `${shown} shown / ${inventory.totalCount} total${inventory.omittedCount ? ` · ${inventory.omittedCount} omitted` : ""}`;
25767
+ const summary = make("summary");
25768
+ summary.append(make("span", undefined, title), make("span", "stats-prompt-details-count", count));
25769
+ details.append(summary);
25770
+ const body = make("div", "stats-prompt-details-body");
25771
+ body.append(renderBody(inventory.items));
25772
+ if (inventory.omittedCount) body.append(make("p", "stats-prompt-note muted", `${inventory.omittedCount} additional ${title.toLowerCase()} omitted by the producer cap.`));
25773
+ details.append(body);
25774
+ return details;
25775
+ }
25776
+
25777
+ function statsPromptDefinitionList(entries) {
25778
+ const list = make("dl", "stats-prompt-definition-list");
25779
+ for (const [term, description] of entries) list.append(make("dt", undefined, term), make("dd", undefined, description));
25780
+ return list;
25781
+ }
25782
+
25783
+ function renderStatsPromptSnapshot(section) {
25784
+ const node = make("section", "stats-prompt-section stats-prompt-snapshot");
25785
+ const heading = statsPromptSectionHeading("Prompt inventory", "Export-backed snapshot");
25786
+ heading.append(make("span", "stats-prompt-badge", `${section.systemPromptChars.toLocaleString()} chars`));
25787
+ node.append(heading);
25788
+ if (section.warning) node.append(make("p", "stats-prompt-warning", section.warning));
25789
+
25790
+ const estimates = section.estimateComponents;
25791
+ const cards = make("div", "stats-prompt-estimate-cards");
23349
25792
  cards.append(
23350
- statsMetricCard("PI estimate", `~${formatStatsTokens(payload?.promptEstimate?.total)} tok`, `${statsPromptEstimateSourceLabel(payload?.promptEstimate)} · ${payload?.promptEstimate?.confidence || "estimate"}`, "tone-yellow"),
23351
- statsMetricCard("Prompt chars", statsNumber(payload?.promptEstimate?.systemPromptChars).toLocaleString(), `${statsNumber(payload?.promptEstimate?.activeToolSchemas)} active tool schemas`, "tone-blue"),
23352
- statsMetricCard("Calibration", `×${statsNumber(payload?.promptEstimate?.calibrationMultiplier, 1).toFixed(2)}`, `${statsNumber(payload?.promptEstimate?.calibrationSamples)} samples`, "tone-teal"),
23353
- statsMetricCard("Attempts", String(statsNumber(payload?.promptEstimate?.attempts)), payload?.promptEstimate?.settled ? "settled" : "live fallback", "tone-mauve"),
25793
+ statsMetricCard("Prompt text", `${formatStatsTokens(estimates.promptText)} tok`, "character-derived estimate", "tone-blue"),
25794
+ statsMetricCard("Tool schemas", `${formatStatsTokens(estimates.toolSchemas)} tok`, "active schema estimate", "tone-teal"),
25795
+ statsMetricCard("Framing", `${formatStatsTokens(estimates.framing)} tok`, "provider/request allowance", "tone-mauve"),
25796
+ statsMetricCard("Calibration", `×${estimates.calibration.multiplier.toFixed(2)}`, `${estimates.calibration.samples} samples`, "tone-yellow"),
25797
+ );
25798
+ node.append(cards);
25799
+
25800
+ const metadataDetails = make("details", "stats-prompt-inventory-details");
25801
+ const metadataSummary = make("summary");
25802
+ metadataSummary.append(make("span", undefined, "Prompt metadata"), make("span", "stats-prompt-details-count", section.settled ? "settled snapshot" : "live fallback"));
25803
+ metadataDetails.append(metadataSummary, make("div", "stats-prompt-details-body"));
25804
+ metadataDetails.lastElementChild.append(statsPromptDefinitionList([
25805
+ ["Source", statsPromptEstimateSourceLabel(section)], ["Attempts", section.attempts.toLocaleString()],
25806
+ ["Current date", section.metadata.currentDate ?? "n/a"], ["Working directory", section.metadata.cwdDisplay ?? "n/a"],
25807
+ ["Extra guidelines", section.metadata.extraGuidelineCount.toLocaleString()],
25808
+ ]));
25809
+
25810
+ const inventory = make("div", "stats-prompt-inventory");
25811
+ inventory.append(
25812
+ metadataDetails,
25813
+ statsPromptInventoryDetails("Active tool schemas", section.tools, (items) => {
25814
+ const list = make("ul", "stats-prompt-card-list");
25815
+ for (const item of items) {
25816
+ const li = make("li");
25817
+ li.append(make("strong", undefined, item.name), make("span", "stats-prompt-item-meta", `${formatStatsTokens(item.estimatedTokens)} tok · ${item.parameterSummary}`));
25818
+ if (item.description) li.append(make("span", "stats-prompt-item-description", item.description));
25819
+ list.append(li);
25820
+ }
25821
+ return list;
25822
+ }),
25823
+ statsPromptInventoryDetails("Available-tool prompt entries", section.toolPromptEntries, (items) => {
25824
+ const list = make("ul", "stats-prompt-chip-list");
25825
+ for (const item of items) list.append(make("li", undefined, item.name));
25826
+ return list;
25827
+ }),
25828
+ statsPromptInventoryDetails("Skills", section.skills, (items) => {
25829
+ const list = make("ul", "stats-prompt-card-list");
25830
+ for (const item of items) {
25831
+ const li = make("li");
25832
+ li.append(make("strong", undefined, item.name));
25833
+ if (item.description) li.append(make("span", "stats-prompt-item-description", item.description));
25834
+ list.append(li);
25835
+ }
25836
+ return list;
25837
+ }),
25838
+ statsPromptInventoryDetails("Context files", section.contextFiles, (items) => {
25839
+ const list = make("ul", "stats-prompt-file-list");
25840
+ for (const item of items) {
25841
+ const row = make("li");
25842
+ row.append(make("span", undefined, item.displayPath), make("span", undefined, item.chars === null ? "n/a" : `${item.chars.toLocaleString()} chars`));
25843
+ list.append(row);
25844
+ }
25845
+ return list;
25846
+ }),
23354
25847
  );
25848
+ node.append(inventory);
25849
+ return node;
25850
+ }
25851
+
25852
+ function renderStatsPromptCurrent(section) {
25853
+ const node = make("section", "stats-prompt-section stats-prompt-current");
25854
+ const heading = statsPromptSectionHeading("Current context", "Actual utilization + heuristic composition");
25855
+ heading.append(make("span", "stats-prompt-badge", section.usage.percent === null ? "usage n/a" : formatStatsPromptNullablePercent(section.usage.percent)));
25856
+ node.append(heading);
25857
+
25858
+ const utilization = make("div", "stats-prompt-utilization");
25859
+ const progress = make("progress", "stats-prompt-progress");
25860
+ progress.max = 100;
25861
+ if (section.usage.percent !== null) progress.value = Math.min(100, section.usage.percent);
25862
+ const usageText = `${formatStatsPromptNullableTokens(section.usage.tokens)} used / ${formatStatsPromptNullableTokens(section.usage.contextWindow)} window · ${formatStatsPromptNullablePercent(section.usage.percent)}`;
25863
+ progress.setAttribute("aria-label", "Actual current context utilization");
25864
+ progress.setAttribute("aria-valuetext", usageText);
25865
+ utilization.append(progress, make("p", "stats-prompt-utilization-text", usageText));
25866
+ node.append(utilization);
25867
+
25868
+ const breakdown = section.breakdown;
25869
+ const cards = make("div", "stats-prompt-estimate-cards compact");
25870
+ cards.append(
25871
+ statsMetricCard("Actual usage", formatStatsPromptNullableTokens(section.usage.tokens), "provider/context usage", "tone-green"),
25872
+ statsMetricCard("Context window", formatStatsPromptNullableTokens(section.usage.contextWindow), "provider/context limit", "tone-blue"),
25873
+ statsMetricCard("Heuristic estimate", `${formatStatsTokens(breakdown.estimatedTotalTokens)} tok`, breakdown.reconstruction === "complete" ? "complete reconstruction" : "partial: reconstruction unavailable", "tone-mauve"),
25874
+ statsMetricCard("Actual − estimate", breakdown.actualMinusEstimatedTokens === null ? "n/a" : `${breakdown.actualMinusEstimatedTokens > 0 ? "+" : ""}${formatStatsTokens(breakdown.actualMinusEstimatedTokens)} tok`, "comparison only; not source attribution", "tone-yellow"),
25875
+ );
25876
+ node.append(cards, make("p", "stats-prompt-note muted", "Source composition below is a character-derived heuristic. Shares use the estimated total, independently of actual provider utilization."));
25877
+ node.append(
25878
+ statsPromptCompositionTrack(breakdown.sources, "estimatedTokens", breakdown.estimatedTotalTokens, "Estimated current-source composition"),
25879
+ statsPromptTable(
25880
+ ["Rank", "Source", "Kind", "Chars", "Estimated tokens", "Estimated share"],
25881
+ breakdown.sources.map((source, index) => [
25882
+ String(index + 1), source.label, statsPromptKindLabel(source.kind), source.chars.toLocaleString(),
25883
+ `${formatStatsTokens(source.estimatedTokens)} tok`, formatStatsPromptNullablePercent(source.percent),
25884
+ ]),
25885
+ "Ranked heuristic current-context source composition. Percentages use the estimated total, not actual usage.",
25886
+ ),
25887
+ );
25888
+ return node;
25889
+ }
25890
+
25891
+ function renderStatsPrompt(payload) {
25892
+ const node = make("div", "stats-overlay-pane stats-prompt-pane");
25893
+ const context = statsPromptRecord(payload?.promptContext);
25894
+ const initialPrompt = normalizeStatsPromptInitial(context?.initialPrompt);
25895
+ const snapshot = normalizeStatsPromptSnapshot(context?.snapshot);
25896
+ const currentContext = normalizeStatsPromptCurrent(context?.currentContext);
23355
25897
  node.append(
23356
- cards,
23357
25898
  renderStatsCalibrationPanel(payload),
23358
- make("h3", undefined, "PI prompt estimate"),
23359
- statsLineBlock(payload?.lines?.promptInjection),
23360
- make("h3", undefined, "Detailed prompt snapshot"),
23361
- statsLineBlock(payload?.lines?.promptDetailed),
23362
- make("h3", undefined, "Current context token breakdown"),
23363
- statsLineBlock(payload?.lines?.tokenBreakdown),
25899
+ initialPrompt ? renderStatsPromptInitial(initialPrompt) : statsPromptLegacyFallback("Initial prompt composition", payload?.lines?.promptInjection),
25900
+ snapshot ? renderStatsPromptSnapshot(snapshot) : statsPromptLegacyFallback("Prompt inventory", payload?.lines?.promptDetailed),
25901
+ currentContext ? renderStatsPromptCurrent(currentContext) : statsPromptLegacyFallback("Current context", payload?.lines?.tokenBreakdown),
23364
25902
  );
23365
25903
  return node;
23366
25904
  }
@@ -23382,8 +25920,9 @@ function renderStatsRaw(payload) {
23382
25920
  statsCommandOutputSection("Model comparison", "/stats-model-compare [days|all]", "Token share, spend share, average cost, and average output by model.", payload?.lines?.modelComparison),
23383
25921
  statsCommandOutputSection("Most expensive sessions", "/stats-most-expense [days|all]", "Highest-cost sessions in the selected range.", payload?.lines?.expensiveSessions),
23384
25922
  statsCommandOutputSection("Cost trend", "/stats-cost-trend [days|all]", "Daily averages, 30-day projection, highest day, and latest active day.", payload?.lines?.costTrend),
23385
- statsCommandOutputSection("Cache efficiency", "/stats-cache [days|all]", "Cache hit rate, cache read/write tokens, estimated savings, and token mix.", payload?.lines?.cache),
25923
+ statsCommandOutputSection("Cache efficiency", "/stats-cache [days|all]", "Cached-input token share, cache read/write tokens, and token mix.", payload?.lines?.cache),
23386
25924
  statsCommandOutputSection("PI prompt breakdown", "/stats-pi detailed", "Export-backed initial prompt estimate with detailed prompt snapshot sections.", [...(payload?.lines?.promptInjection || []), "", ...(payload?.lines?.promptDetailed || [])]),
25925
+ statsCommandOutputSection("Current context breakdown", "/stats tokens", "Actual context usage plus the estimated source breakdown.", payload?.lines?.tokenBreakdown),
23387
25926
  );
23388
25927
  return node;
23389
25928
  }
@@ -23401,6 +25940,13 @@ function renderStatsOverlayPane(payload) {
23401
25940
  }
23402
25941
  }
23403
25942
 
25943
+ function activateStatsOverlayTab(tabId, { focus = false } = {}) {
25944
+ if (!STATS_OVERLAY_TABS.some((tab) => tab.id === tabId)) return;
25945
+ statsOverlayActiveTab = tabId;
25946
+ renderStatsOverlay();
25947
+ if (focus) document.getElementById(`statsOverlayTab-${tabId}`)?.focus();
25948
+ }
25949
+
23404
25950
  function renderStatsOverlay() {
23405
25951
  const payload = currentStatsOverlayPayload();
23406
25952
  if (!elements.statsOverlayDialog) return;
@@ -23409,8 +25955,10 @@ function renderStatsOverlay() {
23409
25955
  syncStatsScopeControls(statsOverlayLoading ? null : payload);
23410
25956
 
23411
25957
  const generated = payload?.generatedAt ? new Date(payload.generatedAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }) : "not loaded";
25958
+ const scopedSessions = payload ? statsNullableNumber(payload?.scopedSessionCount) : null;
25959
+ const sessionText = scopedSessions !== null ? `${scopedSessions} sessions in range` : `${payload?.sessionCount ?? 0} session files`;
23412
25960
  elements.statsOverlaySubtitle.textContent = payload
23413
- ? `${payload.scopeLabel || "stats"} · ${payload.sessionCount ?? 0} sessions · updated ${generated}`
25961
+ ? `${payload.scopeLabel || "stats"} · ${sessionText} · updated ${generated}`
23414
25962
  : "Run stats to load the browser dashboard.";
23415
25963
 
23416
25964
  elements.statsOverlayStatus.textContent = statsOverlayError || (statsOverlayLoading ? "Loading stats from the Pi stats extension…" : statsOverlayCalibrationMessage || (payload ? "" : "No stats payload loaded yet."));
@@ -23419,16 +25967,18 @@ function renderStatsOverlay() {
23419
25967
 
23420
25968
  elements.statsOverlayTabs.replaceChildren();
23421
25969
  for (const tab of STATS_OVERLAY_TABS) {
23422
- const button = make("button", tab.id === statsOverlayActiveTab ? "active" : "", tab.label);
25970
+ const active = tab.id === statsOverlayActiveTab;
25971
+ const button = make("button", active ? "active" : "", tab.label);
23423
25972
  button.type = "button";
25973
+ button.id = `statsOverlayTab-${tab.id}`;
23424
25974
  button.setAttribute("role", "tab");
23425
- button.setAttribute("aria-selected", tab.id === statsOverlayActiveTab ? "true" : "false");
23426
- button.addEventListener("click", () => {
23427
- statsOverlayActiveTab = tab.id;
23428
- renderStatsOverlay();
23429
- });
25975
+ button.setAttribute("aria-selected", active ? "true" : "false");
25976
+ button.setAttribute("aria-controls", "statsOverlayBody");
25977
+ button.tabIndex = active ? 0 : -1;
25978
+ button.addEventListener("click", () => activateStatsOverlayTab(tab.id, { focus: true }));
23430
25979
  elements.statsOverlayTabs.append(button);
23431
25980
  }
25981
+ elements.statsOverlayBody.setAttribute("aria-labelledby", `statsOverlayTab-${statsOverlayActiveTab}`);
23432
25982
 
23433
25983
  elements.statsOverlayRefreshButton.disabled = statsOverlayLoading;
23434
25984
  elements.statsOverlayBody.replaceChildren(renderStatsOverlayPane(payload));
@@ -28725,10 +31275,10 @@ function resetChatOutput() {
28725
31275
  transcriptRenderer.replaceChildren(elements.chat, ...preservedNodes);
28726
31276
  }
28727
31277
 
28728
- function appendChatMessageBubble(bubble) {
31278
+ function appendChatMessageBubble(bubble, { liveTail = false } = {}) {
28729
31279
  const liveBubbles = standaloneLiveTranscriptBubbles();
28730
31280
  const tailAnchor = [...elements.chat.children]
28731
- .find((child) => child !== bubble && (child === runIndicatorBubble || liveBubbles.has(child)));
31281
+ .find((child) => child !== bubble && (child === runIndicatorBubble || (!liveTail && liveBubbles.has(child))));
28732
31282
  if (tailAnchor) elements.chat.insertBefore(bubble, tailAnchor);
28733
31283
  else elements.chat.append(bubble);
28734
31284
  }
@@ -29063,7 +31613,8 @@ function appendToolOutput(parent, text, { label = "output", previewLines = 10, p
29063
31613
  const details = make("details", "tool-output-details");
29064
31614
  details.open = open || toolOutputGloballyExpanded;
29065
31615
  details.append(make("summary", "tool-output-summary", `${label} (${lines.length} lines; expand)`));
29066
- appendText(details, clean, "code-block tool-output-code");
31616
+ const output = appendText(details, clean, "code-block tool-output-code");
31617
+ bindToolDetailsScrollMode(output);
29067
31618
  parent.append(details);
29068
31619
 
29069
31620
  const preview = make("div", "tool-output-preview");
@@ -29166,8 +31717,10 @@ function toolRawDetailsReplacer(key, value) {
29166
31717
  function appendToolRawDetails(parent, tool) {
29167
31718
  const raw = JSON.stringify({ arguments: tool.args ?? {}, result: tool.result ?? null, details: tool.details ?? {} }, toolRawDetailsReplacer, 2);
29168
31719
  const details = make("details", "tool-raw-details");
31720
+ details.open = toolOutputGloballyExpanded;
29169
31721
  details.append(make("summary", "tool-raw-summary", "raw tool data"));
29170
- appendText(details, raw, "code-block tool-raw-code");
31722
+ const output = appendText(details, raw, "code-block tool-raw-code");
31723
+ bindToolDetailsScrollMode(output);
29171
31724
  parent.append(details);
29172
31725
  }
29173
31726
 
@@ -29370,7 +31923,7 @@ function renderWorkflowStatusStack(parent, message) {
29370
31923
  : `latest ${snapshot.fallback}`;
29371
31924
 
29372
31925
  const details = make("details", "workflow-status-stack-details");
29373
- details.open = !!message.isError;
31926
+ details.open = !!message.isError || toolOutputGloballyExpanded;
29374
31927
  const summary = make("summary", "workflow-status-stack-summary");
29375
31928
  summary.setAttribute("aria-label", `Workflow status updates, ${countLabel}; ${latestLabel}${message.isError ? "; contains an error" : ""}`);
29376
31929
  const heading = make("span", "workflow-status-stack-heading");
@@ -29460,21 +32013,166 @@ function toolDetailsStateKey(details, counts) {
29460
32013
  return `${base}|${index}`;
29461
32014
  }
29462
32015
 
29463
- function captureToolDetailsOpenState(root) {
29464
- const state = new Set();
32016
+ function toolDetailsScrollStateKey(node, counts) {
32017
+ const classKey = Array.from(node.classList || []).sort().join(".") || node.tagName.toLowerCase();
32018
+ const index = counts.get(classKey) || 0;
32019
+ counts.set(classKey, index + 1);
32020
+ return `${classKey}|${index}`;
32021
+ }
32022
+
32023
+ function bindToolDetailsScrollMode(node) {
32024
+ if (!node) return;
32025
+ node.dataset.toolScrollMode ||= "position";
32026
+ ensureToolInteractionDelegation();
32027
+ }
32028
+
32029
+ function captureToolDetailsInteractionState(root) {
32030
+ const state = new Map();
29465
32031
  const counts = new Map();
29466
32032
  for (const details of root.querySelectorAll("details")) {
29467
32033
  const key = toolDetailsStateKey(details, counts);
29468
- if (details.open) state.add(key);
32034
+ const summary = details.querySelector(":scope > summary");
32035
+ const scroll = new Map();
32036
+ const scrollCounts = new Map();
32037
+ if (details.open) {
32038
+ for (const node of details.querySelectorAll(".tool-output-code, .tool-raw-code, :scope > .message-body")) {
32039
+ bindToolDetailsScrollMode(node);
32040
+ scroll.set(toolDetailsScrollStateKey(node, scrollCounts), {
32041
+ source: node,
32042
+ mode: node.dataset.toolScrollMode || "position",
32043
+ scrollTop: node.scrollTop,
32044
+ scrollLeft: node.scrollLeft,
32045
+ });
32046
+ }
32047
+ }
32048
+ state.set(key, {
32049
+ open: details.open,
32050
+ summarySource: summary,
32051
+ summaryFocused: document.activeElement === summary,
32052
+ scroll,
32053
+ });
29469
32054
  }
29470
32055
  return state;
29471
32056
  }
29472
32057
 
29473
- function restoreToolDetailsOpenState(root, state) {
32058
+ function restoreToolDetailsInteractionState(root, state) {
29474
32059
  if (!state?.size) return;
29475
32060
  const counts = new Map();
29476
32061
  for (const details of root.querySelectorAll("details")) {
29477
- if (state.has(toolDetailsStateKey(details, counts))) details.open = true;
32062
+ const snapshot = state.get(toolDetailsStateKey(details, counts));
32063
+ if (!snapshot) continue;
32064
+ details.open = snapshot.open;
32065
+ const summary = details.querySelector(":scope > summary");
32066
+ if (snapshot.summaryFocused && document.activeElement !== summary && !isMeaningfulConnectedFocus(document.activeElement)) {
32067
+ try {
32068
+ summary?.focus({ preventScroll: true });
32069
+ } catch {
32070
+ summary?.focus();
32071
+ }
32072
+ }
32073
+ const scrollCounts = new Map();
32074
+ for (const node of details.querySelectorAll(".tool-output-code, .tool-raw-code, :scope > .message-body")) {
32075
+ bindToolDetailsScrollMode(node);
32076
+ const scrollSnapshot = snapshot.scroll.get(toolDetailsScrollStateKey(node, scrollCounts));
32077
+ if (!scrollSnapshot || (node === scrollSnapshot.source && node.scrollTop === scrollSnapshot.scrollTop && node.scrollLeft === scrollSnapshot.scrollLeft)) continue;
32078
+ node.dataset.toolScrollMode = scrollSnapshot.mode;
32079
+ requestAnimationFrame(() => {
32080
+ if (!node.isConnected) return;
32081
+ const maxScrollTop = Math.max(0, node.scrollHeight - node.clientHeight);
32082
+ const maxScrollLeft = Math.max(0, node.scrollWidth - node.clientWidth);
32083
+ node.scrollTop = scrollSnapshot.mode === "follow-end"
32084
+ ? maxScrollTop
32085
+ : Math.min(Math.max(0, scrollSnapshot.scrollTop), maxScrollTop);
32086
+ node.scrollLeft = Math.min(Math.max(0, scrollSnapshot.scrollLeft), maxScrollLeft);
32087
+ });
32088
+ }
32089
+ }
32090
+ }
32091
+
32092
+ const INTERACTED_TOOL_BUBBLE_LIMIT = 16;
32093
+ const TOOL_INTERACTION_BUBBLE_SELECTOR = ".message.toolCall, .message.toolExecution, .message.toolResult, .message.bashExecution, .message.workflowStatusStack, .message.compactionSummary";
32094
+ const TOOL_INTERACTION_SCROLL_SELECTOR = ".tool-output-code, .tool-raw-code, .message-collapse > .message-body";
32095
+ const interactedToolBubbles = new Set();
32096
+ let toolInteractionDelegationBound = false;
32097
+
32098
+ function markInteractedToolBubble(bubble) {
32099
+ if (!bubble?.matches?.(TOOL_INTERACTION_BUBBLE_SELECTOR)) return;
32100
+ interactedToolBubbles.delete(bubble);
32101
+ interactedToolBubbles.add(bubble);
32102
+ while (interactedToolBubbles.size > INTERACTED_TOOL_BUBBLE_LIMIT) {
32103
+ interactedToolBubbles.delete(interactedToolBubbles.values().next().value);
32104
+ }
32105
+ }
32106
+
32107
+ function ensureToolInteractionDelegation() {
32108
+ if (toolInteractionDelegationBound || !elements.chat) return;
32109
+ toolInteractionDelegationBound = true;
32110
+ const markFromEvent = (event) => {
32111
+ const target = event.target instanceof Element ? event.target : null;
32112
+ const bubble = target?.closest?.(TOOL_INTERACTION_BUBBLE_SELECTOR);
32113
+ if (bubble && elements.chat.contains(bubble)) markInteractedToolBubble(bubble);
32114
+ };
32115
+ elements.chat.addEventListener("toggle", markFromEvent, true);
32116
+ elements.chat.addEventListener("focusin", markFromEvent);
32117
+ elements.chat.addEventListener("scroll", (event) => {
32118
+ const node = event.target instanceof HTMLElement ? event.target : null;
32119
+ if (node?.matches?.(TOOL_INTERACTION_SCROLL_SELECTOR)) {
32120
+ const maxScrollTop = Math.max(0, node.scrollHeight - node.clientHeight);
32121
+ node.dataset.toolScrollMode = maxScrollTop > 0 && maxScrollTop - node.scrollTop <= 24 ? "follow-end" : "position";
32122
+ }
32123
+ markFromEvent(event);
32124
+ }, true);
32125
+ }
32126
+
32127
+ function toolInteractionBubbleIdentity(bubble) {
32128
+ const role = ["toolCall", "toolExecution", "toolResult", "bashExecution", "workflowStatusStack", "compactionSummary"]
32129
+ .find((candidate) => bubble.classList.contains(candidate)) || "tool";
32130
+ return {
32131
+ role,
32132
+ toolCallId: bubble.dataset.toolCallId || "",
32133
+ itemKey: bubble.dataset.itemKey || "",
32134
+ transcriptMessageKey: bubble.dataset.transcriptMessageKey || "",
32135
+ messageIndex: bubble.dataset.messageIndex || "",
32136
+ };
32137
+ }
32138
+
32139
+ function captureInteractedToolInteractionState() {
32140
+ const snapshots = [];
32141
+ for (const bubble of [...interactedToolBubbles]) {
32142
+ if (!bubble.isConnected || !elements.chat.contains(bubble)) {
32143
+ interactedToolBubbles.delete(bubble);
32144
+ continue;
32145
+ }
32146
+ snapshots.push({
32147
+ source: bubble,
32148
+ identity: toolInteractionBubbleIdentity(bubble),
32149
+ details: captureToolDetailsInteractionState(bubble),
32150
+ });
32151
+ }
32152
+ return snapshots;
32153
+ }
32154
+
32155
+ function toolInteractionBubbleForSnapshot(snapshot) {
32156
+ if (snapshot.source?.isConnected && elements.chat.contains(snapshot.source)) return snapshot.source;
32157
+ const { role, toolCallId, itemKey, transcriptMessageKey, messageIndex } = snapshot.identity || {};
32158
+ const selector = `.message.${CSS.escape(role || "tool")}`;
32159
+ for (const bubble of elements.chat.querySelectorAll(selector)) {
32160
+ if (toolCallId && bubble.dataset.toolCallId === toolCallId) return bubble;
32161
+ if (!toolCallId && itemKey && bubble.dataset.itemKey === itemKey) return bubble;
32162
+ if (!toolCallId && !itemKey && transcriptMessageKey && bubble.dataset.transcriptMessageKey === transcriptMessageKey) return bubble;
32163
+ if (!toolCallId && !itemKey && !transcriptMessageKey && messageIndex && bubble.dataset.messageIndex === messageIndex) return bubble;
32164
+ }
32165
+ return null;
32166
+ }
32167
+
32168
+ function restoreInteractedToolInteractionState(snapshots) {
32169
+ for (const snapshot of snapshots || []) {
32170
+ const bubble = toolInteractionBubbleForSnapshot(snapshot);
32171
+ if (!bubble) continue;
32172
+ ensureToolInteractionDelegation();
32173
+ restoreToolDetailsInteractionState(bubble, snapshot.details);
32174
+ interactedToolBubbles.delete(snapshot.source);
32175
+ markInteractedToolBubble(bubble);
29478
32176
  }
29479
32177
  }
29480
32178
 
@@ -29530,10 +32228,10 @@ function updateLiveToolCard(bubble, message) {
29530
32228
  kind: "reconcile",
29531
32229
  surfaces: [body],
29532
32230
  mutate: () => {
29533
- const detailsOpenState = captureToolDetailsOpenState(body);
32231
+ const detailsInteractionState = captureToolDetailsInteractionState(body);
29534
32232
  transcriptRenderer.replaceChildren(body);
29535
32233
  renderToolExecution(body, message);
29536
- restoreToolDetailsOpenState(body, detailsOpenState);
32234
+ restoreToolDetailsInteractionState(body, detailsInteractionState);
29537
32235
  transcriptRenderer.ownSurface(body, { messageKey, kind: "tool-execution", segment: "0" });
29538
32236
  bubble._toolRenderSignature = nextRenderSignature;
29539
32237
  },
@@ -29779,6 +32477,7 @@ function createMessageBubble(message, { streaming = false, messageIndex = -1, tr
29779
32477
 
29780
32478
  if (isCollapsibleOutput) {
29781
32479
  const details = make("details", `message-collapse${compactThinkingAggregate ? " compact-thinking-disclosure" : ""}`);
32480
+ bindToolDetailsScrollMode(body);
29782
32481
  if (compactThinkingAggregate) {
29783
32482
  const defaultExpanded = message.compactThinkingDefaultExpanded === true;
29784
32483
  details.open = compactThinkingDisclosureExpanded(message.compactThinkingKey, defaultExpanded);
@@ -29797,6 +32496,7 @@ function createMessageBubble(message, { streaming = false, messageIndex = -1, tr
29797
32496
  bubble.append(header, body);
29798
32497
  }
29799
32498
  ownTranscriptBubble(bubble, body, message, { itemKey, streaming, transient, segmentId });
32499
+ ensureToolInteractionDelegation();
29800
32500
  if (message.role !== "workflowStatusStack") attachMessageCopyButton(bubble, message, body);
29801
32501
  attachMessageEditRetryButton(bubble, message, messageIndex, { streaming, transient });
29802
32502
  if (!streaming && !transient) renderActionFeedbackControls(bubble, message, messageIndex);
@@ -29818,7 +32518,7 @@ function appendMessage(message, options = {}) {
29818
32518
  return reused;
29819
32519
  }
29820
32520
  const created = createMessageBubble(message, { ...options, segmentId });
29821
- appendChatMessageBubble(created.bubble);
32521
+ appendChatMessageBubble(created.bubble, { liveTail: streaming || message?.live === true });
29822
32522
  return created;
29823
32523
  }
29824
32524
 
@@ -30465,53 +33165,107 @@ function chatTextSelectionPoint(surface, offset) {
30465
33165
  return last ? { node: last, offset: last.data.length } : { node: surface, offset: 0 };
30466
33166
  }
30467
33167
 
33168
+ function chatTextSelectionEndpoint(surface, node, offset) {
33169
+ const textOffset = chatTextSelectionOffset(surface, node, offset);
33170
+ if (textOffset === null) return null;
33171
+ const bubble = surface.closest(".message");
33172
+ const surfaceText = surface.textContent || "";
33173
+ const contextRadius = 48;
33174
+ return {
33175
+ source: surface,
33176
+ itemKey: bubble?.dataset?.transcriptMessageKey || bubble?.dataset?.itemKey || "",
33177
+ surfaceKey: surface.dataset?.transcriptSurfaceKey || "",
33178
+ streaming: bubble?.classList?.contains("streaming") === true || bubble?.classList?.contains("compact-live-output") === true,
33179
+ offset: textOffset,
33180
+ before: surfaceText.slice(Math.max(0, textOffset - contextRadius), textOffset),
33181
+ after: surfaceText.slice(textOffset, textOffset + contextRadius),
33182
+ };
33183
+ }
33184
+
30468
33185
  function captureChatTextSelection(expectedSurface = null) {
30469
33186
  const selection = window.getSelection?.();
30470
33187
  if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return null;
30471
33188
  const anchorSurface = chatTextSelectionSurface(selection.anchorNode);
30472
33189
  const focusSurface = chatTextSelectionSurface(selection.focusNode);
30473
- if (!anchorSurface || anchorSurface !== focusSurface || (expectedSurface && anchorSurface !== expectedSurface)) return null;
30474
- const anchorOffset = chatTextSelectionOffset(anchorSurface, selection.anchorNode, selection.anchorOffset);
30475
- const focusOffset = chatTextSelectionOffset(anchorSurface, selection.focusNode, selection.focusOffset);
33190
+ if (!anchorSurface || !focusSurface || (expectedSurface && (anchorSurface !== expectedSurface || focusSurface !== expectedSurface))) return null;
33191
+ const anchor = chatTextSelectionEndpoint(anchorSurface, selection.anchorNode, selection.anchorOffset);
33192
+ const focus = chatTextSelectionEndpoint(focusSurface, selection.focusNode, selection.focusOffset);
30476
33193
  const text = selection.toString();
30477
- if (anchorOffset === null || focusOffset === null || !text) return null;
30478
- const bubble = anchorSurface.closest(".message");
33194
+ if (!anchor || !focus || !text) return null;
30479
33195
  return {
30480
33196
  contextKey: chatTextSelectionContextKey(),
30481
- source: anchorSurface,
30482
- itemKey: bubble?.dataset?.transcriptMessageKey || bubble?.dataset?.itemKey || "",
30483
- streaming: bubble?.classList?.contains("streaming") === true || bubble?.classList?.contains("compact-live-output") === true,
30484
- anchorOffset,
30485
- focusOffset,
33197
+ source: anchor.source,
33198
+ itemKey: anchor.itemKey === focus.itemKey ? anchor.itemKey : "",
33199
+ streaming: anchor.streaming || focus.streaming,
33200
+ anchorOffset: anchor.offset,
33201
+ focusOffset: focus.offset,
33202
+ anchor,
33203
+ focus,
30486
33204
  text,
30487
33205
  };
30488
33206
  }
30489
33207
 
30490
- function chatTextSelectionMatch(surface, snapshot) {
30491
- const anchor = chatTextSelectionPoint(surface, snapshot.anchorOffset);
30492
- const focus = chatTextSelectionPoint(surface, snapshot.focusOffset);
33208
+ function chatTextSelectionEndpointPoint(surface, endpoint) {
33209
+ const surfaceText = surface.textContent || "";
33210
+ const contextMatches = (offset) => surfaceText.slice(Math.max(0, offset - endpoint.before.length), offset) === endpoint.before
33211
+ && surfaceText.slice(offset, offset + endpoint.after.length) === endpoint.after;
33212
+ let offset = endpoint.offset;
33213
+ if (!contextMatches(offset)) {
33214
+ const context = `${endpoint.before}${endpoint.after}`;
33215
+ const index = context ? surfaceText.indexOf(context) : -1;
33216
+ if (index < 0 || surfaceText.indexOf(context, index + 1) !== -1) return null;
33217
+ offset = index + endpoint.before.length;
33218
+ if (!contextMatches(offset)) return null;
33219
+ }
33220
+ return chatTextSelectionPoint(surface, offset);
33221
+ }
33222
+
33223
+ function chatTextSelectionPointPrecedes(anchor, focus) {
33224
+ if (anchor.node === focus.node) return anchor.offset <= focus.offset;
33225
+ return !!(anchor.node.compareDocumentPosition(focus.node) & Node.DOCUMENT_POSITION_FOLLOWING);
33226
+ }
33227
+
33228
+ function chatTextSelectionSpansSurfaces(snapshot) {
33229
+ return snapshot.anchor.itemKey !== snapshot.focus.itemKey || snapshot.anchor.surfaceKey !== snapshot.focus.surfaceKey;
33230
+ }
33231
+
33232
+ function chatTextSelectionMatch(anchorSurface, focusSurface, snapshot) {
33233
+ const anchor = chatTextSelectionEndpointPoint(anchorSurface, snapshot.anchor);
33234
+ const focus = chatTextSelectionEndpointPoint(focusSurface, snapshot.focus);
33235
+ if (!anchor || !focus) return null;
30493
33236
  const range = document.createRange();
30494
- const anchorFirst = snapshot.anchorOffset <= snapshot.focusOffset;
33237
+ const anchorFirst = chatTextSelectionPointPrecedes(anchor, focus);
30495
33238
  try {
30496
33239
  range.setStart(anchorFirst ? anchor.node : focus.node, anchorFirst ? anchor.offset : focus.offset);
30497
33240
  range.setEnd(anchorFirst ? focus.node : anchor.node, anchorFirst ? focus.offset : anchor.offset);
30498
33241
  } catch {
30499
33242
  return null;
30500
33243
  }
30501
- return range.toString() === snapshot.text ? { anchor, focus, range } : null;
33244
+ const text = range.toString();
33245
+ return text && (chatTextSelectionSpansSurfaces(snapshot) || text === snapshot.text) ? { anchor, focus, range } : null;
30502
33246
  }
30503
33247
 
30504
- function chatTextSelectionCandidates(snapshot) {
33248
+ function chatTextSelectionCandidates(snapshot, endpointName) {
33249
+ const endpoint = snapshot?.[endpointName];
33250
+ if (!endpoint) return [];
30505
33251
  const candidates = [];
30506
33252
  const add = (surface) => {
30507
33253
  if (surface && elements.chat.contains(surface) && !candidates.includes(surface)) candidates.push(surface);
30508
33254
  };
30509
- add(snapshot.source?.isConnected ? snapshot.source : null);
30510
- if (snapshot.itemKey) {
30511
- const bubble = elements.chat.querySelector(`.message[data-item-key="${CSS.escape(snapshot.itemKey)}"]`);
30512
- for (const surface of bubble?.querySelectorAll?.("[data-transcript-surface], .markdown-body, .compact-live-text") || []) add(surface);
33255
+ add(endpoint.source?.isConnected ? endpoint.source : null);
33256
+ if (endpoint.surfaceKey) {
33257
+ for (const surface of elements.chat.querySelectorAll("[data-transcript-surface-key]")) {
33258
+ if (surface.dataset.transcriptSurfaceKey === endpoint.surfaceKey) add(surface);
33259
+ }
30513
33260
  }
30514
- if (snapshot.streaming) {
33261
+ if (endpoint.itemKey) {
33262
+ for (const bubble of elements.chat.querySelectorAll(".message[data-item-key], .message[data-transcript-message-key]")) {
33263
+ const key = bubble.dataset.transcriptMessageKey || bubble.dataset.itemKey || "";
33264
+ if (key !== endpoint.itemKey) continue;
33265
+ for (const surface of bubble.querySelectorAll("[data-transcript-surface], .markdown-body, .compact-live-text")) add(surface);
33266
+ }
33267
+ }
33268
+ if (endpoint.streaming) {
30515
33269
  const liveReplacement = [...elements.chat.querySelectorAll(".message.assistant [data-transcript-surface], .message.assistant .markdown-body, .message.assistant .compact-live-text")].reverse();
30516
33270
  for (const surface of liveReplacement) add(surface);
30517
33271
  }
@@ -30525,23 +33279,27 @@ function restoreChatTextSelection(snapshot) {
30525
33279
  const currentText = selection.rangeCount && !selection.isCollapsed ? selection.toString() : "";
30526
33280
  const currentAnchorSurface = chatTextSelectionSurface(selection.anchorNode);
30527
33281
  const currentFocusSurface = chatTextSelectionSurface(selection.focusNode);
30528
- const candidates = chatTextSelectionCandidates(snapshot);
30529
- if (currentText === snapshot.text && currentAnchorSurface === currentFocusSurface && candidates.includes(currentAnchorSurface)) return;
33282
+ const anchorCandidates = chatTextSelectionCandidates(snapshot, "anchor");
33283
+ const focusCandidates = chatTextSelectionCandidates(snapshot, "focus");
33284
+ const currentEndpointsMatch = anchorCandidates.includes(currentAnchorSurface) && focusCandidates.includes(currentFocusSurface);
33285
+ if (currentEndpointsMatch && (chatTextSelectionSpansSurfaces(snapshot) ? !!currentText : currentText === snapshot.text)) return;
30530
33286
  if (currentText && currentAnchorSurface && currentFocusSurface) return;
30531
- for (const surface of candidates) {
30532
- const match = chatTextSelectionMatch(surface, snapshot);
30533
- if (!match) continue;
30534
- try {
30535
- selection.removeAllRanges();
30536
- if (typeof selection.setBaseAndExtent === "function") {
30537
- selection.setBaseAndExtent(match.anchor.node, match.anchor.offset, match.focus.node, match.focus.offset);
30538
- } else {
30539
- selection.addRange(match.range);
33287
+ for (const anchorSurface of anchorCandidates) {
33288
+ for (const focusSurface of focusCandidates) {
33289
+ const match = chatTextSelectionMatch(anchorSurface, focusSurface, snapshot);
33290
+ if (!match) continue;
33291
+ try {
33292
+ selection.removeAllRanges();
33293
+ if (typeof selection.setBaseAndExtent === "function") {
33294
+ selection.setBaseAndExtent(match.anchor.node, match.anchor.offset, match.focus.node, match.focus.offset);
33295
+ } else {
33296
+ selection.addRange(match.range);
33297
+ }
33298
+ } catch {
33299
+ // A stale DOM range should not interfere with the authoritative transcript render.
30540
33300
  }
30541
- } catch {
30542
- // A stale DOM range should not interfere with the authoritative transcript render.
33301
+ return;
30543
33302
  }
30544
- return;
30545
33303
  }
30546
33304
  }
30547
33305
 
@@ -30563,6 +33321,7 @@ function pruneDisconnectedLiveToolCards() {
30563
33321
 
30564
33322
  function renderAllMessages({ preserveScroll = false, forceRebuild = false } = {}) {
30565
33323
  const selectionSnapshot = captureChatTextSelection();
33324
+ const toolInteractionSnapshots = captureInteractedToolInteractionState();
30566
33325
  const shouldFollow = !preserveScroll && (autoFollowChat || isChatNearBottom());
30567
33326
  const previousScrollTop = elements.chat.scrollTop;
30568
33327
  if (!autoFollowChat) chatPausedScrollRestoreUntil = performance.now() + CHAT_PROGRAMMATIC_SCROLL_GRACE_MS;
@@ -30631,7 +33390,7 @@ function renderAllMessages({ preserveScroll = false, forceRebuild = false } = {}
30631
33390
  else if (elements.workspaceDashboard) elements.workspaceDashboard.hidden = workspaceDashboardCollapsed;
30632
33391
  renderedTranscriptState = { epoch, entries: nextEntries.map(({ key, sig }) => ({ key, sig })) };
30633
33392
  rememberActionEntries(transcriptItems);
30634
- applyToolOutputExpansionToDom();
33393
+ restoreInteractedToolInteractionState(toolInteractionSnapshots);
30635
33394
  runIndicatorRemovalDeferred = false;
30636
33395
  renderRunIndicator({ scroll: false });
30637
33396
  updateStickyUserPromptButton();
@@ -31098,6 +33857,7 @@ function resetOptionalFeatureAvailability() {
31098
33857
  for (const key of Object.keys(optionalFeatureAvailability)) optionalFeatureAvailability[key] = false;
31099
33858
  optionalFeatureAvailability.themeBundle = availableThemes.length > 0;
31100
33859
  renderOptionalFeatureControls();
33860
+ if (activeTabId) queueMicrotask(() => refreshQuestionnaireFeatureAvailability());
31101
33861
  }
31102
33862
 
31103
33863
  function optionalFeaturePackageStatus(featureId) {
@@ -31187,6 +33947,24 @@ async function copyOptionalFeatureInstallCommand(featureId) {
31187
33947
  }
31188
33948
  }
31189
33949
 
33950
+ async function refreshQuestionnaireFeatureAvailability(tabContext = activeTabContext()) {
33951
+ if (!tabContext.tabId) return false;
33952
+ try {
33953
+ const response = await api("/api/tools?scope=session", { tabId: tabContext.tabId });
33954
+ if (!isCurrentTabContext(tabContext)) return false;
33955
+ optionalFeatureAvailability.questionnaire = Array.isArray(response.data?.tools)
33956
+ && response.data.tools.some((tool) => tool?.name === "questionnaire");
33957
+ renderOptionalFeatureControls();
33958
+ return true;
33959
+ } catch {
33960
+ if (isCurrentTabContext(tabContext)) {
33961
+ optionalFeatureAvailability.questionnaire = false;
33962
+ renderOptionalFeatureControls();
33963
+ }
33964
+ return false;
33965
+ }
33966
+ }
33967
+
31190
33968
  async function refreshOptionalFeaturePackageStatuses({ announce = false } = {}) {
31191
33969
  try {
31192
33970
  const response = await api("/api/optional-features", { scoped: false });
@@ -31195,6 +33973,7 @@ async function refreshOptionalFeaturePackageStatuses({ announce = false } = {})
31195
33973
  for (const status of response.data?.features || []) {
31196
33974
  if (status?.featureId) optionalFeaturePackageStatuses.set(status.featureId, status);
31197
33975
  }
33976
+ await refreshQuestionnaireFeatureAvailability();
31198
33977
  renderOptionalFeatureControls();
31199
33978
  return true;
31200
33979
  } catch (error) {
@@ -31312,8 +34091,10 @@ function updateOptionalFeatureAvailability() {
31312
34091
  }
31313
34092
 
31314
34093
  function optionalFeatureStatus(featureId) {
34094
+ const feature = OPTIONAL_FEATURE_BY_ID.get(featureId);
31315
34095
  const detected = isOptionalFeatureDetected(featureId);
31316
- const disabled = isOptionalFeatureDisabled(featureId);
34096
+ const managedWithTools = feature?.manageWith === "tools";
34097
+ const disabled = managedWithTools ? false : isOptionalFeatureDisabled(featureId);
31317
34098
  const packageStatus = optionalFeaturePackageStatus(featureId);
31318
34099
  const installMessage = optionalFeatureInstallMessages.get(featureId);
31319
34100
  const installState = optionalFeatureInstallState(featureId);
@@ -31340,6 +34121,7 @@ function optionalFeatureStatus(featureId) {
31340
34121
  }
31341
34122
  const doneDetail = installState?.phase === "done" ? optionalFeatureInstallDetail(installState, installMessage) : "";
31342
34123
  if (packageStatus?.updateAvailable) return { label: "Update available", className: "updating", detail: packageStatus.updateReason || `Installed package is older than the Web UI expects${versionSuffix}` };
34124
+ if (detected && managedWithTools) return { label: "Loaded", className: "enabled", detail: doneDetail || `Detected in the active Pi tab; manage access in Tools${versionSuffix}`, command: installState?.command || "" };
31343
34125
  if (detected && !disabled) return { label: "Enabled", className: "enabled", detail: doneDetail || `Detected and enabled in Web UI${versionSuffix}`, command: installState?.command || "" };
31344
34126
  if (detected && disabled) return { label: "Disabled", className: "disabled", detail: `Detected, but disabled in Web UI${versionSuffix}` };
31345
34127
  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 || "" };
@@ -31486,6 +34268,9 @@ function renderOptionalFeatureRow(feature) {
31486
34268
  action.textContent = "Update…";
31487
34269
  action.classList.add("update");
31488
34270
  action.addEventListener("click", () => installOptionalFeature(feature.id, { update: true }));
34271
+ } else if (detected && feature.manageWith === "tools") {
34272
+ action.textContent = "Tools…";
34273
+ action.addEventListener("click", () => openNativeToolsSelector());
31489
34274
  } else if (detected) {
31490
34275
  action.textContent = enabled ? "Disable" : "Enable";
31491
34276
  action.addEventListener("click", async () => {
@@ -33789,7 +36574,7 @@ function renderCompactToolShell(event, { complete = false } = {}) {
33789
36574
  transcriptRenderer.ownMessage(bubble, { key: `live:compact-tool:${id}`, role: "toolExecution" });
33790
36575
  transcriptRenderer.ownSurface(body, { messageKey: `live:compact-tool:${id}`, kind: "tool-execution", segment: "0" });
33791
36576
  transcriptRenderer.ownSurface(status, { messageKey: `live:compact-tool:${id}`, kind: "tool-execution", segment: "status" });
33792
- appendChatMessageBubble(bubble);
36577
+ appendChatMessageBubble(bubble, { liveTail: true });
33793
36578
  shell = { bubble, role, status };
33794
36579
  compactToolShells.set(id, shell);
33795
36580
  }
@@ -34206,26 +36991,38 @@ function restoreCompactLiveOutputAfterChatRebuild() {
34206
36991
  compactThinkingBubble = null;
34207
36992
  compactThinkingNode = null;
34208
36993
  if (streamMessageActive) flushCompactLiveOutput();
34209
- for (const shell of compactToolShells.values()) appendChatMessageBubble(shell.bubble);
36994
+ for (const shell of compactToolShells.values()) appendChatMessageBubble(shell.bubble, { liveTail: true });
34210
36995
  renderRunIndicator({ scroll: false });
34211
36996
  }
34212
36997
 
34213
36998
  /**
34214
- * The chat DOM was rebuilt while an assistant message is still streaming:
34215
- * drop references to the detached nodes but keep stream text state, then
34216
- * re-append the live thinking/text bubbles so no partial output is lost.
36999
+ * Reconcile live stream surfaces after an authoritative transcript render.
37000
+ * Transcript resets intentionally keep mounted live-tail bubbles, so reuse
37001
+ * those nodes and only rebuild a surface when it was actually detached.
34217
37002
  */
34218
37003
  function restoreStreamRenderAfterChatRebuild() {
34219
37004
  const thinkingText = streamThinking?._rawThinkingText || streamThinking?.textContent || "";
34220
37005
  const thinkingComplete = streamThinkingBubble?.classList.contains("complete") === true;
34221
37006
  const toolCallWasVisible = !!(streamToolCallBubble?.parentElement === elements.chat || streamToolCallRawArguments || streamToolCallName);
34222
- streamBubble = null;
34223
- streamText = null;
34224
- streamThinkingBubble = null;
34225
- streamThinking = null;
34226
- streamToolCallBubble = null;
34227
- streamToolCallText = null;
34228
- streamBubbleVisibleSince = 0;
37007
+ const streamOutputMounted = !!(streamBubble?.parentElement === elements.chat && streamText?.isConnected && streamBubble.contains(streamText));
37008
+ const thinkingOutputMounted = !!(streamThinkingBubble?.parentElement === elements.chat && streamThinking?.isConnected && streamThinkingBubble.contains(streamThinking));
37009
+ const toolCallOutputMounted = !!(streamToolCallBubble?.parentElement === elements.chat && streamToolCallText?.isConnected && streamToolCallBubble.contains(streamToolCallText));
37010
+ if (!streamOutputMounted) {
37011
+ removeLiveTranscriptBubble(streamBubble, "assistant-rebuild");
37012
+ streamBubble = null;
37013
+ streamText = null;
37014
+ streamBubbleVisibleSince = 0;
37015
+ }
37016
+ if (!thinkingOutputMounted) {
37017
+ removeLiveTranscriptBubble(streamThinkingBubble, "thinking-rebuild");
37018
+ streamThinkingBubble = null;
37019
+ streamThinking = null;
37020
+ }
37021
+ if (!toolCallOutputMounted) {
37022
+ removeLiveTranscriptBubble(streamToolCallBubble, "tool-call-rebuild");
37023
+ streamToolCallBubble = null;
37024
+ streamToolCallText = null;
37025
+ }
34229
37026
  if (thinkingText && setStreamingThinkingText(thinkingText) && thinkingComplete) {
34230
37027
  streamThinkingBubble?.classList.add("complete");
34231
37028
  }
@@ -36368,6 +39165,7 @@ function removeQueuedDialogRequests(ids = []) {
36368
39165
  if (activeDialog && idSet.has(String(activeDialog.id || ""))) {
36369
39166
  if (elements.dialog.open) elements.dialog.close();
36370
39167
  activeDialog = null;
39168
+ activeDialogCancel = null;
36371
39169
  showNextDialog();
36372
39170
  return true;
36373
39171
  }
@@ -36386,6 +39184,10 @@ function handleExtensionUiRequest(request) {
36386
39184
  }
36387
39185
  case "setStatus": {
36388
39186
  const statusKey = request.statusKey || "extension";
39187
+ if (statusKey === FEATURE_DECISION_OUTPUT_STATUS_KEY) {
39188
+ handleFeatureDecisionOutputStatus(request.statusText, request.tabId || activeTabId);
39189
+ return;
39190
+ }
36389
39191
  if (statusKey === FEATURE_CATEGORY_STATUS_KEY) {
36390
39192
  handleFeatureCategoryStatus(request.statusText, request.tabId || activeTabId);
36391
39193
  return;
@@ -36508,11 +39310,35 @@ async function sendDialogResponse(payload) {
36508
39310
  if (responseId && activeDialog && String(activeDialog.id || "") !== responseId) return;
36509
39311
  if (elements.dialog.open) elements.dialog.close();
36510
39312
  activeDialog = null;
36511
- if (runIndicatorIsActive()) setRunIndicatorActivity("Continuing after your response…");
39313
+ activeDialogCancel = null;
39314
+ if (runIndicatorIsActive()) {
39315
+ setRunIndicatorActivity("Continuing after your response…");
39316
+ // Extension commands can continue background work after Pi has already
39317
+ // returned to an idle canonical state. Reconcile promptly so this local
39318
+ // handoff label cannot survive the workflow that requested the dialog.
39319
+ scheduleRefreshState(120, tabContext);
39320
+ }
36512
39321
  showNextDialog();
36513
39322
  }
36514
39323
  }
36515
39324
 
39325
+ function cancelActiveExtensionDialog(event) {
39326
+ if (!activeDialog || typeof activeDialogCancel !== "function") return false;
39327
+ event?.preventDefault?.();
39328
+ return activeDialogCancel();
39329
+ }
39330
+
39331
+ function createDialogResponder(sendResponse) {
39332
+ let responseSent = false;
39333
+ return (response, onAccept) => {
39334
+ if (responseSent) return false;
39335
+ responseSent = true;
39336
+ onAccept?.();
39337
+ sendResponse(response);
39338
+ return true;
39339
+ };
39340
+ }
39341
+
36516
39342
  function addDialogButton(label, handler, className) {
36517
39343
  const button = make("button", className, label);
36518
39344
  button.type = "button";
@@ -36548,7 +39374,7 @@ function appendWorkflowScriptTokens(parent, line) {
36548
39374
  if (start < line.length) parent.append(document.createTextNode(line.slice(start)));
36549
39375
  }
36550
39376
 
36551
- function renderWorkflowScriptPreview(request) {
39377
+ function renderWorkflowScriptPreview(request, respondToDialog) {
36552
39378
  const source = request.prefill ?? "";
36553
39379
  const sourceLines = source.split("\n");
36554
39380
  const searchableLines = sourceLines.map((line) => line.toLocaleLowerCase());
@@ -36690,14 +39516,15 @@ function renderWorkflowScriptPreview(request) {
36690
39516
 
36691
39517
  preview.append(metadata, toolbar, codeViewer);
36692
39518
  elements.dialogBody.append(preview);
36693
- addDialogButton("Cancel workflow", () => sendDialogResponse({ type: "extension_ui_response", id: request.id, cancelled: true, tabId: request.tabId }));
36694
- addDialogButton("Back to approval", () => sendDialogResponse({ type: "extension_ui_response", id: request.id, value: request.prefill, tabId: request.tabId }), "primary");
39519
+ addDialogButton("Cancel workflow", () => respondToDialog({ cancelled: true }));
39520
+ addDialogButton("Back to approval", () => respondToDialog({ value: request.prefill }), "primary");
36695
39521
  setTimeout(() => codeViewer.focus(), 0);
36696
39522
  }
36697
39523
 
36698
39524
  function showNextDialog() {
36699
39525
  if (activeDialog || dialogQueue.length === 0) return;
36700
39526
  activeDialog = dialogQueue.shift();
39527
+ activeDialogCancel = null;
36701
39528
  const request = activeDialog;
36702
39529
 
36703
39530
  const prompt = normalizeDialogPrompt(request);
@@ -36707,9 +39534,11 @@ function showNextDialog() {
36707
39534
  const isGuardrailDialog = isGuardrailDialogPrompt(displayPrompt);
36708
39535
  const isReleaseDialog = !!releasePrompt;
36709
39536
  const isWorkflowScriptPreview = isWorkflowScriptPreviewRequest(request, prompt);
39537
+ const questionnaire = request.method === "select" && !isReleaseDialog ? questionnaireSelectParts(prompt, request.options) : null;
36710
39538
  elements.dialog.classList.toggle("guardrail-dialog", isGuardrailDialog);
36711
39539
  elements.dialog.classList.toggle("release-dialog", isReleaseDialog);
36712
39540
  elements.dialog.classList.toggle("workflow-script-dialog", isWorkflowScriptPreview);
39541
+ elements.dialog.classList.toggle("questionnaire-dialog", !!questionnaire);
36713
39542
  elements.dialogTitle.textContent = displayPrompt.title;
36714
39543
  if (isReleaseDialog) renderReleaseDialogMessage(elements.dialogMessage, displayPrompt.message);
36715
39544
  else renderAnsiText(elements.dialogMessage, displayPrompt.message);
@@ -36717,9 +39546,33 @@ function showNextDialog() {
36717
39546
  elements.dialogBody.replaceChildren();
36718
39547
  elements.dialogActions.replaceChildren();
36719
39548
 
36720
- const cancel = () => sendDialogResponse({ type: "extension_ui_response", id: request.id, cancelled: true, tabId: request.tabId });
36721
-
36722
- if (request.method === "select") {
39549
+ const respondToDialog = createDialogResponder((response) => {
39550
+ sendDialogResponse({ type: "extension_ui_response", id: request.id, tabId: request.tabId, ...response });
39551
+ });
39552
+ const cancel = () => respondToDialog({ cancelled: true });
39553
+ activeDialogCancel = cancel;
39554
+
39555
+ if (questionnaire) {
39556
+ const options = make("div", "dialog-options questionnaire-options");
39557
+ const respondToQuestionnaire = (response) => respondToDialog(response, () => {
39558
+ options.querySelectorAll("button").forEach((button) => { button.disabled = true; });
39559
+ elements.dialogActions.querySelectorAll("button").forEach((button) => { button.disabled = true; });
39560
+ });
39561
+ activeDialogCancel = () => respondToQuestionnaire({ cancelled: true });
39562
+ (request.options || []).forEach((option, index) => {
39563
+ const optionLabel = String(option);
39564
+ const row = questionnaire.rows[index];
39565
+ const button = row.kind === "action"
39566
+ ? renderQuestionnaireActionButton(row)
39567
+ : renderQuestionnaireOptionButton(row, questionnaire.mode);
39568
+ // Presentation is derived, but the response always carries the exact
39569
+ // native option string the questionnaire runtime produced.
39570
+ button.addEventListener("click", () => respondToQuestionnaire({ value: optionLabel }));
39571
+ options.append(button);
39572
+ });
39573
+ elements.dialogBody.append(options);
39574
+ addDialogButton("Cancel", () => respondToQuestionnaire({ cancelled: true }), "questionnaire-dialog-cancel");
39575
+ } else if (request.method === "select") {
36723
39576
  const options = make("div", "dialog-options");
36724
39577
  for (const option of request.options || []) {
36725
39578
  const optionLabel = String(option);
@@ -36732,37 +39585,55 @@ function showNextDialog() {
36732
39585
  if (isReleaseDialog && /^\[x\]/.test(optionLabel)) button.classList.add("release-target-option", "release-target-selected");
36733
39586
  if (isReleaseDialog && /^\[ \]/.test(optionLabel)) button.classList.add("release-target-option");
36734
39587
  if (isReleaseDialog && /^(?:No|Cancel)$/i.test(optionLabel)) button.classList.add("release-cancel-action");
36735
- button.addEventListener("click", () => sendDialogResponse({ type: "extension_ui_response", id: request.id, value: optionLabel, tabId: request.tabId }));
39588
+ button.addEventListener("click", () => respondToDialog({ value: optionLabel }));
36736
39589
  options.append(button);
36737
39590
  }
36738
39591
  elements.dialogBody.append(options);
36739
39592
  addDialogButton("Cancel", cancel);
36740
39593
  } else if (request.method === "confirm") {
36741
39594
  addDialogButton("Cancel", cancel);
36742
- addDialogButton("No", () => sendDialogResponse({ type: "extension_ui_response", id: request.id, confirmed: false, tabId: request.tabId }));
36743
- addDialogButton("Yes", () => sendDialogResponse({ type: "extension_ui_response", id: request.id, confirmed: true, tabId: request.tabId }), "primary");
39595
+ addDialogButton("No", () => respondToDialog({ confirmed: false }));
39596
+ addDialogButton("Yes", () => respondToDialog({ confirmed: true }), "primary");
36744
39597
  } else if (request.method === "input") {
36745
39598
  const input = make("input", "dialog-input");
36746
39599
  input.value = request.prefill || "";
36747
39600
  input.placeholder = request.placeholder || "";
36748
39601
  elements.dialogBody.append(input);
36749
- addDialogButton("Cancel", cancel);
36750
- addDialogButton("Submit", () => sendDialogResponse({ type: "extension_ui_response", id: request.id, value: input.value, tabId: request.tabId }), "primary");
39602
+ // The dialog form uses method="dialog", so an unhandled Enter would close it
39603
+ // implicitly without ever sending a response and leave the extension blocked.
39604
+ // Keyboard, click, and cancel paths therefore share one guarded one-shot closure.
39605
+ const respondToInput = (response) => respondToDialog(response, () => {
39606
+ input.disabled = true;
39607
+ elements.dialogActions.querySelectorAll("button").forEach((button) => { button.disabled = true; });
39608
+ });
39609
+ const submitInput = () => respondToInput({ value: input.value });
39610
+ activeDialogCancel = () => respondToInput({ cancelled: true });
39611
+ input.addEventListener("keydown", (event) => {
39612
+ const intent = dialogInputEnterIntent(event);
39613
+ if (intent === "ignore") return;
39614
+ event.preventDefault();
39615
+ event.stopPropagation();
39616
+ if (intent === "submit") submitInput();
39617
+ });
39618
+ addDialogButton("Cancel", () => respondToInput({ cancelled: true }));
39619
+ addDialogButton("Submit", submitInput, "primary");
36751
39620
  setTimeout(() => input.focus(), 0);
36752
39621
  } else if (isWorkflowScriptPreview) {
36753
- renderWorkflowScriptPreview(request);
39622
+ renderWorkflowScriptPreview(request, respondToDialog);
36754
39623
  } else if (request.method === "editor") {
36755
39624
  const textarea = make("textarea", "dialog-editor");
36756
39625
  textarea.value = request.prefill || "";
36757
39626
  elements.dialogBody.append(textarea);
36758
39627
  addDialogButton("Cancel", cancel);
36759
- addDialogButton("Submit", () => sendDialogResponse({ type: "extension_ui_response", id: request.id, value: textarea.value, tabId: request.tabId }), "primary");
39628
+ addDialogButton("Submit", () => respondToDialog({ value: textarea.value }), "primary");
36760
39629
  setTimeout(() => textarea.focus(), 0);
36761
39630
  }
36762
39631
 
36763
39632
  elements.dialog.showModal();
36764
39633
  }
36765
39634
 
39635
+ elements.dialog.addEventListener("cancel", cancelActiveExtensionDialog);
39636
+
36766
39637
  function supervisorEventEnvelope(event, fallbackTabId = activeTabId) {
36767
39638
  if (!event || typeof event !== "object") return null;
36768
39639
  const fields = ["supervisorScopeId", "supervisorEpoch", "supervisorSeq"];
@@ -36896,8 +39767,7 @@ function handleEvent(event) {
36896
39767
  switch (event.type) {
36897
39768
  case "webui_connected": {
36898
39769
  const connectedTabId = event.tabId || activeTabId;
36899
- featureCategoryByTab.delete(connectedTabId);
36900
- if (connectedTabId === activeTabId) renderFeatureCategoryTag(connectedTabId);
39770
+ clearFeatureDecisionStateForTab(connectedTabId, { render: true });
36901
39771
  acceptOutputModeAcknowledgement(event);
36902
39772
  setWebuiVersion(event.version);
36903
39773
  setPiVersion(event.piVersion);
@@ -37350,6 +40220,11 @@ elements.skillEditorDialog?.addEventListener("keydown", (event) => {
37350
40220
  if (!elements.skillEditorSaveButton?.disabled) saveSkillEditor();
37351
40221
  });
37352
40222
  elements.skillEditorDialog?.querySelector("form")?.addEventListener("submit", (event) => event.preventDefault());
40223
+ elements.featureCategoryTag?.addEventListener("click", openFeatureDecisionDialog);
40224
+ elements.featureDecisionDialog?.addEventListener("close", () => {
40225
+ featureDecisionDialogTabId = null;
40226
+ if (elements.featureDecisionDialogOutput) elements.featureDecisionDialogOutput.textContent = "";
40227
+ });
37353
40228
  elements.sendFeedbackButton.addEventListener("click", () => submitQueuedActionFeedback());
37354
40229
  elements.composer.addEventListener("submit", (event) => {
37355
40230
  event.preventDefault();
@@ -37659,6 +40534,18 @@ elements.statsOverlayCustomDays?.addEventListener("keydown", (event) => {
37659
40534
  event.preventDefault();
37660
40535
  requestStatsOverlayRefresh();
37661
40536
  });
40537
+ elements.statsOverlayTabs?.addEventListener("keydown", (event) => {
40538
+ const index = STATS_OVERLAY_TABS.findIndex((tab) => tab.id === statsOverlayActiveTab);
40539
+ if (index < 0) return;
40540
+ let nextIndex = -1;
40541
+ if (event.key === "ArrowRight" || event.key === "ArrowDown") nextIndex = (index + 1) % STATS_OVERLAY_TABS.length;
40542
+ else if (event.key === "ArrowLeft" || event.key === "ArrowUp") nextIndex = (index - 1 + STATS_OVERLAY_TABS.length) % STATS_OVERLAY_TABS.length;
40543
+ else if (event.key === "Home") nextIndex = 0;
40544
+ else if (event.key === "End") nextIndex = STATS_OVERLAY_TABS.length - 1;
40545
+ if (nextIndex < 0) return;
40546
+ event.preventDefault();
40547
+ activateStatsOverlayTab(STATS_OVERLAY_TABS[nextIndex].id, { focus: true });
40548
+ });
37662
40549
  elements.statsOverlayCloseButton?.addEventListener("click", () => elements.statsOverlayDialog?.close());
37663
40550
  elements.statsOverlayDialog?.querySelector("form")?.addEventListener("submit", (event) => event.preventDefault());
37664
40551
  elements.gitWorkflowSteps.addEventListener("click", (event) => {
@@ -38164,6 +41051,9 @@ if (elements.subagentOpenModeSelect) {
38164
41051
  setSubagentOpenMode(elements.subagentOpenModeSelect.value, { announce: true });
38165
41052
  });
38166
41053
  }
41054
+ elements.subagentsAutoClearButton?.addEventListener("click", () => {
41055
+ setSubagentAutoClearEnabled(!subagentAutoClearEnabled, { announce: true });
41056
+ });
38167
41057
  elements.subagentsClearFinishedButton?.addEventListener("click", () => {
38168
41058
  void clearFinishedSubagentRuns();
38169
41059
  });
@@ -38227,8 +41117,18 @@ elements.piVersionButton?.addEventListener("click", () => {
38227
41117
  openPiReleaseNotes().catch((error) => addEvent(error.message || String(error), "error"));
38228
41118
  });
38229
41119
  elements.webuiVersionButton?.addEventListener("click", () => {
41120
+ openWebuiPackageDialog().catch((error) => addEvent(error.message || String(error), "error"));
41121
+ });
41122
+ elements.piComponentUpdateButton?.addEventListener("click", () => {
41123
+ startComponentUpdate("pi").catch((error) => addEvent(error.message || String(error), "error"));
41124
+ });
41125
+ elements.webuiComponentUpdateButton?.addEventListener("click", () => {
41126
+ startComponentUpdate("webui").catch((error) => addEvent(error.message || String(error), "error"));
41127
+ });
41128
+ elements.webuiPackageNpmButton?.addEventListener("click", () => {
38230
41129
  confirmOpenWebuiNpmPage().catch((error) => addEvent(error.message || String(error), "error"));
38231
41130
  });
41131
+ elements.webuiPackageCloseButton?.addEventListener("click", () => elements.webuiPackageDialog?.close());
38232
41132
  elements.piReleaseNotesCloseButton?.addEventListener("click", () => elements.piReleaseNotesDialog?.close());
38233
41133
  elements.toggleSidePanelButton.addEventListener("click", () => {
38234
41134
  setSidePanelCollapsed(true);
@@ -38521,10 +41421,36 @@ window.addEventListener("beforeunload", persistMobileContinuityState);
38521
41421
  window.addEventListener("storage", (event) => {
38522
41422
  if (event.key === OPTIONAL_FEATURES_STORAGE_KEY) reconcileDisabledOptionalFeaturesFromStorage();
38523
41423
  if (event.key === SIDE_PANEL_SECTION_VISIBILITY_STORAGE_KEY) restoreSidePanelSectionVisibility();
41424
+ if (event.key === SIDE_PANEL_SECTION_ORDER_STORAGE_KEY) restoreSidePanelSectionOrder();
41425
+ if (event.key === COMPOSER_ACTION_ORDER_STORAGE_KEY) restoreComposerActionOrder();
41426
+ if (event.key === COMPOSER_ACTION_LAYOUT_STORAGE_KEY) restoreComposerActionSlotLayout();
38524
41427
  if (event.key === SIDE_PANEL_WIDTH_STORAGE_KEY) {
38525
41428
  const width = readStoredSidePanelWidth();
38526
41429
  if (width && !isSidePanelOverlayView()) applySidePanelWidth(width);
38527
41430
  }
41431
+ // Another same-origin tab already saved these durable fields, so receiving
41432
+ // tabs only adopt the shared local cache without repeating the server write.
41433
+ if (event.key === SIDE_PANEL_SECTION_STORAGE_KEY) restoreSidePanelSectionState();
41434
+ if (event.key === SIDE_PANEL_STORAGE_KEY) restoreSidePanelState();
41435
+ if (event.key === TERMINAL_TABS_LAYOUT_STORAGE_KEY) restoreTerminalTabsLayoutSetting();
41436
+ if (event.key === TERMINAL_CUSTOM_GROUPS_STORAGE_KEY) {
41437
+ restoreTerminalCustomGroups();
41438
+ syncTerminalCustomGroupsWithTabs(tabs, { persist: false });
41439
+ renderTabs();
41440
+ }
41441
+ if (event.key === FOOTER_SCOPED_MODEL_ORDER_STORAGE_KEY) {
41442
+ footerScopedModels = orderedFooterScopedModels();
41443
+ renderFooter();
41444
+ }
41445
+ if (event.key === FILE_VIEWER_WIDTH_STORAGE_KEY) restoreFileViewerWidthPreference();
41446
+ });
41447
+ // Durable layout reconciliation runs on its own foreground/online lifecycle
41448
+ // listeners so retained dirty state retries without changing the existing
41449
+ // transcript/session reconciliation contracts.
41450
+ window.addEventListener("online", () => reconcileDurableUiLayout());
41451
+ window.addEventListener("pageshow", () => reconcileDurableUiLayout());
41452
+ document.addEventListener("visibilitychange", () => {
41453
+ if (document.visibilityState === "visible") reconcileDurableUiLayout();
38528
41454
  });
38529
41455
  window.addEventListener("resize", syncResizablePanelWidthsForViewport, { passive: true });
38530
41456
  window.addEventListener("keydown", (event) => {
@@ -38913,6 +41839,7 @@ elements.promptInput.addEventListener("blur", () => {
38913
41839
  installModalPrimitives();
38914
41840
  initializeIssueWizard();
38915
41841
  resizePromptInput();
41842
+ restoreDurableUiLayoutPendingJournal();
38916
41843
  restoreSidePanelWidthPreference();
38917
41844
  restoreFileViewerWidthPreference();
38918
41845
  focusPromptInput({ defer: true });
@@ -38938,11 +41865,14 @@ restoreAgentDoneNotificationsSetting();
38938
41865
  restoreThinkingVisibilitySetting();
38939
41866
  restoreTerminalTabsLayoutSetting();
38940
41867
  restoreSubagentOpenModeSetting();
41868
+ restoreSubagentAutoClearSetting();
38941
41869
  restoreTerminalCustomGroups();
38942
41870
  restoreToolOutputExpansionSetting();
38943
41871
  restoreWorkspaceDashboardState();
38944
41872
  restoreInterfaceDensity();
38945
41873
  initializeTerminalHeaderTooltips();
41874
+ initializeComposerActionOrdering();
41875
+ restoreSidePanelSectionOrder();
38946
41876
  restoreSidePanelSectionVisibility();
38947
41877
  restoreSidePanelSectionState();
38948
41878
  bindSidePanelSectionToggles();