@firstpick/pi-package-webui 0.8.1 → 0.8.2

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 (32) hide show
  1. package/README.md +12 -0
  2. package/bin/pi-webui.mjs +190 -20
  3. package/lib/component-update-state.mjs +126 -0
  4. package/lib/trust-boundaries.mjs +1 -0
  5. package/package.json +1 -1
  6. package/public/app.js +1454 -101
  7. package/public/index.html +155 -27
  8. package/public/service-worker.js +1 -1
  9. package/public/styles.css +731 -2
  10. package/tests/boot-failure-diagnostics.test.mjs +63 -5
  11. package/tests/browser/control-deck-component-updates.spec.mjs +180 -0
  12. package/tests/browser/interaction-continuity.spec.mjs +158 -0
  13. package/tests/browser/mobile-foundation.spec.mjs +11 -0
  14. package/tests/browser/side-panel-section-reorder.spec.mjs +101 -0
  15. package/tests/browser/stats-overlay.spec.mjs +265 -0
  16. package/tests/codex-fast-mode-static.test.mjs +2 -2
  17. package/tests/component-update-api-static.test.mjs +67 -0
  18. package/tests/component-update-state.test.mjs +80 -0
  19. package/tests/control-deck-component-updates-static.test.mjs +251 -0
  20. package/tests/fast-mode-client-static.test.mjs +1 -1
  21. package/tests/fixtures/fake-pi.mjs +129 -5
  22. package/tests/footer-provider-usage-visual-static.test.mjs +71 -0
  23. package/tests/interaction-state-stability-static.test.mjs +21 -4
  24. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  25. package/tests/mobile-foundation-static.test.mjs +6 -4
  26. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  27. package/tests/mobile-static.test.mjs +2 -1
  28. package/tests/native-parity-harness.test.mjs +2 -0
  29. package/tests/open-issue-wizard-static.test.mjs +1 -1
  30. package/tests/side-panel-section-reorder-static.test.mjs +68 -0
  31. package/tests/sse-backpressure-harness.test.mjs +51 -12
  32. package/tests/stats-dashboard-static.test.mjs +266 -0
package/public/app.js CHANGED
@@ -388,6 +388,16 @@ const elements = {
388
388
  piReleaseNotesBody: $("#piReleaseNotesBody"),
389
389
  piReleaseNotesGithubLink: $("#piReleaseNotesGithubLink"),
390
390
  piReleaseNotesCloseButton: $("#piReleaseNotesCloseButton"),
391
+ piComponentUpdateStatus: $("#piComponentUpdateStatus"),
392
+ piComponentUpdateButton: $("#piComponentUpdateButton"),
393
+ webuiPackageDialog: $("#webuiPackageDialog"),
394
+ webuiPackageTitle: $("#webuiPackageTitle"),
395
+ webuiPackageCurrentVersion: $("#webuiPackageCurrentVersion"),
396
+ webuiPackageLatestVersion: $("#webuiPackageLatestVersion"),
397
+ webuiPackageNpmButton: $("#webuiPackageNpmButton"),
398
+ webuiPackageCloseButton: $("#webuiPackageCloseButton"),
399
+ webuiComponentUpdateStatus: $("#webuiComponentUpdateStatus"),
400
+ webuiComponentUpdateButton: $("#webuiComponentUpdateButton"),
391
401
  dialog: $("#extensionDialog"),
392
402
  dialogTitle: $("#dialogTitle"),
393
403
  dialogMessage: $("#dialogMessage"),
@@ -480,6 +490,9 @@ let fileViewerSearchTimer = null;
480
490
  let fileViewerSearchHighlightElement = null;
481
491
  let fileContextMenuState = null;
482
492
  let sidePanelContextMenuState = null;
493
+ let sidePanelSectionPointerDrag = null;
494
+ let sidePanelSectionLastDragOverKey = "";
495
+ let sidePanelSectionSuppressClickUntil = 0;
483
496
  let fileTreeDragState = null;
484
497
  let fileViewerResizeState = null;
485
498
  let sidePanelResizeState = null;
@@ -686,6 +699,8 @@ let updateRequestInProgress = false;
686
699
  let latestUpdateStatus = null;
687
700
  let updateStatusRefreshTimer = null;
688
701
  let updateNotificationHideTimer = null;
702
+ let componentUpdatePollTimer = null;
703
+ let componentUpdateStartInProgress = false;
689
704
  let backendOfflineNoticeShown = false;
690
705
  let latestMessages = [];
691
706
  let latestMessagesSessionKey = "";
@@ -792,6 +807,8 @@ const SIDE_PANEL_STORAGE_KEY = "pi-webui-side-panel-collapsed";
792
807
  const INTERFACE_DENSITY_STORAGE_KEY = "pi-webui-interface-density";
793
808
  const SIDE_PANEL_SECTION_STORAGE_KEY = "pi-webui-side-panel-sections-collapsed";
794
809
  const SIDE_PANEL_SECTION_VISIBILITY_STORAGE_KEY = "pi-webui-side-panel-sections-hidden";
810
+ const SIDE_PANEL_SECTION_ORDER_STORAGE_KEY = "pi-webui-side-panel-section-order-v1";
811
+ const SIDE_PANEL_SECTION_POINTER_DRAG_THRESHOLD_PX = 6;
795
812
  const TAB_STORAGE_KEY = "pi-webui-active-tab";
796
813
  const PATH_FAST_PICKS_STORAGE_KEY = "pi-webui-path-fast-picks";
797
814
  const AGENT_DONE_NOTIFICATIONS_STORAGE_KEY = "pi-webui-agent-done-notifications";
@@ -981,6 +998,7 @@ const SUBAGENTS_IDLE_REFRESH_MS = 4000;
981
998
  const SUBAGENTS_HIDDEN_REFRESH_MS = 10_000;
982
999
  const SUBAGENT_OVERLAY_REFRESH_MS = 1000;
983
1000
  const UPDATE_STATUS_REFRESH_MS = 6 * 60 * 60 * 1000;
1001
+ const COMPONENT_UPDATE_POLL_MS = 1000;
984
1002
  const UPDATE_STATUS_INITIAL_DELAY_MS = 1800;
985
1003
  const RUN_INDICATOR_TICK_MS = 1000;
986
1004
  const RUN_INDICATOR_START_GRACE_MS = 2500;
@@ -3382,6 +3400,131 @@ function sidePanelSectionRecords() {
3382
3400
  .filter((record) => record.id && record.button && record.content);
3383
3401
  }
3384
3402
 
3403
+ function readStoredSidePanelSectionOrder() {
3404
+ try {
3405
+ const parsed = JSON.parse(localStorage.getItem(SIDE_PANEL_SECTION_ORDER_STORAGE_KEY) || "[]");
3406
+ return Array.isArray(parsed) ? [...new Set(parsed.filter((id) => typeof id === "string" && id.trim()))] : [];
3407
+ } catch {
3408
+ return [];
3409
+ }
3410
+ }
3411
+
3412
+ function persistSidePanelSectionOrder() {
3413
+ try {
3414
+ localStorage.setItem(SIDE_PANEL_SECTION_ORDER_STORAGE_KEY, JSON.stringify(sidePanelSectionRecords().map(({ id }) => id)));
3415
+ } catch {
3416
+ // Ignore storage failures; ordering should still work for this page load.
3417
+ }
3418
+ }
3419
+
3420
+ function restoreSidePanelSectionOrder() {
3421
+ if (sidePanelSectionPointerDrag?.active) return;
3422
+ const records = sidePanelSectionRecords();
3423
+ const parent = records[0]?.section.parentElement;
3424
+ if (!parent || records.some(({ section }) => section.parentElement !== parent)) return;
3425
+ const rank = new Map(readStoredSidePanelSectionOrder().map((id, index) => [id, index]));
3426
+ records.sort((a, b) => {
3427
+ const aRank = rank.has(a.id) ? rank.get(a.id) : Number.MAX_SAFE_INTEGER;
3428
+ const bRank = rank.has(b.id) ? rank.get(b.id) : Number.MAX_SAFE_INTEGER;
3429
+ return aRank - bRank;
3430
+ });
3431
+ for (const { section } of records) parent.append(section);
3432
+ }
3433
+
3434
+ function visibleSidePanelSectionRecords() {
3435
+ return sidePanelSectionRecords().filter(({ section }) => !section.hidden);
3436
+ }
3437
+
3438
+ function clearSidePanelSectionDragMarkers() {
3439
+ for (const { section } of sidePanelSectionRecords()) {
3440
+ section.classList.remove("drag-over-before", "drag-over-after");
3441
+ }
3442
+ }
3443
+
3444
+ function moveSidePanelSectionRelative(fromId, targetRecord, insertBefore) {
3445
+ const sourceRecord = sidePanelSectionRecords().find(({ id }) => id === fromId);
3446
+ if (!sourceRecord || !targetRecord || sourceRecord.section === targetRecord.section) return false;
3447
+ const parent = sourceRecord.section.parentElement;
3448
+ if (!parent || targetRecord.section.parentElement !== parent) return false;
3449
+ clearSidePanelSectionDragMarkers();
3450
+ targetRecord.section.classList.add(insertBefore ? "drag-over-before" : "drag-over-after");
3451
+ sidePanelSectionLastDragOverKey = `${targetRecord.id}:${insertBefore ? "before" : "after"}`;
3452
+ if (insertBefore) parent.insertBefore(sourceRecord.section, targetRecord.section);
3453
+ else parent.insertBefore(sourceRecord.section, targetRecord.section.nextSibling);
3454
+ persistSidePanelSectionOrder();
3455
+ return true;
3456
+ }
3457
+
3458
+ function moveSidePanelSectionByOffset(sectionId, offset) {
3459
+ const records = visibleSidePanelSectionRecords();
3460
+ const fromIndex = records.findIndex(({ id }) => id === sectionId);
3461
+ const toIndex = fromIndex + offset;
3462
+ if (fromIndex < 0 || toIndex < 0 || toIndex >= records.length) return false;
3463
+ const targetRecord = records[toIndex];
3464
+ const moved = moveSidePanelSectionRelative(sectionId, targetRecord, offset < 0);
3465
+ clearSidePanelSectionDragMarkers();
3466
+ if (moved) queueMicrotask(() => sidePanelSectionRecords().find(({ id }) => id === sectionId)?.button.focus({ preventScroll: true }));
3467
+ return moved;
3468
+ }
3469
+
3470
+ function sidePanelSectionToggleFromPoint(clientX, clientY) {
3471
+ return document.elementFromPoint(clientX, clientY)?.closest?.("[data-side-panel-section-toggle]") || null;
3472
+ }
3473
+
3474
+ function beginSidePanelSectionPointerDrag(event, sectionId) {
3475
+ if (event.button !== 0 || !sectionId || sidePanelSectionPointerDrag) return;
3476
+ sidePanelSectionPointerDrag = { sectionId, pointerId: event.pointerId, startX: event.clientX, startY: event.clientY, active: false };
3477
+ window.addEventListener("pointermove", updateSidePanelSectionPointerDrag, { capture: true });
3478
+ window.addEventListener("pointerup", endSidePanelSectionPointerDrag, { capture: true });
3479
+ window.addEventListener("pointercancel", endSidePanelSectionPointerDrag, { capture: true });
3480
+ }
3481
+
3482
+ function updateSidePanelSectionPointerDrag(event) {
3483
+ const drag = sidePanelSectionPointerDrag;
3484
+ if (!drag || drag.pointerId !== event.pointerId) return;
3485
+ const distance = Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY);
3486
+ if (!drag.active && distance < SIDE_PANEL_SECTION_POINTER_DRAG_THRESHOLD_PX) return;
3487
+ event.preventDefault();
3488
+ if (!drag.active) {
3489
+ drag.active = true;
3490
+ sidePanelSectionLastDragOverKey = "";
3491
+ clearTimeout(pointerActivationTimeout);
3492
+ pointerActivationTimeout = null;
3493
+ activePointerActivation = null;
3494
+ const sourceRecord = sidePanelSectionRecords().find(({ id }) => id === drag.sectionId);
3495
+ sourceRecord?.section.classList.add("dragging");
3496
+ }
3497
+ const targetToggle = sidePanelSectionToggleFromPoint(event.clientX, event.clientY);
3498
+ const targetRecord = targetToggle
3499
+ ? sidePanelSectionRecords().find(({ button }) => button === targetToggle)
3500
+ : null;
3501
+ if (!targetRecord || targetRecord.id === drag.sectionId || targetRecord.section.hidden) return;
3502
+ const rect = targetToggle.getBoundingClientRect();
3503
+ const insertBefore = event.clientY < rect.top + rect.height / 2;
3504
+ const markerKey = `${targetRecord.id}:${insertBefore ? "before" : "after"}`;
3505
+ if (markerKey === sidePanelSectionLastDragOverKey) return;
3506
+ moveSidePanelSectionRelative(drag.sectionId, targetRecord, insertBefore);
3507
+ }
3508
+
3509
+ function endSidePanelSectionPointerDrag(event) {
3510
+ const drag = sidePanelSectionPointerDrag;
3511
+ if (!drag || drag.pointerId !== event.pointerId) return;
3512
+ window.removeEventListener("pointermove", updateSidePanelSectionPointerDrag, { capture: true });
3513
+ window.removeEventListener("pointerup", endSidePanelSectionPointerDrag, { capture: true });
3514
+ window.removeEventListener("pointercancel", endSidePanelSectionPointerDrag, { capture: true });
3515
+ const sourceRecord = sidePanelSectionRecords().find(({ id }) => id === drag.sectionId);
3516
+ sidePanelSectionPointerDrag = null;
3517
+ sidePanelSectionLastDragOverKey = "";
3518
+ clearSidePanelSectionDragMarkers();
3519
+ sourceRecord?.section.classList.remove("dragging");
3520
+ if (drag.active) {
3521
+ sidePanelSectionSuppressClickUntil = Date.now() + 250;
3522
+ event.preventDefault();
3523
+ persistSidePanelSectionOrder();
3524
+ queueMicrotask(() => sourceRecord?.button.focus({ preventScroll: true }));
3525
+ }
3526
+ }
3527
+
3385
3528
  function readStoredSidePanelSectionCollapsedIds() {
3386
3529
  try {
3387
3530
  const stored = localStorage.getItem(SIDE_PANEL_SECTION_STORAGE_KEY);
@@ -3450,7 +3593,7 @@ function setSidePanelSectionCollapsed(record, collapsed, { persist = true } = {}
3450
3593
  record.content.hidden = collapsed;
3451
3594
  record.button.setAttribute("aria-expanded", collapsed ? "false" : "true");
3452
3595
  record.button.setAttribute("aria-label", `${collapsed ? "Expand" : "Collapse"} ${label} section`);
3453
- record.button.setAttribute("title", `${collapsed ? "Expand" : "Collapse"} ${label} section`);
3596
+ record.button.setAttribute("title", `${collapsed ? "Expand" : "Collapse"} ${label} section · drag to reorder · Alt+↑/↓ moves`);
3454
3597
  if (!collapsed && record.id === "git" && !record.section.hidden) {
3455
3598
  queueMicrotask(() => {
3456
3599
  renderGitPanel();
@@ -3532,13 +3675,23 @@ function showSidePanelContextMenu(event) {
3532
3675
 
3533
3676
  function bindSidePanelSectionToggles() {
3534
3677
  for (const record of sidePanelSectionRecords()) {
3535
- record.button.addEventListener("click", () => {
3678
+ record.button.addEventListener("click", (event) => {
3679
+ if (Date.now() < sidePanelSectionSuppressClickUntil) {
3680
+ event.preventDefault();
3681
+ return;
3682
+ }
3536
3683
  if (record.section.classList.contains("collapsed")) {
3537
3684
  setOnlySidePanelSectionExpanded(record);
3538
3685
  } else {
3539
3686
  setSidePanelSectionCollapsed(record, true);
3540
3687
  }
3541
3688
  });
3689
+ record.button.addEventListener("keydown", (event) => {
3690
+ if (!event.altKey || (event.key !== "ArrowUp" && event.key !== "ArrowDown")) return;
3691
+ event.preventDefault();
3692
+ moveSidePanelSectionByOffset(record.id, event.key === "ArrowUp" ? -1 : 1);
3693
+ });
3694
+ record.button.addEventListener("pointerdown", (event) => beginSidePanelSectionPointerDrag(event, record.id));
3542
3695
  }
3543
3696
  }
3544
3697
 
@@ -6111,9 +6264,14 @@ function renderPiVersionButton() {
6111
6264
  const label = formatWebuiVersion(piVersion);
6112
6265
  button.hidden = !label;
6113
6266
  button.textContent = label ? `Pi ${label}` : "";
6267
+ const state = componentUpdateTagState("pi");
6268
+ const stateText = componentUpdateTagStateText(state);
6269
+ if (state) button.dataset.updateState = state;
6270
+ else delete button.dataset.updateState;
6114
6271
  if (label) {
6115
- button.title = `View Pi ${label} release notes`;
6116
- button.setAttribute("aria-label", `View Pi ${label} release notes`);
6272
+ const base = `View Pi ${label} release notes`;
6273
+ button.title = stateText ? `${base} — ${stateText}` : base;
6274
+ button.setAttribute("aria-label", stateText ? `${base}, ${stateText}` : base);
6117
6275
  }
6118
6276
  }
6119
6277
 
@@ -6123,9 +6281,14 @@ function renderWebuiVersionButton() {
6123
6281
  const label = formatWebuiVersion(webuiVersion);
6124
6282
  button.hidden = !label;
6125
6283
  button.textContent = label ? `Web UI ${label}` : "";
6284
+ const state = componentUpdateTagState("webui");
6285
+ const stateText = componentUpdateTagStateText(state);
6286
+ if (state) button.dataset.updateState = state;
6287
+ else delete button.dataset.updateState;
6126
6288
  if (label) {
6127
- button.title = `Open Pi Web UI ${label} on npm`;
6128
- button.setAttribute("aria-label", `Open Pi Web UI ${label} package page`);
6289
+ const base = `Open Pi Web UI ${label} package and update details`;
6290
+ button.title = stateText ? `${base} — ${stateText}` : base;
6291
+ button.setAttribute("aria-label", stateText ? `${base}, ${stateText}` : base);
6129
6292
  }
6130
6293
  }
6131
6294
 
@@ -6217,7 +6380,9 @@ async function openPiReleaseNotes() {
6217
6380
  elements.piReleaseNotesBody.setAttribute("aria-busy", "true");
6218
6381
  elements.piReleaseNotesBody.replaceChildren(make("p", "muted", "Loading…"));
6219
6382
  setPiReleaseNotesLink(piReleasePageUrl(requestedVersion));
6383
+ renderComponentUpdateDialogs();
6220
6384
  if (!dialog.open) dialog.showModal();
6385
+ refreshUpdateStatus({ notify: false }).catch((error) => addEvent(`Pi/Web UI update check failed: ${error.message || String(error)}`, "warn"));
6221
6386
 
6222
6387
  try {
6223
6388
  const response = await api("/api/pi-release-notes", { scoped: false });
@@ -6348,6 +6513,9 @@ async function refreshUpdateStatus({ force = false, notify = true } = {}) {
6348
6513
  const response = await api(path, { scoped: false });
6349
6514
  latestUpdateStatus = response.data || null;
6350
6515
  if (notify) renderUpdateNotification(latestUpdateStatus);
6516
+ renderComponentUpdateIndicators();
6517
+ renderComponentUpdateDialogs();
6518
+ syncComponentUpdatePolling();
6351
6519
  return latestUpdateStatus;
6352
6520
  }
6353
6521
 
@@ -6360,6 +6528,189 @@ function scheduleUpdateStatusRefresh() {
6360
6528
  }, UPDATE_STATUS_REFRESH_MS);
6361
6529
  }
6362
6530
 
6531
+ const COMPONENT_UPDATE_TARGETS = ["pi", "webui"];
6532
+
6533
+ function componentUpdateLabel(target) {
6534
+ return target === "pi" ? "Pi" : "Web UI";
6535
+ }
6536
+
6537
+ function componentUpdateJob(target) {
6538
+ const job = latestUpdateStatus?.componentUpdates?.[target];
6539
+ return job && typeof job === "object" ? job : null;
6540
+ }
6541
+
6542
+ function componentUpdateTagState(target) {
6543
+ const job = componentUpdateJob(target);
6544
+ if (job?.state === "running") return "running";
6545
+ if (job?.state === "failed") return "failed";
6546
+ if (job?.state === "succeeded") return "succeeded";
6547
+ if (latestUpdateStatus?.[target]?.updateAvailable) return "available";
6548
+ return "";
6549
+ }
6550
+
6551
+ function componentUpdateTagStateText(state) {
6552
+ switch (state) {
6553
+ case "running": return "update running";
6554
+ case "failed": return "update failed";
6555
+ case "succeeded": return "update succeeded";
6556
+ case "available": return "update available";
6557
+ default: return "";
6558
+ }
6559
+ }
6560
+
6561
+ function anyComponentUpdateRunning() {
6562
+ return COMPONENT_UPDATE_TARGETS.some((target) => componentUpdateJob(target)?.state === "running");
6563
+ }
6564
+
6565
+ function renderComponentUpdateIndicators() {
6566
+ renderPiVersionButton();
6567
+ renderWebuiVersionButton();
6568
+ }
6569
+
6570
+ function componentUpdateStatusText(target) {
6571
+ const label = componentUpdateLabel(target);
6572
+ const job = componentUpdateJob(target);
6573
+ const pkg = latestUpdateStatus?.[target] || {};
6574
+ const current = formatWebuiVersion(pkg.currentVersion || (target === "pi" ? piVersion : webuiVersion) || "");
6575
+ const latest = formatWebuiVersion(pkg.latestVersion || "");
6576
+ if (job?.state === "running") return { text: job.message || `Updating ${label}…`, level: "warn" };
6577
+ if (job?.state === "succeeded") {
6578
+ const activation = target === "pi"
6579
+ ? "New or reloaded Pi sessions use the update; already-running tabs keep their current runtime until restarted."
6580
+ : "Restart the Web UI server to use the update; it is not restarted automatically.";
6581
+ return { text: `${job.message || `${label} update completed.`} ${activation}`, level: "success" };
6582
+ }
6583
+ if (job?.state === "failed") {
6584
+ const detail = job.error ? ` ${job.error}` : "";
6585
+ return { text: `${job.message || `${label} update failed.`}${detail} You can retry the update.`, level: "error" };
6586
+ }
6587
+ const availability = pkg.updateAvailable
6588
+ ? (latest ? `${label} ${current || "current"} → ${latest} is available.` : `${label} update is available.`)
6589
+ : "";
6590
+ if (job && job.canStart === false && job.unavailableReason) {
6591
+ return { text: [availability, job.unavailableReason].filter(Boolean).join(" "), level: "warn" };
6592
+ }
6593
+ if (availability) return { text: availability, level: "info" };
6594
+ if (pkg.checked && latest) return { text: `${label} is up to date.`, level: "info" };
6595
+ if (pkg.skippedReason) return { text: `Update check skipped: ${pkg.skippedReason}.`, level: "info" };
6596
+ return { text: "", level: "info" };
6597
+ }
6598
+
6599
+ function componentUpdateButtonState(target) {
6600
+ const label = componentUpdateLabel(target);
6601
+ const job = componentUpdateJob(target);
6602
+ const pkg = latestUpdateStatus?.[target] || {};
6603
+ if (job?.state === "running") return { disabled: true, label: "Updating…" };
6604
+ if (job && job.canStart === false) return { disabled: true, label: `Update ${label}` };
6605
+ if (componentUpdateStartInProgress || updateRequestInProgress || latestUpdateStatus?.updateInProgress || anyComponentUpdateRunning()) {
6606
+ return { disabled: true, label: `Update ${label}` };
6607
+ }
6608
+ if (job?.state === "failed") return { disabled: false, label: `Retry ${label} update` };
6609
+ if (pkg.checked && !pkg.updateAvailable) return { disabled: true, label: "Up to date" };
6610
+ return { disabled: false, label: `Update ${label}` };
6611
+ }
6612
+
6613
+ function renderComponentUpdatePanel(target, statusElement, buttonElement) {
6614
+ if (!statusElement || !buttonElement) return;
6615
+ const { text, level } = componentUpdateStatusText(target);
6616
+ statusElement.hidden = false;
6617
+ statusElement.textContent = text;
6618
+ statusElement.dataset.level = level;
6619
+ const buttonState = componentUpdateButtonState(target);
6620
+ buttonElement.disabled = buttonState.disabled;
6621
+ buttonElement.textContent = buttonState.label;
6622
+ }
6623
+
6624
+ function renderComponentUpdateDialogs() {
6625
+ renderComponentUpdatePanel("pi", elements.piComponentUpdateStatus, elements.piComponentUpdateButton);
6626
+ const pkg = latestUpdateStatus?.webui || {};
6627
+ if (elements.webuiPackageCurrentVersion) {
6628
+ elements.webuiPackageCurrentVersion.textContent = formatWebuiVersion(pkg.currentVersion || webuiVersion || "") || "Unknown";
6629
+ }
6630
+ if (elements.webuiPackageLatestVersion) {
6631
+ elements.webuiPackageLatestVersion.textContent = formatWebuiVersion(pkg.latestVersion || "") || (pkg.checked ? "Unknown" : "Not checked");
6632
+ }
6633
+ renderComponentUpdatePanel("webui", elements.webuiComponentUpdateStatus, elements.webuiComponentUpdateButton);
6634
+ }
6635
+
6636
+ function syncComponentUpdatePolling() {
6637
+ if (anyComponentUpdateRunning()) {
6638
+ if (componentUpdatePollTimer === null) {
6639
+ componentUpdatePollTimer = setTimeout(() => {
6640
+ componentUpdatePollTimer = null;
6641
+ refreshUpdateStatus({ notify: false }).catch((error) => {
6642
+ addEvent(`Component update status check failed: ${error.message || String(error)}`, "warn");
6643
+ if (anyComponentUpdateRunning()) syncComponentUpdatePolling();
6644
+ });
6645
+ }, COMPONENT_UPDATE_POLL_MS);
6646
+ }
6647
+ } else if (componentUpdatePollTimer !== null) {
6648
+ clearTimeout(componentUpdatePollTimer);
6649
+ componentUpdatePollTimer = null;
6650
+ }
6651
+ }
6652
+
6653
+ function componentUpdateConfirmationText(target) {
6654
+ const pkg = latestUpdateStatus?.[target] || {};
6655
+ const versionText = pkg.updateAvailable ? `\n\nDetected update: ${packageUpdateText(componentUpdateLabel(target), pkg)}.` : "";
6656
+ if (target === "pi") {
6657
+ 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.`;
6658
+ }
6659
+ 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.`;
6660
+ }
6661
+
6662
+ async function startComponentUpdate(target) {
6663
+ if (componentUpdateStartInProgress) return;
6664
+ const label = componentUpdateLabel(target);
6665
+ const job = componentUpdateJob(target);
6666
+ if (job?.state === "running" || anyComponentUpdateRunning() || updateRequestInProgress || latestUpdateStatus?.updateInProgress) return;
6667
+ if (job && job.canStart === false) {
6668
+ addEvent(job.unavailableReason || `${label} update is currently unavailable.`, "warn");
6669
+ renderComponentUpdateDialogs();
6670
+ return;
6671
+ }
6672
+ const confirmed = await appConfirmText(componentUpdateConfirmationText(target), {
6673
+ affected: target === "pi" ? "The Pi installation on the Web UI host" : "The Web UI package installation on this host",
6674
+ confirmLabel: job?.state === "failed" ? `Retry ${label} update` : `Update ${label}`,
6675
+ danger: false,
6676
+ });
6677
+ if (!confirmed) return;
6678
+ componentUpdateStartInProgress = true;
6679
+ renderComponentUpdateDialogs();
6680
+ try {
6681
+ const response = await api("/api/component-update", { method: "POST", body: { target }, scoped: false });
6682
+ const accepted = response?.data;
6683
+ if (accepted && typeof accepted === "object") {
6684
+ latestUpdateStatus = {
6685
+ ...(latestUpdateStatus || {}),
6686
+ updateInProgress: true,
6687
+ componentUpdates: { ...(latestUpdateStatus?.componentUpdates || {}), [target]: accepted },
6688
+ };
6689
+ }
6690
+ addEvent(`${label} update started in the background`, "info");
6691
+ } catch (error) {
6692
+ addEvent(error.message || String(error), "error");
6693
+ if (error?.statusCode === 409) await refreshUpdateStatus({ notify: false }).catch(() => {});
6694
+ } finally {
6695
+ componentUpdateStartInProgress = false;
6696
+ renderComponentUpdateIndicators();
6697
+ renderComponentUpdateDialogs();
6698
+ syncComponentUpdatePolling();
6699
+ }
6700
+ }
6701
+
6702
+ async function openWebuiPackageDialog() {
6703
+ const dialog = elements.webuiPackageDialog;
6704
+ if (!dialog) return;
6705
+ renderComponentUpdateDialogs();
6706
+ if (!dialog.open) dialog.showModal();
6707
+ try {
6708
+ await refreshUpdateStatus({ notify: false });
6709
+ } catch (error) {
6710
+ addEvent(`Pi/Web UI update check failed: ${error.message || String(error)}`, "warn");
6711
+ }
6712
+ }
6713
+
6363
6714
  function initializeUpdateNotifications() {
6364
6715
  setTimeout(() => {
6365
6716
  refreshUpdateStatus().catch((error) => addEvent(`Pi/Web UI update check failed: ${error.message || String(error)}`, "warn"));
@@ -13848,6 +14199,27 @@ function applyFooterContextUsage(node, contextUsage) {
13848
14199
  return node;
13849
14200
  }
13850
14201
 
14202
+ // Dedicated Usage visual apply path: sets two independent lane widths (top =
14203
+ // primary/first window, bottom = secondary/second window) plus a max-window
14204
+ // active foreground/glow reusing the Context color interpolation. Clamps
14205
+ // defensively to 0..100; exact text and tooltip remain untouched.
14206
+ function applyFooterUsageWindows(node, usageWindows) {
14207
+ node.classList.add("footer-usage-card");
14208
+ const primaryPercent = typeof usageWindows?.primaryPercent === "number" ? usageWindows.primaryPercent : Number.NaN;
14209
+ const secondaryPercent = typeof usageWindows?.secondaryPercent === "number" ? usageWindows.secondaryPercent : Number.NaN;
14210
+ if (Number.isFinite(primaryPercent) && Number.isFinite(secondaryPercent)) {
14211
+ const clampedPrimary = Math.min(100, Math.max(0, primaryPercent));
14212
+ const clampedSecondary = Math.min(100, Math.max(0, secondaryPercent));
14213
+ const activeColor = contextUsageActiveColor(Math.max(clampedPrimary, clampedSecondary));
14214
+ node.classList.add("has-usage-windows");
14215
+ node.style.setProperty("--usage-primary", `${clampedPrimary.toFixed(1)}%`);
14216
+ node.style.setProperty("--usage-secondary", `${clampedSecondary.toFixed(1)}%`);
14217
+ node.style.setProperty("--usage-active-color", activeColor.color);
14218
+ node.style.setProperty("--usage-active-glow", activeColor.glow);
14219
+ }
14220
+ return node;
14221
+ }
14222
+
13851
14223
  const FOOTER_MIDDLE_TRUNCATION_END_CHARS = 16;
13852
14224
  const FOOTER_MIDDLE_TRUNCATION_MIN_START_CHARS = 6;
13853
14225
 
@@ -13935,6 +14307,7 @@ const GIT_FOOTER_TOOLTIP_COPY = {
13935
14307
  speed: "Assistant streaming speed. Shows live output tokens for the current reply and current or last tokens per second.",
13936
14308
  cost: "Estimated session cost. sub means subscription-backed provider; api means metered API usage.",
13937
14309
  context: "Context window pressure. Shows percent used over the model limit; auto means auto-compaction is enabled.",
14310
+ usage: "Provider subscription usage. Shows the used share of the provider-reported primary and secondary rate windows.",
13938
14311
  cwd: "Active working directory for this Web UI tab.",
13939
14312
  git: "Current Git branch. detached means HEAD is not on a branch; no repo means the cwd is outside a Git work tree.",
13940
14313
  "git-state": "Active Git operation or detached state. Finish or abort rebase/merge/cherry-pick/revert/bisect before normal commits.",
@@ -14313,6 +14686,13 @@ function normalizeFooterPayloadChip(value, index) {
14313
14686
  contextWindow: Number.isFinite(contextWindow) ? contextWindow : 0,
14314
14687
  };
14315
14688
  }
14689
+ if (value.usageWindows && typeof value.usageWindows === "object") {
14690
+ const primaryPercent = typeof value.usageWindows.primaryPercent === "number" ? value.usageWindows.primaryPercent : Number.NaN;
14691
+ const secondaryPercent = typeof value.usageWindows.secondaryPercent === "number" ? value.usageWindows.secondaryPercent : Number.NaN;
14692
+ if (Number.isFinite(primaryPercent) && Number.isFinite(secondaryPercent)) {
14693
+ chip.usageWindows = { primaryPercent, secondaryPercent };
14694
+ }
14695
+ }
14316
14696
  return chip;
14317
14697
  }
14318
14698
 
@@ -14615,7 +14995,9 @@ function renderGitFooterPayloadMetric(chip, payload) {
14615
14995
  const action = piAction || contextAction;
14616
14996
  options.title = gitFooterPayloadTooltip(chip, { action });
14617
14997
  const node = footerMetric(chip.icon || "•", chip.label, chip.value, chip.tone ? `tone-${chip.tone}` : "", options);
14618
- return chip.contextUsage ? applyFooterContextUsage(node, chip.contextUsage) : node;
14998
+ if (chip.contextUsage) applyFooterContextUsage(node, chip.contextUsage);
14999
+ if (chip.usageWindows) applyFooterUsageWindows(node, chip.usageWindows);
15000
+ return node;
14619
15001
  }
14620
15002
 
14621
15003
  function gitFooterSyncOutgoingCount(value) {
@@ -14744,7 +15126,9 @@ function renderGitFooterPayloadMeta(chip, tab, payload) {
14744
15126
  node.setAttribute("aria-haspopup", "listbox");
14745
15127
  node.setAttribute("aria-expanded", footerBranchPickerOpen ? "true" : "false");
14746
15128
  }
14747
- return chip.contextUsage ? applyFooterContextUsage(node, chip.contextUsage) : node;
15129
+ if (chip.contextUsage) applyFooterContextUsage(node, chip.contextUsage);
15130
+ if (chip.usageWindows) applyFooterUsageWindows(node, chip.usageWindows);
15131
+ return node;
14748
15132
  }
14749
15133
 
14750
15134
  // Shape key for a footer chip with the frequently-changing fields removed, so
@@ -14754,10 +15138,17 @@ function gitFooterChipShapeKey(chip) {
14754
15138
  const shape = {};
14755
15139
  for (const [key, value] of Object.entries(chip || {})) {
14756
15140
  if (key === "value") continue;
15141
+ // Usage percentages/reset details make its title dynamic. The fast path
15142
+ // refreshes the complete tooltip and aria-label in place below.
15143
+ if (key === "title" && chip?.key === "usage") continue;
14757
15144
  if (key === "contextUsage") {
14758
15145
  shape.contextUsage = value ? true : false;
14759
15146
  continue;
14760
15147
  }
15148
+ if (key === "usageWindows") {
15149
+ shape.usageWindows = value ? true : false;
15150
+ continue;
15151
+ }
14761
15152
  shape[key] = value;
14762
15153
  }
14763
15154
  return JSON.stringify(shape);
@@ -14794,9 +15185,12 @@ function updateGitFooterChipNodeValue(node, chip, valueSelector) {
14794
15185
  }
14795
15186
  const previousTooltip = node.getAttribute("data-tooltip");
14796
15187
  if (previousTooltip) {
14797
- const nextTooltip = previousTooltip.replace(/Current: [^\n]*/u, `Current: ${cleanFooterPayloadText(chip.value, "—")}`);
15188
+ const nextTooltip = chip.key === "usage"
15189
+ ? gitFooterPayloadTooltip(chip)
15190
+ : previousTooltip.replace(/Current: [^\n]*/u, `Current: ${cleanFooterPayloadText(chip.value, "—")}`);
14798
15191
  if (nextTooltip !== previousTooltip) {
14799
15192
  node.setAttribute("data-tooltip", nextTooltip);
15193
+ node.setAttribute("aria-label", nextTooltip.replace(/\s+/g, " "));
14800
15194
  if (footerTooltipTarget === node && footerTooltipNode && !footerTooltipNode.hidden) {
14801
15195
  footerTooltipNode.textContent = nextTooltip;
14802
15196
  positionFooterTooltip(node);
@@ -14804,6 +15198,7 @@ function updateGitFooterChipNodeValue(node, chip, valueSelector) {
14804
15198
  }
14805
15199
  }
14806
15200
  if (chip.contextUsage) applyFooterContextUsage(node, chip.contextUsage);
15201
+ if (chip.usageWindows) applyFooterUsageWindows(node, chip.usageWindows);
14807
15202
  }
14808
15203
 
14809
15204
  let gitFooterRenderCache = null;
@@ -23118,6 +23513,117 @@ function formatStatsPercent(value) {
23118
23513
  return `${statsNumber(value).toFixed(1)}%`;
23119
23514
  }
23120
23515
 
23516
+ function statsArray(value) {
23517
+ return Array.isArray(value) ? value : [];
23518
+ }
23519
+
23520
+ function statsNullableNumber(value) {
23521
+ const number = Number(value);
23522
+ return Number.isFinite(number) ? number : null;
23523
+ }
23524
+
23525
+ function formatStatsNullablePercent(value) {
23526
+ const number = statsNullableNumber(value);
23527
+ return number === null ? "n/a" : `${number.toFixed(1)}%`;
23528
+ }
23529
+
23530
+ function formatStatsNullableCost(value) {
23531
+ const number = statsNullableNumber(value);
23532
+ return number === null ? "n/a" : formatStatsCost(number);
23533
+ }
23534
+
23535
+ function formatStatsNullableTokens(value) {
23536
+ const number = statsNullableNumber(value);
23537
+ return number === null ? "n/a" : `${formatStatsTokens(number)} tok`;
23538
+ }
23539
+
23540
+ function formatStatsSignedCost(value) {
23541
+ const number = statsNullableNumber(value);
23542
+ if (number === null) return "n/a";
23543
+ const sign = number > 0 ? "+" : number < 0 ? "−" : "";
23544
+ return `${sign}${formatStatsCost(Math.abs(number))}`;
23545
+ }
23546
+
23547
+ function statsSummaryHas(summary, key) {
23548
+ return !!summary && typeof summary === "object" && key in summary;
23549
+ }
23550
+
23551
+ function statsCostShareOf(cost, totalCost) {
23552
+ const total = statsNumber(totalCost);
23553
+ return total > 0 ? (statsNumber(cost) / total) * 100 : null;
23554
+ }
23555
+
23556
+ function statsCachedInputShare(summary, totals) {
23557
+ if (statsSummaryHas(summary, "cachedInputShare")) return statsNullableNumber(summary.cachedInputShare);
23558
+ // Legacy v1 payload fallback: compute the cached-input share client-side.
23559
+ const denominator = statsNumber(totals?.input) + statsNumber(totals?.cacheRead) + statsNumber(totals?.cacheWrite);
23560
+ return denominator > 0 ? (statsNumber(totals?.cacheRead) / denominator) * 100 : null;
23561
+ }
23562
+
23563
+ function statsPromptSideTokens(summary, totals) {
23564
+ if (statsSummaryHas(summary, "promptSideTokens")) return statsNumber(summary.promptSideTokens);
23565
+ return statsNumber(totals?.input) + statsNumber(totals?.cacheRead) + statsNumber(totals?.cacheWrite);
23566
+ }
23567
+
23568
+ function statsEffectiveCostRate(summary, totals) {
23569
+ if (statsSummaryHas(summary, "effectiveCostPerMillionTokens")) return statsNullableNumber(summary.effectiveCostPerMillionTokens);
23570
+ // Legacy v1 payload fallback: blended cost per million total tokens.
23571
+ return statsNumber(totals?.total) > 0 ? (statsNumber(totals?.cost) / statsNumber(totals.total)) * 1_000_000 : null;
23572
+ }
23573
+
23574
+ function statsScopedSessionCount(payload) {
23575
+ const scoped = statsNullableNumber(payload?.scopedSessionCount);
23576
+ if (scoped !== null) return scoped;
23577
+ // Legacy v1 payload fallback: only the session-file count is available.
23578
+ return statsNullableNumber(payload?.sessionCount);
23579
+ }
23580
+
23581
+ function statsAverageCostPerSession(summary, payload) {
23582
+ if (statsSummaryHas(summary, "averageCostPerSession")) return statsNullableNumber(summary.averageCostPerSession);
23583
+ const sessions = statsScopedSessionCount(payload);
23584
+ return sessions && sessions > 0 ? statsNumber(payload?.totals?.cost) / sessions : null;
23585
+ }
23586
+
23587
+ function statsAverageTokensPerSession(summary, payload) {
23588
+ if (statsSummaryHas(summary, "averageTokensPerSession")) return statsNullableNumber(summary.averageTokensPerSession);
23589
+ const sessions = statsScopedSessionCount(payload);
23590
+ return sessions && sessions > 0 ? statsNumber(payload?.totals?.total) / sessions : null;
23591
+ }
23592
+
23593
+ function statsSpendComparison(summary) {
23594
+ const comparison = statsSummaryHas(summary, "spendComparison") ? summary.spendComparison : null;
23595
+ if (!comparison || typeof comparison !== "object") return null;
23596
+ const windowDays = statsNumber(comparison.windowDays);
23597
+ if (windowDays <= 0) return null;
23598
+ return {
23599
+ windowDays,
23600
+ recentStartDay: typeof comparison.recentStartDay === "string" ? comparison.recentStartDay : "",
23601
+ recentEndDay: typeof comparison.recentEndDay === "string" ? comparison.recentEndDay : "",
23602
+ recentCost: statsNumber(comparison.recentCost),
23603
+ priorCost: statsNumber(comparison.priorCost),
23604
+ changeCost: statsNullableNumber(comparison.changeCost),
23605
+ changePercent: statsNullableNumber(comparison.changePercent),
23606
+ };
23607
+ }
23608
+
23609
+ function statsModelDriverEntries(payload) {
23610
+ const totalCost = statsNumber(payload?.totals?.cost);
23611
+ return statsArray(payload?.models).map((model) => ({
23612
+ name: model?.model || "unknown",
23613
+ cost: statsNumber(model?.cost),
23614
+ share: statsCostShareOf(model?.cost, totalCost),
23615
+ }));
23616
+ }
23617
+
23618
+ function statsSessionDriverEntries(payload) {
23619
+ const totalCost = statsNumber(payload?.totals?.cost);
23620
+ return statsArray(payload?.expensiveSessions).map((session) => ({
23621
+ name: session?.displayName || session?.sessionId || "unknown",
23622
+ cost: statsNumber(session?.cost),
23623
+ share: statsCostShareOf(session?.cost, totalCost),
23624
+ }));
23625
+ }
23626
+
23121
23627
  function parseStatsWebuiPayloadRaw(raw) {
23122
23628
  if (!raw) return null;
23123
23629
  try {
@@ -23192,13 +23698,18 @@ function statsLineBlock(lines = []) {
23192
23698
  return pre;
23193
23699
  }
23194
23700
 
23195
- function renderStatsTable(headers, rows, emptyText = "No data.") {
23701
+ function renderStatsTable(headers, rows, emptyText = "No data.", caption = "") {
23196
23702
  if (!rows.length) return make("p", "stats-overlay-empty muted", emptyText);
23197
23703
  const wrapper = make("div", "stats-overlay-table-wrap");
23198
23704
  const table = make("table", "stats-overlay-table");
23705
+ if (caption) table.append(make("caption", "stats-overlay-table-caption", caption));
23199
23706
  const thead = make("thead");
23200
23707
  const headRow = make("tr");
23201
- for (const header of headers) headRow.append(make("th", undefined, header));
23708
+ for (const header of headers) {
23709
+ const th = make("th", undefined, header);
23710
+ th.scope = "col";
23711
+ headRow.append(th);
23712
+ }
23202
23713
  thead.append(headRow);
23203
23714
  const tbody = make("tbody");
23204
23715
  for (const row of rows) {
@@ -23211,18 +23722,57 @@ function renderStatsTable(headers, rows, emptyText = "No data.") {
23211
23722
  return wrapper;
23212
23723
  }
23213
23724
 
23725
+ const STATS_CHART_POINT_LIMIT = 31;
23726
+
23727
+ function statsChartWindow(rows = []) {
23728
+ const list = statsArray(rows);
23729
+ const capped = list.length > STATS_CHART_POINT_LIMIT ? list.slice(-STATS_CHART_POINT_LIMIT) : list;
23730
+ return { capped, total: list.length, truncated: list.length > capped.length };
23731
+ }
23732
+
23733
+ function statsChartWindowNote({ total, truncated }, noun = "days") {
23734
+ if (!truncated) return null;
23735
+ 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.`);
23736
+ }
23737
+
23738
+ function statsLegendItem(seriesClass, label) {
23739
+ const item = make("span", "stats-overlay-legend-item");
23740
+ item.append(make("span", `stats-overlay-legend-swatch ${seriesClass}`), label);
23741
+ return item;
23742
+ }
23743
+
23214
23744
  function renderStatsBarRows(daily = []) {
23215
- const rows = daily.filter((row) => statsNumber(row.total) > 0 || statsNumber(row.cost) > 0);
23745
+ const rows = statsArray(daily).filter((row) => statsNumber(row?.total) > 0 || statsNumber(row?.cost) > 0);
23216
23746
  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)));
23747
+ const windowed = statsChartWindow(rows);
23748
+ const capped = windowed.capped;
23749
+ const maxTokens = Math.max(1, ...capped.map((row) => statsNumber(row.total)));
23750
+ const maxCost = Math.max(0.0001, ...capped.map((row) => statsNumber(row.cost)));
23751
+ const peakTokens = capped.reduce((best, row) => (statsNumber(row.total) > statsNumber(best?.total) ? row : best), capped[0]);
23752
+ const peakCost = capped.reduce((best, row) => (statsNumber(row.cost) > statsNumber(best?.cost) ? row : best), capped[0]);
23753
+ const wrapper = make("div", "stats-overlay-bars-panel");
23754
+ const legend = make("p", "stats-overlay-legend");
23755
+ legend.append(
23756
+ statsLegendItem("tokens", "Tokens"),
23757
+ statsLegendItem("cost", "Cost"),
23758
+ make("span", "stats-overlay-legend-note muted", "token and cost bars use independent scales"),
23759
+ );
23218
23760
  const list = make("div", "stats-overlay-bars");
23219
- for (const row of rows) {
23220
- const tokenRatio = Math.max(0.015, statsNumber(row.total) / maxTokens);
23761
+ for (const row of capped) {
23762
+ const tokenRatio = Math.min(100, Math.max(statsNumber(row.total) > 0 ? 1.5 : 0, (statsNumber(row.total) / maxTokens) * 100));
23763
+ const costRatio = Math.min(100, Math.max(statsNumber(row.cost) > 0 ? 1.5 : 0, (statsNumber(row.cost) / maxCost) * 100));
23221
23764
  const item = make("div", "stats-overlay-bar-row");
23222
23765
  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);
23766
+ bar.setAttribute("aria-hidden", "true");
23767
+ const tokenLane = make("span", "stats-overlay-bar-lane");
23768
+ const tokenFill = make("span", "stats-overlay-bar-fill");
23769
+ tokenFill.style.width = `${tokenRatio}%`;
23770
+ tokenLane.append(tokenFill);
23771
+ const costLane = make("span", "stats-overlay-bar-lane");
23772
+ const costFill = make("span", "stats-overlay-bar-fill cost");
23773
+ costFill.style.width = `${costRatio}%`;
23774
+ costLane.append(costFill);
23775
+ bar.append(tokenLane, costLane);
23226
23776
  item.append(
23227
23777
  make("span", "stats-overlay-bar-day", row.day || "—"),
23228
23778
  bar,
@@ -23231,33 +23781,144 @@ function renderStatsBarRows(daily = []) {
23231
23781
  );
23232
23782
  list.append(item);
23233
23783
  }
23784
+ wrapper.append(
23785
+ legend,
23786
+ list,
23787
+ 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 || "—"}`),
23788
+ );
23789
+ const note = statsChartWindowNote(windowed, "active days");
23790
+ if (note) wrapper.append(note);
23791
+ return wrapper;
23792
+ }
23793
+
23794
+ function renderStatsSpendChart(daily = []) {
23795
+ const rows = statsArray(daily).map((row) => ({ day: String(row?.day || "—"), cost: Math.max(0, statsNumber(row?.cost)) }));
23796
+ if (!rows.length) return make("p", "stats-overlay-empty muted", "No daily usage in this range.");
23797
+ const windowed = statsChartWindow(rows);
23798
+ const capped = windowed.capped;
23799
+ const maxCost = Math.max(0, ...capped.map((row) => row.cost));
23800
+ const total = capped.reduce((acc, row) => acc + row.cost, 0);
23801
+ if (total <= 0) return make("p", "stats-overlay-empty muted", "No spend recorded in this range.");
23802
+ const peak = capped.reduce((best, row) => (row.cost > (best?.cost ?? -1) ? row : best), null);
23803
+ const wrapper = make("div", "stats-overlay-spend");
23804
+ const chart = make("div", "stats-overlay-spend-chart");
23805
+ chart.setAttribute("role", "img");
23806
+ 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}.`);
23807
+ for (const row of capped) {
23808
+ const col = make("span", "stats-overlay-spend-col");
23809
+ const bar = make("span", "stats-overlay-spend-bar");
23810
+ const height = maxCost > 0 ? Math.min(100, Math.max(row.cost > 0 ? 3 : 0, (row.cost / maxCost) * 100)) : 0;
23811
+ bar.style.height = `${height}%`;
23812
+ col.title = `${row.day}: ${formatStatsCost(row.cost)}`;
23813
+ col.append(bar);
23814
+ chart.append(col);
23815
+ }
23816
+ 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` : ""}`);
23817
+ wrapper.append(chart, caption);
23818
+ return wrapper;
23819
+ }
23820
+
23821
+ function renderStatsComposition(totals = {}) {
23822
+ const segments = [
23823
+ { key: "seg-input", label: "Input", value: Math.max(0, statsNumber(totals.input)) },
23824
+ { key: "seg-output", label: "Output", value: Math.max(0, statsNumber(totals.output)) },
23825
+ { key: "seg-cache-read", label: "Cache read", value: Math.max(0, statsNumber(totals.cacheRead)) },
23826
+ { key: "seg-cache-write", label: "Cache write", value: Math.max(0, statsNumber(totals.cacheWrite)) },
23827
+ ];
23828
+ const total = segments.reduce((acc, segment) => acc + segment.value, 0);
23829
+ if (total <= 0) return make("p", "stats-overlay-empty muted", "No token usage in this range.");
23830
+ const shareText = (value) => `${((value / total) * 100).toFixed(1)}%`;
23831
+ const wrapper = make("div", "stats-overlay-composition");
23832
+ const track = make("div", "stats-overlay-composition-track");
23833
+ track.setAttribute("role", "img");
23834
+ track.setAttribute("aria-label", `Token composition: ${segments.map((segment) => `${segment.label} ${shareText(segment.value)}`).join(", ")}.`);
23835
+ for (const segment of segments) {
23836
+ if (segment.value <= 0) continue;
23837
+ const node = make("span", `stats-overlay-composition-segment ${segment.key}`);
23838
+ node.style.width = `${Math.min(100, Math.max(0, (segment.value / total) * 100))}%`;
23839
+ node.title = `${segment.label}: ${formatStatsTokens(segment.value)} tok (${shareText(segment.value)})`;
23840
+ track.append(node);
23841
+ }
23842
+ const legend = make("ul", "stats-overlay-legend stats-overlay-composition-legend");
23843
+ for (const segment of segments) {
23844
+ const item = make("li", "stats-overlay-legend-item");
23845
+ item.append(make("span", `stats-overlay-legend-swatch ${segment.key}`), `${segment.label} ${formatStatsTokens(segment.value)} tok · ${shareText(segment.value)}`);
23846
+ legend.append(item);
23847
+ }
23848
+ wrapper.append(track, legend);
23849
+ return wrapper;
23850
+ }
23851
+
23852
+ function renderStatsDriverList(entries = [], emptyText = "No cost drivers in this range.") {
23853
+ const rows = statsArray(entries)
23854
+ .map((entry) => ({ name: entry?.name || "unknown", cost: Math.max(0, statsNumber(entry?.cost)), share: statsNullableNumber(entry?.share) }))
23855
+ .filter((entry) => entry.cost > 0)
23856
+ .slice(0, 8);
23857
+ if (!rows.length) return make("p", "stats-overlay-empty muted", emptyText);
23858
+ const maxCost = Math.max(...rows.map((entry) => entry.cost));
23859
+ const list = make("div", "stats-overlay-driver-list");
23860
+ for (const [index, entry] of rows.entries()) {
23861
+ const ratio = maxCost > 0 ? Math.min(100, Math.max(2, (entry.cost / maxCost) * 100)) : 0;
23862
+ const row = make("div", "stats-overlay-driver-row");
23863
+ const bar = make("span", "stats-overlay-driver-bar");
23864
+ bar.setAttribute("aria-hidden", "true");
23865
+ const fill = make("span", "stats-overlay-driver-bar-fill");
23866
+ fill.style.width = `${ratio}%`;
23867
+ bar.append(fill);
23868
+ row.append(
23869
+ make("span", "stats-overlay-driver-rank", String(index + 1)),
23870
+ make("span", "stats-overlay-driver-name", entry.name),
23871
+ bar,
23872
+ make("span", "stats-overlay-driver-value", `${formatStatsCost(entry.cost)} · ${formatStatsNullablePercent(entry.share)}`),
23873
+ );
23874
+ list.append(row);
23875
+ }
23234
23876
  return list;
23235
23877
  }
23236
23878
 
23879
+ function renderStatsDriverSection(title, entries, emptyText) {
23880
+ const section = make("section", "stats-overlay-driver-section");
23881
+ section.append(make("h4", undefined, title), renderStatsDriverList(entries, emptyText));
23882
+ return section;
23883
+ }
23884
+
23885
+ function renderStatsTopDrivers(payload) {
23886
+ const grid = make("div", "stats-overlay-drivers");
23887
+ grid.append(
23888
+ renderStatsDriverSection("Models by spend", statsModelDriverEntries(payload), "No model spend in this range."),
23889
+ renderStatsDriverSection("Sessions by spend", statsSessionDriverEntries(payload), "No session spend in this range."),
23890
+ );
23891
+ return grid;
23892
+ }
23893
+
23237
23894
  function renderStatsOverview(payload) {
23238
23895
  const node = make("div", "stats-overlay-pane stats-overlay-overview");
23239
23896
  const totals = payload?.totals || {};
23240
23897
  const summary = payload?.summary || {};
23241
23898
  const highest = summary.highestDay;
23899
+ const scopedSessions = statsNullableNumber(payload?.scopedSessionCount);
23900
+ const sessionDetail = scopedSessions !== null ? `${scopedSessions} sessions in range` : `${payload?.sessionCount ?? 0} session files`;
23901
+ const cachedShare = statsCachedInputShare(summary, totals);
23242
23902
  const cards = make("div", "stats-overlay-cards");
23243
23903
  cards.append(
23244
23904
  statsMetricCard("Total tokens", formatStatsTokens(totals.total), `↑${formatStatsTokens(totals.input)} ↓${formatStatsTokens(totals.output)}`, "tone-blue"),
23245
23905
  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"),
23906
+ statsMetricCard("Effective $/1M", formatStatsNullableCost(statsEffectiveCostRate(summary, totals)), "blended rate, not provider list pricing", "tone-sky"),
23907
+ statsMetricCard("Messages", String(statsNumber(totals.messages)), sessionDetail, "tone-mauve"),
23247
23908
  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"),
23909
+ 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
23910
  statsMetricCard("Active days", `${payload?.activeDayCount ?? 0}/${payload?.dayCount ?? 0}`, highest ? `peak ${highest.day} · ${formatStatsCost(highest.cost)}` : "no peak yet", "tone-pink"),
23250
23911
  );
23251
- node.append(cards, make("h3", undefined, "Daily usage"), renderStatsBarRows(payload?.daily || []));
23912
+ node.append(cards, make("h3", undefined, "Daily usage"), renderStatsBarRows(payload?.daily));
23252
23913
  return node;
23253
23914
  }
23254
23915
 
23255
23916
  function renderStatsDaily(payload) {
23256
23917
  const node = make("div", "stats-overlay-pane");
23257
- node.append(make("h3", undefined, "Daily token and cost trend"), renderStatsBarRows(payload?.daily || []));
23918
+ node.append(make("h3", undefined, "Daily token and cost trend"), renderStatsBarRows(payload?.daily));
23258
23919
  node.append(renderStatsTable(
23259
23920
  ["Day", "Tokens", "Cost", "Input", "Output", "Cache R/W", "Msgs"],
23260
- (payload?.daily || []).map((row) => [
23921
+ statsArray(payload?.daily).map((row) => [
23261
23922
  row.day || "—",
23262
23923
  formatStatsTokens(row.total),
23263
23924
  formatStatsCost(row.cost),
@@ -23266,14 +23927,21 @@ function renderStatsDaily(payload) {
23266
23927
  `${formatStatsTokens(row.cacheRead)} / ${formatStatsTokens(row.cacheWrite)}`,
23267
23928
  String(statsNumber(row.messages)),
23268
23929
  ]),
23930
+ "No data.",
23931
+ "Daily tokens and cost by UTC day",
23269
23932
  ));
23270
23933
  return node;
23271
23934
  }
23272
23935
 
23273
23936
  function renderStatsModels(payload) {
23274
- return renderStatsTable(
23937
+ const node = make("div", "stats-overlay-pane");
23938
+ node.append(
23939
+ make("h3", undefined, "Model spend ranks"),
23940
+ renderStatsDriverList(statsModelDriverEntries(payload), "No model spend in this range."),
23941
+ );
23942
+ node.append(renderStatsTable(
23275
23943
  ["Model", "Tokens", "Token %", "Cost", "Spend %", "$/1M", "Avg out", "Msgs"],
23276
- (payload?.models || []).map((model) => [
23944
+ statsArray(payload?.models).map((model) => [
23277
23945
  model.model || "unknown",
23278
23946
  formatStatsTokens(model.tokens),
23279
23947
  formatStatsPercent(model.percent),
@@ -23284,13 +23952,20 @@ function renderStatsModels(payload) {
23284
23952
  String(statsNumber(model.messages)),
23285
23953
  ]),
23286
23954
  "No model usage in this range.",
23287
- );
23955
+ "Model token and cost comparison",
23956
+ ));
23957
+ return node;
23288
23958
  }
23289
23959
 
23290
23960
  function renderStatsSessions(payload) {
23291
- return renderStatsTable(
23961
+ const node = make("div", "stats-overlay-pane");
23962
+ node.append(
23963
+ make("h3", undefined, "Session spend ranks"),
23964
+ renderStatsDriverList(statsSessionDriverEntries(payload), "No session spend in this range."),
23965
+ );
23966
+ node.append(renderStatsTable(
23292
23967
  ["Day", "Session", "Cost", "Tokens", "Model"],
23293
- (payload?.expensiveSessions || []).map((session) => [
23968
+ statsArray(payload?.expensiveSessions).map((session) => [
23294
23969
  session.day || "—",
23295
23970
  session.displayName || session.sessionId || "unknown",
23296
23971
  formatStatsCost(session.cost),
@@ -23298,21 +23973,43 @@ function renderStatsSessions(payload) {
23298
23973
  session.model || "unknown",
23299
23974
  ]),
23300
23975
  "No session usage in this range.",
23301
- );
23976
+ "Most expensive sessions in the selected range",
23977
+ ));
23978
+ return node;
23302
23979
  }
23303
23980
 
23304
23981
  function renderStatsCostCache(payload) {
23305
23982
  const node = make("div", "stats-overlay-pane");
23306
23983
  const totals = payload?.totals || {};
23307
23984
  const summary = payload?.summary || {};
23985
+ const comparison = statsSpendComparison(summary);
23986
+ const scopedSessions = statsNullableNumber(payload?.scopedSessionCount);
23987
+ const sessionDetail = scopedSessions !== null ? `per session in range (${scopedSessions})` : "per session file (legacy count)";
23308
23988
  const cards = make("div", "stats-overlay-cards compact");
23309
23989
  cards.append(
23310
23990
  statsMetricCard("Avg/day", formatStatsCost(summary.calendarAvgCost), "calendar average", "tone-green"),
23311
23991
  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"),
23992
+ statsMetricCard("Effective $/1M", formatStatsNullableCost(statsEffectiveCostRate(summary, totals)), "blended rate, not provider list pricing", "tone-blue"),
23993
+ statsMetricCard("Cached-input share", formatStatsNullablePercent(statsCachedInputShare(summary, totals)), `reads ${formatStatsTokens(totals.cacheRead)} of ${formatStatsTokens(statsPromptSideTokens(summary, totals))} prompt-side tok`, "tone-yellow"),
23994
+ statsMetricCard("Avg cost/session", formatStatsNullableCost(statsAverageCostPerSession(summary, payload)), `${formatStatsNullableTokens(statsAverageTokensPerSession(summary, payload))} · ${sessionDetail}`, "tone-mauve"),
23995
+ statsMetricCard(
23996
+ "Recent spend",
23997
+ comparison ? formatStatsCost(comparison.recentCost) : "n/a",
23998
+ comparison
23999
+ ? `${comparison.recentStartDay} → ${comparison.recentEndDay} (${comparison.windowDays}d) vs prior ${comparison.windowDays}d ${formatStatsCost(comparison.priorCost)} · ${formatStatsSignedCost(comparison.changeCost)} (${formatStatsNullablePercent(comparison.changePercent)})`
24000
+ : "requires the latest stats extension",
24001
+ "tone-pink",
24002
+ ),
24003
+ );
24004
+ node.append(
24005
+ cards,
24006
+ make("h3", undefined, "Daily spend"),
24007
+ renderStatsSpendChart(payload?.daily),
24008
+ make("h3", undefined, "Token & cache composition"),
24009
+ renderStatsComposition(totals),
24010
+ make("h3", undefined, "Top cost drivers"),
24011
+ renderStatsTopDrivers(payload),
23314
24012
  );
23315
- node.append(cards, make("h3", undefined, "Cost trend"), statsLineBlock(payload?.lines?.costTrend), make("h3", undefined, "Cache efficiency"), statsLineBlock(payload?.lines?.cache));
23316
24013
  return node;
23317
24014
  }
23318
24015
 
@@ -23343,24 +24040,429 @@ function renderStatsCalibrationPanel(payload) {
23343
24040
  return panel;
23344
24041
  }
23345
24042
 
23346
- function renderStatsPrompt(payload) {
23347
- const node = make("div", "stats-overlay-pane");
23348
- const cards = make("div", "stats-overlay-cards compact");
24043
+ const STATS_PROMPT_SOURCE_LIMIT = 24;
24044
+ const STATS_PROMPT_TOOL_LIMIT = 12;
24045
+ const STATS_PROMPT_TOOL_ENTRY_LIMIT = 24;
24046
+ const STATS_PROMPT_SKILL_LIMIT = 10;
24047
+ const STATS_PROMPT_CONTEXT_FILE_LIMIT = 8;
24048
+ const STATS_PROMPT_SOURCE_KINDS = new Set([
24049
+ "system-prompt", "tools-prompt", "custom-prompt", "append-system", "context-file", "skills",
24050
+ "tool-schemas", "framing", "user-messages", "assistant-messages", "assistant-tool-calls",
24051
+ "tool-results", "other",
24052
+ ]);
24053
+
24054
+ function statsPromptRecord(value) {
24055
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
24056
+ }
24057
+
24058
+ function statsPromptText(value, maxLength = 240) {
24059
+ if (typeof value !== "string" || !value.trim()) return null;
24060
+ return value.trim().slice(0, maxLength);
24061
+ }
24062
+
24063
+ function statsPromptNullableText(value, maxLength = 240) {
24064
+ if (value === null) return null;
24065
+ return typeof value === "string" ? value.trim().slice(0, maxLength) : undefined;
24066
+ }
24067
+
24068
+ function statsPromptMetric(value, { integer = false, signed = false } = {}) {
24069
+ if (typeof value !== "number" || !Number.isFinite(value) || (!signed && value < 0)) return null;
24070
+ if (integer && !Number.isInteger(value)) return null;
24071
+ return value;
24072
+ }
24073
+
24074
+ function statsPromptNullableMetric(value, options = {}) {
24075
+ if (value === null) return null;
24076
+ const metric = statsPromptMetric(value, options);
24077
+ return metric === null ? undefined : metric;
24078
+ }
24079
+
24080
+ function statsPromptPercent(value) {
24081
+ const percent = statsPromptNullableMetric(value);
24082
+ return percent === undefined || (percent !== null && percent > 100) ? undefined : percent;
24083
+ }
24084
+
24085
+ function formatStatsPromptNullablePercent(value) {
24086
+ return value === null ? "n/a" : `${value.toFixed(1)}%`;
24087
+ }
24088
+
24089
+ function formatStatsPromptNullableTokens(value) {
24090
+ return value === null ? "n/a" : `${formatStatsTokens(value)} tok`;
24091
+ }
24092
+
24093
+ function statsPromptList(value, limit, normalize) {
24094
+ if (!Array.isArray(value)) return null;
24095
+ const result = [];
24096
+ for (const entry of value.slice(0, limit)) {
24097
+ const normalized = normalize(entry);
24098
+ if (!normalized) return null;
24099
+ result.push(normalized);
24100
+ }
24101
+ return result;
24102
+ }
24103
+
24104
+ function normalizeStatsPromptSource(value, tokenKey, { charsNullable = false } = {}) {
24105
+ const source = statsPromptRecord(value);
24106
+ if (!source) return null;
24107
+ const id = statsPromptText(source.id, 120);
24108
+ const kind = statsPromptText(source.kind, 80);
24109
+ const label = statsPromptText(source.label, 240);
24110
+ const chars = charsNullable ? statsPromptNullableMetric(source.chars) : statsPromptMetric(source.chars);
24111
+ const tokens = statsPromptMetric(source[tokenKey]);
24112
+ const percent = statsPromptPercent(source.percent);
24113
+ if (!id || !kind || !STATS_PROMPT_SOURCE_KINDS.has(kind) || !label || chars === undefined || tokens === null || percent === undefined) return null;
24114
+ return { id, kind, label, chars, [tokenKey]: tokens, percent };
24115
+ }
24116
+
24117
+ function normalizeStatsPromptInitial(value) {
24118
+ const section = statsPromptRecord(value);
24119
+ if (!section) return null;
24120
+ const totalTokens = statsPromptMetric(section.totalTokens);
24121
+ const lowTokens = statsPromptMetric(section.lowTokens);
24122
+ const highTokens = statsPromptMetric(section.highTokens);
24123
+ const confidence = statsPromptText(section.confidence, 80);
24124
+ const source = statsPromptText(section.source, 80);
24125
+ const warning = statsPromptNullableText(section.warning, 360);
24126
+ const estimateMethod = statsPromptText(section.estimateMethod, 160);
24127
+ const components = statsPromptList(section.components, STATS_PROMPT_SOURCE_LIMIT, (entry) => {
24128
+ const component = normalizeStatsPromptSource(entry, "tokens", { charsNullable: true });
24129
+ if (!component) return null;
24130
+ const uncalibratedTokens = statsPromptMetric(entry.uncalibratedTokens);
24131
+ return uncalibratedTokens === null ? null : { ...component, uncalibratedTokens };
24132
+ });
24133
+ if (totalTokens === null || lowTokens === null || highTokens === null || !confidence || !source || warning === undefined || !estimateMethod || !components) return null;
24134
+ const componentTotal = components.reduce((sum, component) => sum + component.tokens, 0);
24135
+ if (componentTotal !== totalTokens) return null;
24136
+ return { totalTokens, lowTokens, highTokens, confidence, source, warning, estimateMethod, components };
24137
+ }
24138
+
24139
+ function normalizeStatsPromptInventory(value, limit, itemKey, normalizeItem) {
24140
+ const inventory = statsPromptRecord(value);
24141
+ if (!inventory) return null;
24142
+ const totalCount = statsPromptMetric(inventory.totalCount, { integer: true });
24143
+ const omittedCount = statsPromptMetric(inventory.omittedCount, { integer: true });
24144
+ const items = statsPromptList(inventory[itemKey], limit, normalizeItem);
24145
+ if (totalCount === null || omittedCount === null || !items) return null;
24146
+ return { totalCount, omittedCount, items };
24147
+ }
24148
+
24149
+ function normalizeStatsPromptSnapshot(value) {
24150
+ const section = statsPromptRecord(value);
24151
+ const estimates = statsPromptRecord(section?.estimateComponents);
24152
+ const calibration = statsPromptRecord(estimates?.calibration);
24153
+ const metadata = statsPromptRecord(section?.metadata);
24154
+ if (!section || !estimates || !calibration || !metadata) return null;
24155
+
24156
+ const source = statsPromptText(section.source, 80);
24157
+ const settled = typeof section.settled === "boolean" ? section.settled : null;
24158
+ const attempts = statsPromptMetric(section.attempts, { integer: true });
24159
+ const warning = statsPromptNullableText(section.warning, 360);
24160
+ const systemPromptChars = statsPromptMetric(section.systemPromptChars, { integer: true });
24161
+ const promptText = statsPromptMetric(estimates.promptText);
24162
+ const toolSchemas = statsPromptMetric(estimates.toolSchemas);
24163
+ const framing = statsPromptMetric(estimates.framing);
24164
+ const multiplier = statsPromptMetric(calibration.multiplier);
24165
+ const samples = statsPromptMetric(calibration.samples, { integer: true });
24166
+ const currentDate = statsPromptNullableText(metadata.currentDate, 120);
24167
+ const cwdDisplay = statsPromptNullableText(metadata.cwdDisplay, 120);
24168
+ const extraGuidelineCount = statsPromptMetric(metadata.extraGuidelineCount, { integer: true });
24169
+
24170
+ const tools = normalizeStatsPromptInventory(section.tools, STATS_PROMPT_TOOL_LIMIT, "items", (value) => {
24171
+ const item = statsPromptRecord(value);
24172
+ if (!item) return null;
24173
+ const name = statsPromptText(item.name, 120);
24174
+ const description = statsPromptNullableText(item.description, 360);
24175
+ const parameterSummary = statsPromptText(item.parameterSummary, 120);
24176
+ const estimatedTokens = statsPromptMetric(item.estimatedTokens);
24177
+ return !name || description === undefined || !parameterSummary || estimatedTokens === null
24178
+ ? null
24179
+ : { name, description, parameterSummary, estimatedTokens };
24180
+ });
24181
+ const toolPromptEntries = normalizeStatsPromptInventory(section.toolPromptEntries, STATS_PROMPT_TOOL_ENTRY_LIMIT, "names", (name) => {
24182
+ const normalized = statsPromptText(name, 120);
24183
+ return normalized ? { name: normalized } : null;
24184
+ });
24185
+ const skills = normalizeStatsPromptInventory(section.skills, STATS_PROMPT_SKILL_LIMIT, "items", (value) => {
24186
+ const item = statsPromptRecord(value);
24187
+ if (!item) return null;
24188
+ const name = statsPromptText(item.name, 120);
24189
+ const description = statsPromptNullableText(item.description, 360);
24190
+ return !name || description === undefined ? null : { name, description };
24191
+ });
24192
+ const contextFiles = normalizeStatsPromptInventory(section.contextFiles, STATS_PROMPT_CONTEXT_FILE_LIMIT, "items", (value) => {
24193
+ const item = statsPromptRecord(value);
24194
+ if (!item) return null;
24195
+ const displayPath = statsPromptText(item.displayPath, 240);
24196
+ const chars = statsPromptNullableMetric(item.chars);
24197
+ return !displayPath || chars === undefined ? null : { displayPath, chars };
24198
+ });
24199
+
24200
+ if (!source || settled === null || attempts === null || warning === undefined || systemPromptChars === null
24201
+ || promptText === null || toolSchemas === null || framing === null || multiplier === null || samples === null
24202
+ || currentDate === undefined || cwdDisplay === undefined || extraGuidelineCount === null
24203
+ || !tools || !toolPromptEntries || !skills || !contextFiles) return null;
24204
+ return {
24205
+ source, settled, attempts, warning, systemPromptChars,
24206
+ estimateComponents: { promptText, toolSchemas, framing, calibration: { multiplier, samples } },
24207
+ metadata: { currentDate, cwdDisplay, extraGuidelineCount },
24208
+ tools, toolPromptEntries, skills, contextFiles,
24209
+ };
24210
+ }
24211
+
24212
+ function normalizeStatsPromptCurrent(value) {
24213
+ const section = statsPromptRecord(value);
24214
+ const usage = statsPromptRecord(section?.usage);
24215
+ const breakdown = statsPromptRecord(section?.breakdown);
24216
+ if (!section || !usage || !breakdown) return null;
24217
+ const tokens = statsPromptNullableMetric(usage.tokens);
24218
+ const contextWindow = statsPromptNullableMetric(usage.contextWindow);
24219
+ const percent = statsPromptNullableMetric(usage.percent);
24220
+ const estimateMethod = statsPromptText(breakdown.estimateMethod, 160);
24221
+ const reconstruction = statsPromptText(breakdown.reconstruction, 40);
24222
+ const estimatedTotalTokens = statsPromptMetric(breakdown.estimatedTotalTokens);
24223
+ const actualMinusEstimatedTokens = statsPromptNullableMetric(breakdown.actualMinusEstimatedTokens, { signed: true });
24224
+ const sources = statsPromptList(breakdown.sources, STATS_PROMPT_SOURCE_LIMIT, (entry) => normalizeStatsPromptSource(entry, "estimatedTokens"));
24225
+ if (tokens === undefined || contextWindow === undefined || percent === undefined || !estimateMethod
24226
+ || !["complete", "unavailable"].includes(reconstruction) || estimatedTotalTokens === null
24227
+ || actualMinusEstimatedTokens === undefined || !sources) return null;
24228
+ return { usage: { tokens, contextWindow, percent }, breakdown: { estimateMethod, reconstruction, estimatedTotalTokens, actualMinusEstimatedTokens, sources } };
24229
+ }
24230
+
24231
+ function statsPromptKindLabel(kind) {
24232
+ return ({
24233
+ "system-prompt": "System prompt", "tools-prompt": "Tools prompt", "custom-prompt": "Custom prompt",
24234
+ "append-system": "Append system", "context-file": "Context file", skills: "Skills",
24235
+ "tool-schemas": "Tool schemas", framing: "Framing", "user-messages": "User messages",
24236
+ "assistant-messages": "Assistant messages", "assistant-tool-calls": "Assistant + tool calls",
24237
+ "tool-results": "Tool results", other: "Other",
24238
+ })[kind] || kind;
24239
+ }
24240
+
24241
+ function statsPromptSectionHeading(title, eyebrow) {
24242
+ const header = make("div", "stats-prompt-section-heading");
24243
+ const text = make("div");
24244
+ text.append(make("span", "stats-prompt-eyebrow", eyebrow), make("h3", undefined, title));
24245
+ header.append(text);
24246
+ return header;
24247
+ }
24248
+
24249
+ function statsPromptLegacyFallback(title, lines) {
24250
+ const section = make("section", "stats-prompt-section stats-prompt-legacy-fallback");
24251
+ const heading = statsPromptSectionHeading(title, "Legacy fallback");
24252
+ heading.append(make("span", "stats-prompt-badge warning", "Structured data unavailable"));
24253
+ section.append(heading, make("p", "stats-prompt-note muted", "Showing the matching legacy command output for this section."), statsLineBlock(lines));
24254
+ return section;
24255
+ }
24256
+
24257
+ function statsPromptCompositionTrack(rows, tokenKey, totalTokens, label) {
24258
+ const figure = make("figure", "stats-prompt-composition");
24259
+ const track = make("div", "stats-prompt-composition-track");
24260
+ const describedRows = rows.slice(0, 6);
24261
+ const described = describedRows.map((row) => `${row.label} ${formatStatsPromptNullablePercent(row.percent)}`).join(", ");
24262
+ const remaining = rows.length - describedRows.length;
24263
+ track.setAttribute("role", "img");
24264
+ track.setAttribute("aria-label", `${label}: ${described || "no estimated tokens"}${remaining > 0 ? `, and ${remaining} more sources` : ""}.`);
24265
+ for (const row of rows) {
24266
+ if (row[tokenKey] <= 0 || row.percent === null) continue;
24267
+ const segment = make("span", "stats-prompt-composition-segment");
24268
+ segment.dataset.promptKind = row.kind;
24269
+ segment.style.width = `${Math.min(100, row.percent)}%`;
24270
+ segment.title = `${row.label}: ${formatStatsTokens(row[tokenKey])} tok (${formatStatsPromptNullablePercent(row.percent)})`;
24271
+ track.append(segment);
24272
+ }
24273
+ figure.append(track, make("figcaption", "stats-prompt-note muted", `${formatStatsTokens(totalTokens)} estimated tokens · numeric values are repeated in the table below.`));
24274
+ return figure;
24275
+ }
24276
+
24277
+ function statsPromptTable(headers, rows, caption) {
24278
+ const wrapper = make("div", "stats-overlay-table-wrap stats-prompt-table-wrap");
24279
+ const table = make("table", "stats-overlay-table stats-prompt-table");
24280
+ table.append(make("caption", "stats-overlay-table-caption", caption));
24281
+ const thead = make("thead");
24282
+ const headRow = make("tr");
24283
+ for (const header of headers) {
24284
+ const th = make("th", undefined, header);
24285
+ th.scope = "col";
24286
+ headRow.append(th);
24287
+ }
24288
+ thead.append(headRow);
24289
+ const tbody = make("tbody");
24290
+ for (const row of rows) {
24291
+ const tr = make("tr");
24292
+ row.forEach((value, index) => {
24293
+ const cell = make("td", undefined, value);
24294
+ cell.dataset.label = headers[index];
24295
+ tr.append(cell);
24296
+ });
24297
+ tbody.append(tr);
24298
+ }
24299
+ table.append(thead, tbody);
24300
+ wrapper.append(table);
24301
+ return wrapper;
24302
+ }
24303
+
24304
+ function renderStatsPromptInitial(section) {
24305
+ const node = make("section", "stats-prompt-section stats-prompt-initial");
24306
+ const heading = statsPromptSectionHeading("Initial prompt composition", "Calibrated estimate");
24307
+ heading.append(make("span", "stats-prompt-badge", `${formatStatsTokens(section.totalTokens)} tok`));
24308
+ const summary = make("p", "stats-prompt-note muted", `Range ${formatStatsTokens(section.lowTokens)}–${formatStatsTokens(section.highTokens)} tok · ${section.confidence} · ${statsPromptEstimateSourceLabel(section)}`);
24309
+ node.append(heading, summary);
24310
+ if (section.warning) node.append(make("p", "stats-prompt-warning", section.warning));
24311
+ node.append(
24312
+ statsPromptCompositionTrack(section.components, "tokens", section.totalTokens, "Initial prompt composition"),
24313
+ statsPromptTable(
24314
+ ["Rank", "Source", "Kind", "Chars", "Uncalibrated", "Tokens", "Share"],
24315
+ section.components.map((component, index) => [
24316
+ String(index + 1), component.label, statsPromptKindLabel(component.kind),
24317
+ component.chars === null ? "n/a" : component.chars.toLocaleString(),
24318
+ `${formatStatsTokens(component.uncalibratedTokens)} tok`, `${formatStatsTokens(component.tokens)} tok`,
24319
+ formatStatsPromptNullablePercent(component.percent),
24320
+ ]),
24321
+ "Ranked initial-prompt token composition. Calibrated component tokens sum to the displayed total.",
24322
+ ),
24323
+ );
24324
+ return node;
24325
+ }
24326
+
24327
+ function statsPromptInventoryDetails(title, inventory, renderBody) {
24328
+ const details = make("details", "stats-prompt-inventory-details");
24329
+ const shown = inventory.items.length;
24330
+ const count = `${shown} shown / ${inventory.totalCount} total${inventory.omittedCount ? ` · ${inventory.omittedCount} omitted` : ""}`;
24331
+ const summary = make("summary");
24332
+ summary.append(make("span", undefined, title), make("span", "stats-prompt-details-count", count));
24333
+ details.append(summary);
24334
+ const body = make("div", "stats-prompt-details-body");
24335
+ body.append(renderBody(inventory.items));
24336
+ if (inventory.omittedCount) body.append(make("p", "stats-prompt-note muted", `${inventory.omittedCount} additional ${title.toLowerCase()} omitted by the producer cap.`));
24337
+ details.append(body);
24338
+ return details;
24339
+ }
24340
+
24341
+ function statsPromptDefinitionList(entries) {
24342
+ const list = make("dl", "stats-prompt-definition-list");
24343
+ for (const [term, description] of entries) list.append(make("dt", undefined, term), make("dd", undefined, description));
24344
+ return list;
24345
+ }
24346
+
24347
+ function renderStatsPromptSnapshot(section) {
24348
+ const node = make("section", "stats-prompt-section stats-prompt-snapshot");
24349
+ const heading = statsPromptSectionHeading("Prompt inventory", "Export-backed snapshot");
24350
+ heading.append(make("span", "stats-prompt-badge", `${section.systemPromptChars.toLocaleString()} chars`));
24351
+ node.append(heading);
24352
+ if (section.warning) node.append(make("p", "stats-prompt-warning", section.warning));
24353
+
24354
+ const estimates = section.estimateComponents;
24355
+ const cards = make("div", "stats-prompt-estimate-cards");
23349
24356
  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"),
24357
+ statsMetricCard("Prompt text", `${formatStatsTokens(estimates.promptText)} tok`, "character-derived estimate", "tone-blue"),
24358
+ statsMetricCard("Tool schemas", `${formatStatsTokens(estimates.toolSchemas)} tok`, "active schema estimate", "tone-teal"),
24359
+ statsMetricCard("Framing", `${formatStatsTokens(estimates.framing)} tok`, "provider/request allowance", "tone-mauve"),
24360
+ statsMetricCard("Calibration", `×${estimates.calibration.multiplier.toFixed(2)}`, `${estimates.calibration.samples} samples`, "tone-yellow"),
23354
24361
  );
24362
+ node.append(cards);
24363
+
24364
+ const metadataDetails = make("details", "stats-prompt-inventory-details");
24365
+ const metadataSummary = make("summary");
24366
+ metadataSummary.append(make("span", undefined, "Prompt metadata"), make("span", "stats-prompt-details-count", section.settled ? "settled snapshot" : "live fallback"));
24367
+ metadataDetails.append(metadataSummary, make("div", "stats-prompt-details-body"));
24368
+ metadataDetails.lastElementChild.append(statsPromptDefinitionList([
24369
+ ["Source", statsPromptEstimateSourceLabel(section)], ["Attempts", section.attempts.toLocaleString()],
24370
+ ["Current date", section.metadata.currentDate ?? "n/a"], ["Working directory", section.metadata.cwdDisplay ?? "n/a"],
24371
+ ["Extra guidelines", section.metadata.extraGuidelineCount.toLocaleString()],
24372
+ ]));
24373
+
24374
+ const inventory = make("div", "stats-prompt-inventory");
24375
+ inventory.append(
24376
+ metadataDetails,
24377
+ statsPromptInventoryDetails("Active tool schemas", section.tools, (items) => {
24378
+ const list = make("ul", "stats-prompt-card-list");
24379
+ for (const item of items) {
24380
+ const li = make("li");
24381
+ li.append(make("strong", undefined, item.name), make("span", "stats-prompt-item-meta", `${formatStatsTokens(item.estimatedTokens)} tok · ${item.parameterSummary}`));
24382
+ if (item.description) li.append(make("span", "stats-prompt-item-description", item.description));
24383
+ list.append(li);
24384
+ }
24385
+ return list;
24386
+ }),
24387
+ statsPromptInventoryDetails("Available-tool prompt entries", section.toolPromptEntries, (items) => {
24388
+ const list = make("ul", "stats-prompt-chip-list");
24389
+ for (const item of items) list.append(make("li", undefined, item.name));
24390
+ return list;
24391
+ }),
24392
+ statsPromptInventoryDetails("Skills", section.skills, (items) => {
24393
+ const list = make("ul", "stats-prompt-card-list");
24394
+ for (const item of items) {
24395
+ const li = make("li");
24396
+ li.append(make("strong", undefined, item.name));
24397
+ if (item.description) li.append(make("span", "stats-prompt-item-description", item.description));
24398
+ list.append(li);
24399
+ }
24400
+ return list;
24401
+ }),
24402
+ statsPromptInventoryDetails("Context files", section.contextFiles, (items) => {
24403
+ const list = make("ul", "stats-prompt-file-list");
24404
+ for (const item of items) {
24405
+ const row = make("li");
24406
+ row.append(make("span", undefined, item.displayPath), make("span", undefined, item.chars === null ? "n/a" : `${item.chars.toLocaleString()} chars`));
24407
+ list.append(row);
24408
+ }
24409
+ return list;
24410
+ }),
24411
+ );
24412
+ node.append(inventory);
24413
+ return node;
24414
+ }
24415
+
24416
+ function renderStatsPromptCurrent(section) {
24417
+ const node = make("section", "stats-prompt-section stats-prompt-current");
24418
+ const heading = statsPromptSectionHeading("Current context", "Actual utilization + heuristic composition");
24419
+ heading.append(make("span", "stats-prompt-badge", section.usage.percent === null ? "usage n/a" : formatStatsPromptNullablePercent(section.usage.percent)));
24420
+ node.append(heading);
24421
+
24422
+ const utilization = make("div", "stats-prompt-utilization");
24423
+ const progress = make("progress", "stats-prompt-progress");
24424
+ progress.max = 100;
24425
+ if (section.usage.percent !== null) progress.value = Math.min(100, section.usage.percent);
24426
+ const usageText = `${formatStatsPromptNullableTokens(section.usage.tokens)} used / ${formatStatsPromptNullableTokens(section.usage.contextWindow)} window · ${formatStatsPromptNullablePercent(section.usage.percent)}`;
24427
+ progress.setAttribute("aria-label", "Actual current context utilization");
24428
+ progress.setAttribute("aria-valuetext", usageText);
24429
+ utilization.append(progress, make("p", "stats-prompt-utilization-text", usageText));
24430
+ node.append(utilization);
24431
+
24432
+ const breakdown = section.breakdown;
24433
+ const cards = make("div", "stats-prompt-estimate-cards compact");
24434
+ cards.append(
24435
+ statsMetricCard("Actual usage", formatStatsPromptNullableTokens(section.usage.tokens), "provider/context usage", "tone-green"),
24436
+ statsMetricCard("Context window", formatStatsPromptNullableTokens(section.usage.contextWindow), "provider/context limit", "tone-blue"),
24437
+ statsMetricCard("Heuristic estimate", `${formatStatsTokens(breakdown.estimatedTotalTokens)} tok`, breakdown.reconstruction === "complete" ? "complete reconstruction" : "partial: reconstruction unavailable", "tone-mauve"),
24438
+ statsMetricCard("Actual − estimate", breakdown.actualMinusEstimatedTokens === null ? "n/a" : `${breakdown.actualMinusEstimatedTokens > 0 ? "+" : ""}${formatStatsTokens(breakdown.actualMinusEstimatedTokens)} tok`, "comparison only; not source attribution", "tone-yellow"),
24439
+ );
24440
+ 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."));
24441
+ node.append(
24442
+ statsPromptCompositionTrack(breakdown.sources, "estimatedTokens", breakdown.estimatedTotalTokens, "Estimated current-source composition"),
24443
+ statsPromptTable(
24444
+ ["Rank", "Source", "Kind", "Chars", "Estimated tokens", "Estimated share"],
24445
+ breakdown.sources.map((source, index) => [
24446
+ String(index + 1), source.label, statsPromptKindLabel(source.kind), source.chars.toLocaleString(),
24447
+ `${formatStatsTokens(source.estimatedTokens)} tok`, formatStatsPromptNullablePercent(source.percent),
24448
+ ]),
24449
+ "Ranked heuristic current-context source composition. Percentages use the estimated total, not actual usage.",
24450
+ ),
24451
+ );
24452
+ return node;
24453
+ }
24454
+
24455
+ function renderStatsPrompt(payload) {
24456
+ const node = make("div", "stats-overlay-pane stats-prompt-pane");
24457
+ const context = statsPromptRecord(payload?.promptContext);
24458
+ const initialPrompt = normalizeStatsPromptInitial(context?.initialPrompt);
24459
+ const snapshot = normalizeStatsPromptSnapshot(context?.snapshot);
24460
+ const currentContext = normalizeStatsPromptCurrent(context?.currentContext);
23355
24461
  node.append(
23356
- cards,
23357
24462
  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),
24463
+ initialPrompt ? renderStatsPromptInitial(initialPrompt) : statsPromptLegacyFallback("Initial prompt composition", payload?.lines?.promptInjection),
24464
+ snapshot ? renderStatsPromptSnapshot(snapshot) : statsPromptLegacyFallback("Prompt inventory", payload?.lines?.promptDetailed),
24465
+ currentContext ? renderStatsPromptCurrent(currentContext) : statsPromptLegacyFallback("Current context", payload?.lines?.tokenBreakdown),
23364
24466
  );
23365
24467
  return node;
23366
24468
  }
@@ -23382,8 +24484,9 @@ function renderStatsRaw(payload) {
23382
24484
  statsCommandOutputSection("Model comparison", "/stats-model-compare [days|all]", "Token share, spend share, average cost, and average output by model.", payload?.lines?.modelComparison),
23383
24485
  statsCommandOutputSection("Most expensive sessions", "/stats-most-expense [days|all]", "Highest-cost sessions in the selected range.", payload?.lines?.expensiveSessions),
23384
24486
  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),
24487
+ statsCommandOutputSection("Cache efficiency", "/stats-cache [days|all]", "Cached-input token share, cache read/write tokens, and token mix.", payload?.lines?.cache),
23386
24488
  statsCommandOutputSection("PI prompt breakdown", "/stats-pi detailed", "Export-backed initial prompt estimate with detailed prompt snapshot sections.", [...(payload?.lines?.promptInjection || []), "", ...(payload?.lines?.promptDetailed || [])]),
24489
+ statsCommandOutputSection("Current context breakdown", "/stats tokens", "Actual context usage plus the estimated source breakdown.", payload?.lines?.tokenBreakdown),
23387
24490
  );
23388
24491
  return node;
23389
24492
  }
@@ -23401,6 +24504,13 @@ function renderStatsOverlayPane(payload) {
23401
24504
  }
23402
24505
  }
23403
24506
 
24507
+ function activateStatsOverlayTab(tabId, { focus = false } = {}) {
24508
+ if (!STATS_OVERLAY_TABS.some((tab) => tab.id === tabId)) return;
24509
+ statsOverlayActiveTab = tabId;
24510
+ renderStatsOverlay();
24511
+ if (focus) document.getElementById(`statsOverlayTab-${tabId}`)?.focus();
24512
+ }
24513
+
23404
24514
  function renderStatsOverlay() {
23405
24515
  const payload = currentStatsOverlayPayload();
23406
24516
  if (!elements.statsOverlayDialog) return;
@@ -23409,8 +24519,10 @@ function renderStatsOverlay() {
23409
24519
  syncStatsScopeControls(statsOverlayLoading ? null : payload);
23410
24520
 
23411
24521
  const generated = payload?.generatedAt ? new Date(payload.generatedAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }) : "not loaded";
24522
+ const scopedSessions = payload ? statsNullableNumber(payload?.scopedSessionCount) : null;
24523
+ const sessionText = scopedSessions !== null ? `${scopedSessions} sessions in range` : `${payload?.sessionCount ?? 0} session files`;
23412
24524
  elements.statsOverlaySubtitle.textContent = payload
23413
- ? `${payload.scopeLabel || "stats"} · ${payload.sessionCount ?? 0} sessions · updated ${generated}`
24525
+ ? `${payload.scopeLabel || "stats"} · ${sessionText} · updated ${generated}`
23414
24526
  : "Run stats to load the browser dashboard.";
23415
24527
 
23416
24528
  elements.statsOverlayStatus.textContent = statsOverlayError || (statsOverlayLoading ? "Loading stats from the Pi stats extension…" : statsOverlayCalibrationMessage || (payload ? "" : "No stats payload loaded yet."));
@@ -23419,16 +24531,18 @@ function renderStatsOverlay() {
23419
24531
 
23420
24532
  elements.statsOverlayTabs.replaceChildren();
23421
24533
  for (const tab of STATS_OVERLAY_TABS) {
23422
- const button = make("button", tab.id === statsOverlayActiveTab ? "active" : "", tab.label);
24534
+ const active = tab.id === statsOverlayActiveTab;
24535
+ const button = make("button", active ? "active" : "", tab.label);
23423
24536
  button.type = "button";
24537
+ button.id = `statsOverlayTab-${tab.id}`;
23424
24538
  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
- });
24539
+ button.setAttribute("aria-selected", active ? "true" : "false");
24540
+ button.setAttribute("aria-controls", "statsOverlayBody");
24541
+ button.tabIndex = active ? 0 : -1;
24542
+ button.addEventListener("click", () => activateStatsOverlayTab(tab.id, { focus: true }));
23430
24543
  elements.statsOverlayTabs.append(button);
23431
24544
  }
24545
+ elements.statsOverlayBody.setAttribute("aria-labelledby", `statsOverlayTab-${statsOverlayActiveTab}`);
23432
24546
 
23433
24547
  elements.statsOverlayRefreshButton.disabled = statsOverlayLoading;
23434
24548
  elements.statsOverlayBody.replaceChildren(renderStatsOverlayPane(payload));
@@ -29063,7 +30177,8 @@ function appendToolOutput(parent, text, { label = "output", previewLines = 10, p
29063
30177
  const details = make("details", "tool-output-details");
29064
30178
  details.open = open || toolOutputGloballyExpanded;
29065
30179
  details.append(make("summary", "tool-output-summary", `${label} (${lines.length} lines; expand)`));
29066
- appendText(details, clean, "code-block tool-output-code");
30180
+ const output = appendText(details, clean, "code-block tool-output-code");
30181
+ bindToolDetailsScrollMode(output);
29067
30182
  parent.append(details);
29068
30183
 
29069
30184
  const preview = make("div", "tool-output-preview");
@@ -29166,8 +30281,10 @@ function toolRawDetailsReplacer(key, value) {
29166
30281
  function appendToolRawDetails(parent, tool) {
29167
30282
  const raw = JSON.stringify({ arguments: tool.args ?? {}, result: tool.result ?? null, details: tool.details ?? {} }, toolRawDetailsReplacer, 2);
29168
30283
  const details = make("details", "tool-raw-details");
30284
+ details.open = toolOutputGloballyExpanded;
29169
30285
  details.append(make("summary", "tool-raw-summary", "raw tool data"));
29170
- appendText(details, raw, "code-block tool-raw-code");
30286
+ const output = appendText(details, raw, "code-block tool-raw-code");
30287
+ bindToolDetailsScrollMode(output);
29171
30288
  parent.append(details);
29172
30289
  }
29173
30290
 
@@ -29370,7 +30487,7 @@ function renderWorkflowStatusStack(parent, message) {
29370
30487
  : `latest ${snapshot.fallback}`;
29371
30488
 
29372
30489
  const details = make("details", "workflow-status-stack-details");
29373
- details.open = !!message.isError;
30490
+ details.open = !!message.isError || toolOutputGloballyExpanded;
29374
30491
  const summary = make("summary", "workflow-status-stack-summary");
29375
30492
  summary.setAttribute("aria-label", `Workflow status updates, ${countLabel}; ${latestLabel}${message.isError ? "; contains an error" : ""}`);
29376
30493
  const heading = make("span", "workflow-status-stack-heading");
@@ -29460,21 +30577,166 @@ function toolDetailsStateKey(details, counts) {
29460
30577
  return `${base}|${index}`;
29461
30578
  }
29462
30579
 
29463
- function captureToolDetailsOpenState(root) {
29464
- const state = new Set();
30580
+ function toolDetailsScrollStateKey(node, counts) {
30581
+ const classKey = Array.from(node.classList || []).sort().join(".") || node.tagName.toLowerCase();
30582
+ const index = counts.get(classKey) || 0;
30583
+ counts.set(classKey, index + 1);
30584
+ return `${classKey}|${index}`;
30585
+ }
30586
+
30587
+ function bindToolDetailsScrollMode(node) {
30588
+ if (!node) return;
30589
+ node.dataset.toolScrollMode ||= "position";
30590
+ ensureToolInteractionDelegation();
30591
+ }
30592
+
30593
+ function captureToolDetailsInteractionState(root) {
30594
+ const state = new Map();
29465
30595
  const counts = new Map();
29466
30596
  for (const details of root.querySelectorAll("details")) {
29467
30597
  const key = toolDetailsStateKey(details, counts);
29468
- if (details.open) state.add(key);
30598
+ const summary = details.querySelector(":scope > summary");
30599
+ const scroll = new Map();
30600
+ const scrollCounts = new Map();
30601
+ if (details.open) {
30602
+ for (const node of details.querySelectorAll(".tool-output-code, .tool-raw-code, :scope > .message-body")) {
30603
+ bindToolDetailsScrollMode(node);
30604
+ scroll.set(toolDetailsScrollStateKey(node, scrollCounts), {
30605
+ source: node,
30606
+ mode: node.dataset.toolScrollMode || "position",
30607
+ scrollTop: node.scrollTop,
30608
+ scrollLeft: node.scrollLeft,
30609
+ });
30610
+ }
30611
+ }
30612
+ state.set(key, {
30613
+ open: details.open,
30614
+ summarySource: summary,
30615
+ summaryFocused: document.activeElement === summary,
30616
+ scroll,
30617
+ });
29469
30618
  }
29470
30619
  return state;
29471
30620
  }
29472
30621
 
29473
- function restoreToolDetailsOpenState(root, state) {
30622
+ function restoreToolDetailsInteractionState(root, state) {
29474
30623
  if (!state?.size) return;
29475
30624
  const counts = new Map();
29476
30625
  for (const details of root.querySelectorAll("details")) {
29477
- if (state.has(toolDetailsStateKey(details, counts))) details.open = true;
30626
+ const snapshot = state.get(toolDetailsStateKey(details, counts));
30627
+ if (!snapshot) continue;
30628
+ details.open = snapshot.open;
30629
+ const summary = details.querySelector(":scope > summary");
30630
+ if (snapshot.summaryFocused && document.activeElement !== summary && !isMeaningfulConnectedFocus(document.activeElement)) {
30631
+ try {
30632
+ summary?.focus({ preventScroll: true });
30633
+ } catch {
30634
+ summary?.focus();
30635
+ }
30636
+ }
30637
+ const scrollCounts = new Map();
30638
+ for (const node of details.querySelectorAll(".tool-output-code, .tool-raw-code, :scope > .message-body")) {
30639
+ bindToolDetailsScrollMode(node);
30640
+ const scrollSnapshot = snapshot.scroll.get(toolDetailsScrollStateKey(node, scrollCounts));
30641
+ if (!scrollSnapshot || (node === scrollSnapshot.source && node.scrollTop === scrollSnapshot.scrollTop && node.scrollLeft === scrollSnapshot.scrollLeft)) continue;
30642
+ node.dataset.toolScrollMode = scrollSnapshot.mode;
30643
+ requestAnimationFrame(() => {
30644
+ if (!node.isConnected) return;
30645
+ const maxScrollTop = Math.max(0, node.scrollHeight - node.clientHeight);
30646
+ const maxScrollLeft = Math.max(0, node.scrollWidth - node.clientWidth);
30647
+ node.scrollTop = scrollSnapshot.mode === "follow-end"
30648
+ ? maxScrollTop
30649
+ : Math.min(Math.max(0, scrollSnapshot.scrollTop), maxScrollTop);
30650
+ node.scrollLeft = Math.min(Math.max(0, scrollSnapshot.scrollLeft), maxScrollLeft);
30651
+ });
30652
+ }
30653
+ }
30654
+ }
30655
+
30656
+ const INTERACTED_TOOL_BUBBLE_LIMIT = 16;
30657
+ const TOOL_INTERACTION_BUBBLE_SELECTOR = ".message.toolCall, .message.toolExecution, .message.toolResult, .message.bashExecution, .message.workflowStatusStack, .message.compactionSummary";
30658
+ const TOOL_INTERACTION_SCROLL_SELECTOR = ".tool-output-code, .tool-raw-code, .message-collapse > .message-body";
30659
+ const interactedToolBubbles = new Set();
30660
+ let toolInteractionDelegationBound = false;
30661
+
30662
+ function markInteractedToolBubble(bubble) {
30663
+ if (!bubble?.matches?.(TOOL_INTERACTION_BUBBLE_SELECTOR)) return;
30664
+ interactedToolBubbles.delete(bubble);
30665
+ interactedToolBubbles.add(bubble);
30666
+ while (interactedToolBubbles.size > INTERACTED_TOOL_BUBBLE_LIMIT) {
30667
+ interactedToolBubbles.delete(interactedToolBubbles.values().next().value);
30668
+ }
30669
+ }
30670
+
30671
+ function ensureToolInteractionDelegation() {
30672
+ if (toolInteractionDelegationBound || !elements.chat) return;
30673
+ toolInteractionDelegationBound = true;
30674
+ const markFromEvent = (event) => {
30675
+ const target = event.target instanceof Element ? event.target : null;
30676
+ const bubble = target?.closest?.(TOOL_INTERACTION_BUBBLE_SELECTOR);
30677
+ if (bubble && elements.chat.contains(bubble)) markInteractedToolBubble(bubble);
30678
+ };
30679
+ elements.chat.addEventListener("toggle", markFromEvent, true);
30680
+ elements.chat.addEventListener("focusin", markFromEvent);
30681
+ elements.chat.addEventListener("scroll", (event) => {
30682
+ const node = event.target instanceof HTMLElement ? event.target : null;
30683
+ if (node?.matches?.(TOOL_INTERACTION_SCROLL_SELECTOR)) {
30684
+ const maxScrollTop = Math.max(0, node.scrollHeight - node.clientHeight);
30685
+ node.dataset.toolScrollMode = maxScrollTop > 0 && maxScrollTop - node.scrollTop <= 24 ? "follow-end" : "position";
30686
+ }
30687
+ markFromEvent(event);
30688
+ }, true);
30689
+ }
30690
+
30691
+ function toolInteractionBubbleIdentity(bubble) {
30692
+ const role = ["toolCall", "toolExecution", "toolResult", "bashExecution", "workflowStatusStack", "compactionSummary"]
30693
+ .find((candidate) => bubble.classList.contains(candidate)) || "tool";
30694
+ return {
30695
+ role,
30696
+ toolCallId: bubble.dataset.toolCallId || "",
30697
+ itemKey: bubble.dataset.itemKey || "",
30698
+ transcriptMessageKey: bubble.dataset.transcriptMessageKey || "",
30699
+ messageIndex: bubble.dataset.messageIndex || "",
30700
+ };
30701
+ }
30702
+
30703
+ function captureInteractedToolInteractionState() {
30704
+ const snapshots = [];
30705
+ for (const bubble of [...interactedToolBubbles]) {
30706
+ if (!bubble.isConnected || !elements.chat.contains(bubble)) {
30707
+ interactedToolBubbles.delete(bubble);
30708
+ continue;
30709
+ }
30710
+ snapshots.push({
30711
+ source: bubble,
30712
+ identity: toolInteractionBubbleIdentity(bubble),
30713
+ details: captureToolDetailsInteractionState(bubble),
30714
+ });
30715
+ }
30716
+ return snapshots;
30717
+ }
30718
+
30719
+ function toolInteractionBubbleForSnapshot(snapshot) {
30720
+ if (snapshot.source?.isConnected && elements.chat.contains(snapshot.source)) return snapshot.source;
30721
+ const { role, toolCallId, itemKey, transcriptMessageKey, messageIndex } = snapshot.identity || {};
30722
+ const selector = `.message.${CSS.escape(role || "tool")}`;
30723
+ for (const bubble of elements.chat.querySelectorAll(selector)) {
30724
+ if (toolCallId && bubble.dataset.toolCallId === toolCallId) return bubble;
30725
+ if (!toolCallId && itemKey && bubble.dataset.itemKey === itemKey) return bubble;
30726
+ if (!toolCallId && !itemKey && transcriptMessageKey && bubble.dataset.transcriptMessageKey === transcriptMessageKey) return bubble;
30727
+ if (!toolCallId && !itemKey && !transcriptMessageKey && messageIndex && bubble.dataset.messageIndex === messageIndex) return bubble;
30728
+ }
30729
+ return null;
30730
+ }
30731
+
30732
+ function restoreInteractedToolInteractionState(snapshots) {
30733
+ for (const snapshot of snapshots || []) {
30734
+ const bubble = toolInteractionBubbleForSnapshot(snapshot);
30735
+ if (!bubble) continue;
30736
+ ensureToolInteractionDelegation();
30737
+ restoreToolDetailsInteractionState(bubble, snapshot.details);
30738
+ interactedToolBubbles.delete(snapshot.source);
30739
+ markInteractedToolBubble(bubble);
29478
30740
  }
29479
30741
  }
29480
30742
 
@@ -29530,10 +30792,10 @@ function updateLiveToolCard(bubble, message) {
29530
30792
  kind: "reconcile",
29531
30793
  surfaces: [body],
29532
30794
  mutate: () => {
29533
- const detailsOpenState = captureToolDetailsOpenState(body);
30795
+ const detailsInteractionState = captureToolDetailsInteractionState(body);
29534
30796
  transcriptRenderer.replaceChildren(body);
29535
30797
  renderToolExecution(body, message);
29536
- restoreToolDetailsOpenState(body, detailsOpenState);
30798
+ restoreToolDetailsInteractionState(body, detailsInteractionState);
29537
30799
  transcriptRenderer.ownSurface(body, { messageKey, kind: "tool-execution", segment: "0" });
29538
30800
  bubble._toolRenderSignature = nextRenderSignature;
29539
30801
  },
@@ -29779,6 +31041,7 @@ function createMessageBubble(message, { streaming = false, messageIndex = -1, tr
29779
31041
 
29780
31042
  if (isCollapsibleOutput) {
29781
31043
  const details = make("details", `message-collapse${compactThinkingAggregate ? " compact-thinking-disclosure" : ""}`);
31044
+ bindToolDetailsScrollMode(body);
29782
31045
  if (compactThinkingAggregate) {
29783
31046
  const defaultExpanded = message.compactThinkingDefaultExpanded === true;
29784
31047
  details.open = compactThinkingDisclosureExpanded(message.compactThinkingKey, defaultExpanded);
@@ -29797,6 +31060,7 @@ function createMessageBubble(message, { streaming = false, messageIndex = -1, tr
29797
31060
  bubble.append(header, body);
29798
31061
  }
29799
31062
  ownTranscriptBubble(bubble, body, message, { itemKey, streaming, transient, segmentId });
31063
+ ensureToolInteractionDelegation();
29800
31064
  if (message.role !== "workflowStatusStack") attachMessageCopyButton(bubble, message, body);
29801
31065
  attachMessageEditRetryButton(bubble, message, messageIndex, { streaming, transient });
29802
31066
  if (!streaming && !transient) renderActionFeedbackControls(bubble, message, messageIndex);
@@ -30465,53 +31729,107 @@ function chatTextSelectionPoint(surface, offset) {
30465
31729
  return last ? { node: last, offset: last.data.length } : { node: surface, offset: 0 };
30466
31730
  }
30467
31731
 
31732
+ function chatTextSelectionEndpoint(surface, node, offset) {
31733
+ const textOffset = chatTextSelectionOffset(surface, node, offset);
31734
+ if (textOffset === null) return null;
31735
+ const bubble = surface.closest(".message");
31736
+ const surfaceText = surface.textContent || "";
31737
+ const contextRadius = 48;
31738
+ return {
31739
+ source: surface,
31740
+ itemKey: bubble?.dataset?.transcriptMessageKey || bubble?.dataset?.itemKey || "",
31741
+ surfaceKey: surface.dataset?.transcriptSurfaceKey || "",
31742
+ streaming: bubble?.classList?.contains("streaming") === true || bubble?.classList?.contains("compact-live-output") === true,
31743
+ offset: textOffset,
31744
+ before: surfaceText.slice(Math.max(0, textOffset - contextRadius), textOffset),
31745
+ after: surfaceText.slice(textOffset, textOffset + contextRadius),
31746
+ };
31747
+ }
31748
+
30468
31749
  function captureChatTextSelection(expectedSurface = null) {
30469
31750
  const selection = window.getSelection?.();
30470
31751
  if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return null;
30471
31752
  const anchorSurface = chatTextSelectionSurface(selection.anchorNode);
30472
31753
  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);
31754
+ if (!anchorSurface || !focusSurface || (expectedSurface && (anchorSurface !== expectedSurface || focusSurface !== expectedSurface))) return null;
31755
+ const anchor = chatTextSelectionEndpoint(anchorSurface, selection.anchorNode, selection.anchorOffset);
31756
+ const focus = chatTextSelectionEndpoint(focusSurface, selection.focusNode, selection.focusOffset);
30476
31757
  const text = selection.toString();
30477
- if (anchorOffset === null || focusOffset === null || !text) return null;
30478
- const bubble = anchorSurface.closest(".message");
31758
+ if (!anchor || !focus || !text) return null;
30479
31759
  return {
30480
31760
  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,
31761
+ source: anchor.source,
31762
+ itemKey: anchor.itemKey === focus.itemKey ? anchor.itemKey : "",
31763
+ streaming: anchor.streaming || focus.streaming,
31764
+ anchorOffset: anchor.offset,
31765
+ focusOffset: focus.offset,
31766
+ anchor,
31767
+ focus,
30486
31768
  text,
30487
31769
  };
30488
31770
  }
30489
31771
 
30490
- function chatTextSelectionMatch(surface, snapshot) {
30491
- const anchor = chatTextSelectionPoint(surface, snapshot.anchorOffset);
30492
- const focus = chatTextSelectionPoint(surface, snapshot.focusOffset);
31772
+ function chatTextSelectionEndpointPoint(surface, endpoint) {
31773
+ const surfaceText = surface.textContent || "";
31774
+ const contextMatches = (offset) => surfaceText.slice(Math.max(0, offset - endpoint.before.length), offset) === endpoint.before
31775
+ && surfaceText.slice(offset, offset + endpoint.after.length) === endpoint.after;
31776
+ let offset = endpoint.offset;
31777
+ if (!contextMatches(offset)) {
31778
+ const context = `${endpoint.before}${endpoint.after}`;
31779
+ const index = context ? surfaceText.indexOf(context) : -1;
31780
+ if (index < 0 || surfaceText.indexOf(context, index + 1) !== -1) return null;
31781
+ offset = index + endpoint.before.length;
31782
+ if (!contextMatches(offset)) return null;
31783
+ }
31784
+ return chatTextSelectionPoint(surface, offset);
31785
+ }
31786
+
31787
+ function chatTextSelectionPointPrecedes(anchor, focus) {
31788
+ if (anchor.node === focus.node) return anchor.offset <= focus.offset;
31789
+ return !!(anchor.node.compareDocumentPosition(focus.node) & Node.DOCUMENT_POSITION_FOLLOWING);
31790
+ }
31791
+
31792
+ function chatTextSelectionSpansSurfaces(snapshot) {
31793
+ return snapshot.anchor.itemKey !== snapshot.focus.itemKey || snapshot.anchor.surfaceKey !== snapshot.focus.surfaceKey;
31794
+ }
31795
+
31796
+ function chatTextSelectionMatch(anchorSurface, focusSurface, snapshot) {
31797
+ const anchor = chatTextSelectionEndpointPoint(anchorSurface, snapshot.anchor);
31798
+ const focus = chatTextSelectionEndpointPoint(focusSurface, snapshot.focus);
31799
+ if (!anchor || !focus) return null;
30493
31800
  const range = document.createRange();
30494
- const anchorFirst = snapshot.anchorOffset <= snapshot.focusOffset;
31801
+ const anchorFirst = chatTextSelectionPointPrecedes(anchor, focus);
30495
31802
  try {
30496
31803
  range.setStart(anchorFirst ? anchor.node : focus.node, anchorFirst ? anchor.offset : focus.offset);
30497
31804
  range.setEnd(anchorFirst ? focus.node : anchor.node, anchorFirst ? focus.offset : anchor.offset);
30498
31805
  } catch {
30499
31806
  return null;
30500
31807
  }
30501
- return range.toString() === snapshot.text ? { anchor, focus, range } : null;
31808
+ const text = range.toString();
31809
+ return text && (chatTextSelectionSpansSurfaces(snapshot) || text === snapshot.text) ? { anchor, focus, range } : null;
30502
31810
  }
30503
31811
 
30504
- function chatTextSelectionCandidates(snapshot) {
31812
+ function chatTextSelectionCandidates(snapshot, endpointName) {
31813
+ const endpoint = snapshot?.[endpointName];
31814
+ if (!endpoint) return [];
30505
31815
  const candidates = [];
30506
31816
  const add = (surface) => {
30507
31817
  if (surface && elements.chat.contains(surface) && !candidates.includes(surface)) candidates.push(surface);
30508
31818
  };
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);
31819
+ add(endpoint.source?.isConnected ? endpoint.source : null);
31820
+ if (endpoint.surfaceKey) {
31821
+ for (const surface of elements.chat.querySelectorAll("[data-transcript-surface-key]")) {
31822
+ if (surface.dataset.transcriptSurfaceKey === endpoint.surfaceKey) add(surface);
31823
+ }
31824
+ }
31825
+ if (endpoint.itemKey) {
31826
+ for (const bubble of elements.chat.querySelectorAll(".message[data-item-key], .message[data-transcript-message-key]")) {
31827
+ const key = bubble.dataset.transcriptMessageKey || bubble.dataset.itemKey || "";
31828
+ if (key !== endpoint.itemKey) continue;
31829
+ for (const surface of bubble.querySelectorAll("[data-transcript-surface], .markdown-body, .compact-live-text")) add(surface);
31830
+ }
30513
31831
  }
30514
- if (snapshot.streaming) {
31832
+ if (endpoint.streaming) {
30515
31833
  const liveReplacement = [...elements.chat.querySelectorAll(".message.assistant [data-transcript-surface], .message.assistant .markdown-body, .message.assistant .compact-live-text")].reverse();
30516
31834
  for (const surface of liveReplacement) add(surface);
30517
31835
  }
@@ -30525,23 +31843,27 @@ function restoreChatTextSelection(snapshot) {
30525
31843
  const currentText = selection.rangeCount && !selection.isCollapsed ? selection.toString() : "";
30526
31844
  const currentAnchorSurface = chatTextSelectionSurface(selection.anchorNode);
30527
31845
  const currentFocusSurface = chatTextSelectionSurface(selection.focusNode);
30528
- const candidates = chatTextSelectionCandidates(snapshot);
30529
- if (currentText === snapshot.text && currentAnchorSurface === currentFocusSurface && candidates.includes(currentAnchorSurface)) return;
31846
+ const anchorCandidates = chatTextSelectionCandidates(snapshot, "anchor");
31847
+ const focusCandidates = chatTextSelectionCandidates(snapshot, "focus");
31848
+ const currentEndpointsMatch = anchorCandidates.includes(currentAnchorSurface) && focusCandidates.includes(currentFocusSurface);
31849
+ if (currentEndpointsMatch && (chatTextSelectionSpansSurfaces(snapshot) ? !!currentText : currentText === snapshot.text)) return;
30530
31850
  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);
31851
+ for (const anchorSurface of anchorCandidates) {
31852
+ for (const focusSurface of focusCandidates) {
31853
+ const match = chatTextSelectionMatch(anchorSurface, focusSurface, snapshot);
31854
+ if (!match) continue;
31855
+ try {
31856
+ selection.removeAllRanges();
31857
+ if (typeof selection.setBaseAndExtent === "function") {
31858
+ selection.setBaseAndExtent(match.anchor.node, match.anchor.offset, match.focus.node, match.focus.offset);
31859
+ } else {
31860
+ selection.addRange(match.range);
31861
+ }
31862
+ } catch {
31863
+ // A stale DOM range should not interfere with the authoritative transcript render.
30540
31864
  }
30541
- } catch {
30542
- // A stale DOM range should not interfere with the authoritative transcript render.
31865
+ return;
30543
31866
  }
30544
- return;
30545
31867
  }
30546
31868
  }
30547
31869
 
@@ -30563,6 +31885,7 @@ function pruneDisconnectedLiveToolCards() {
30563
31885
 
30564
31886
  function renderAllMessages({ preserveScroll = false, forceRebuild = false } = {}) {
30565
31887
  const selectionSnapshot = captureChatTextSelection();
31888
+ const toolInteractionSnapshots = captureInteractedToolInteractionState();
30566
31889
  const shouldFollow = !preserveScroll && (autoFollowChat || isChatNearBottom());
30567
31890
  const previousScrollTop = elements.chat.scrollTop;
30568
31891
  if (!autoFollowChat) chatPausedScrollRestoreUntil = performance.now() + CHAT_PROGRAMMATIC_SCROLL_GRACE_MS;
@@ -30631,7 +31954,7 @@ function renderAllMessages({ preserveScroll = false, forceRebuild = false } = {}
30631
31954
  else if (elements.workspaceDashboard) elements.workspaceDashboard.hidden = workspaceDashboardCollapsed;
30632
31955
  renderedTranscriptState = { epoch, entries: nextEntries.map(({ key, sig }) => ({ key, sig })) };
30633
31956
  rememberActionEntries(transcriptItems);
30634
- applyToolOutputExpansionToDom();
31957
+ restoreInteractedToolInteractionState(toolInteractionSnapshots);
30635
31958
  runIndicatorRemovalDeferred = false;
30636
31959
  renderRunIndicator({ scroll: false });
30637
31960
  updateStickyUserPromptButton();
@@ -36508,7 +37831,13 @@ async function sendDialogResponse(payload) {
36508
37831
  if (responseId && activeDialog && String(activeDialog.id || "") !== responseId) return;
36509
37832
  if (elements.dialog.open) elements.dialog.close();
36510
37833
  activeDialog = null;
36511
- if (runIndicatorIsActive()) setRunIndicatorActivity("Continuing after your response…");
37834
+ if (runIndicatorIsActive()) {
37835
+ setRunIndicatorActivity("Continuing after your response…");
37836
+ // Extension commands can continue background work after Pi has already
37837
+ // returned to an idle canonical state. Reconcile promptly so this local
37838
+ // handoff label cannot survive the workflow that requested the dialog.
37839
+ scheduleRefreshState(120, tabContext);
37840
+ }
36512
37841
  showNextDialog();
36513
37842
  }
36514
37843
  }
@@ -37659,6 +38988,18 @@ elements.statsOverlayCustomDays?.addEventListener("keydown", (event) => {
37659
38988
  event.preventDefault();
37660
38989
  requestStatsOverlayRefresh();
37661
38990
  });
38991
+ elements.statsOverlayTabs?.addEventListener("keydown", (event) => {
38992
+ const index = STATS_OVERLAY_TABS.findIndex((tab) => tab.id === statsOverlayActiveTab);
38993
+ if (index < 0) return;
38994
+ let nextIndex = -1;
38995
+ if (event.key === "ArrowRight" || event.key === "ArrowDown") nextIndex = (index + 1) % STATS_OVERLAY_TABS.length;
38996
+ else if (event.key === "ArrowLeft" || event.key === "ArrowUp") nextIndex = (index - 1 + STATS_OVERLAY_TABS.length) % STATS_OVERLAY_TABS.length;
38997
+ else if (event.key === "Home") nextIndex = 0;
38998
+ else if (event.key === "End") nextIndex = STATS_OVERLAY_TABS.length - 1;
38999
+ if (nextIndex < 0) return;
39000
+ event.preventDefault();
39001
+ activateStatsOverlayTab(STATS_OVERLAY_TABS[nextIndex].id, { focus: true });
39002
+ });
37662
39003
  elements.statsOverlayCloseButton?.addEventListener("click", () => elements.statsOverlayDialog?.close());
37663
39004
  elements.statsOverlayDialog?.querySelector("form")?.addEventListener("submit", (event) => event.preventDefault());
37664
39005
  elements.gitWorkflowSteps.addEventListener("click", (event) => {
@@ -38227,8 +39568,18 @@ elements.piVersionButton?.addEventListener("click", () => {
38227
39568
  openPiReleaseNotes().catch((error) => addEvent(error.message || String(error), "error"));
38228
39569
  });
38229
39570
  elements.webuiVersionButton?.addEventListener("click", () => {
39571
+ openWebuiPackageDialog().catch((error) => addEvent(error.message || String(error), "error"));
39572
+ });
39573
+ elements.piComponentUpdateButton?.addEventListener("click", () => {
39574
+ startComponentUpdate("pi").catch((error) => addEvent(error.message || String(error), "error"));
39575
+ });
39576
+ elements.webuiComponentUpdateButton?.addEventListener("click", () => {
39577
+ startComponentUpdate("webui").catch((error) => addEvent(error.message || String(error), "error"));
39578
+ });
39579
+ elements.webuiPackageNpmButton?.addEventListener("click", () => {
38230
39580
  confirmOpenWebuiNpmPage().catch((error) => addEvent(error.message || String(error), "error"));
38231
39581
  });
39582
+ elements.webuiPackageCloseButton?.addEventListener("click", () => elements.webuiPackageDialog?.close());
38232
39583
  elements.piReleaseNotesCloseButton?.addEventListener("click", () => elements.piReleaseNotesDialog?.close());
38233
39584
  elements.toggleSidePanelButton.addEventListener("click", () => {
38234
39585
  setSidePanelCollapsed(true);
@@ -38521,6 +39872,7 @@ window.addEventListener("beforeunload", persistMobileContinuityState);
38521
39872
  window.addEventListener("storage", (event) => {
38522
39873
  if (event.key === OPTIONAL_FEATURES_STORAGE_KEY) reconcileDisabledOptionalFeaturesFromStorage();
38523
39874
  if (event.key === SIDE_PANEL_SECTION_VISIBILITY_STORAGE_KEY) restoreSidePanelSectionVisibility();
39875
+ if (event.key === SIDE_PANEL_SECTION_ORDER_STORAGE_KEY) restoreSidePanelSectionOrder();
38524
39876
  if (event.key === SIDE_PANEL_WIDTH_STORAGE_KEY) {
38525
39877
  const width = readStoredSidePanelWidth();
38526
39878
  if (width && !isSidePanelOverlayView()) applySidePanelWidth(width);
@@ -38943,6 +40295,7 @@ restoreToolOutputExpansionSetting();
38943
40295
  restoreWorkspaceDashboardState();
38944
40296
  restoreInterfaceDensity();
38945
40297
  initializeTerminalHeaderTooltips();
40298
+ restoreSidePanelSectionOrder();
38946
40299
  restoreSidePanelSectionVisibility();
38947
40300
  restoreSidePanelSectionState();
38948
40301
  bindSidePanelSectionToggles();