@firstpick/pi-package-webui 0.9.6 → 0.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +7 -3
  2. package/bin/pi-webui.mjs +367 -72
  3. package/lib/git-workflow-preferences.mjs +21 -1
  4. package/lib/session-tree-event-targets.mjs +70 -0
  5. package/lib/subagent-launch-policy.mjs +375 -0
  6. package/lib/subagent-launch-slots.mjs +2 -1
  7. package/package.json +1 -1
  8. package/public/app.js +721 -35
  9. package/public/index.html +38 -2
  10. package/public/service-worker.js +1 -1
  11. package/public/styles.css +254 -3
  12. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  13. package/tests/browser/control-visibility.spec.mjs +141 -2
  14. package/tests/browser/events-tree-context-menu.spec.mjs +240 -0
  15. package/tests/browser/guided-git-fallback.spec.mjs +153 -0
  16. package/tests/codex-fast-mode-static.test.mjs +2 -2
  17. package/tests/compact-sections-static.test.mjs +4 -0
  18. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  19. package/tests/control-visibility-static.test.mjs +66 -3
  20. package/tests/controls-layout-static.test.mjs +3 -3
  21. package/tests/events-tree-context-menu-static.test.mjs +131 -0
  22. package/tests/fast-mode-client-static.test.mjs +5 -2
  23. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  24. package/tests/file-viewer-image-static.test.mjs +3 -3
  25. package/tests/git-workflow-preferences.test.mjs +30 -1
  26. package/tests/guided-git-fallback-runtime.test.mjs +418 -0
  27. package/tests/guided-git-fallback-ui-static.test.mjs +60 -0
  28. package/tests/guided-git-message-reliability-static.test.mjs +8 -7
  29. package/tests/intercom-conversation-viewer-static.test.mjs +3 -3
  30. package/tests/main-output-loading-static.test.mjs +3 -3
  31. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  32. package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
  33. package/tests/mobile-foundation-static.test.mjs +3 -3
  34. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  35. package/tests/mobile-static.test.mjs +7 -5
  36. package/tests/open-issue-wizard-static.test.mjs +1 -1
  37. package/tests/persistent-ui-layout-static.test.mjs +3 -3
  38. package/tests/prompt-input-vertical-scroll-static.test.mjs +3 -3
  39. package/tests/questionnaire-dialog.test.mjs +3 -3
  40. package/tests/remote-auth-settings-harness.test.mjs +23 -0
  41. package/tests/resource-defaults-helper.test.mjs +12 -0
  42. package/tests/session-sampling-helper.test.mjs +1 -0
  43. package/tests/session-sampling-ui-static.test.mjs +3 -3
  44. package/tests/session-tree-event-targets.test.mjs +106 -0
  45. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  46. package/tests/subagent-launch-policy.test.mjs +532 -0
  47. package/tests/subagent-observability-static.test.mjs +2 -2
  48. package/tests/subagents-helper.test.mjs +211 -1
  49. package/tests/syntax-highlighting-static.test.mjs +3 -3
  50. package/tests/tab-close-continuity-static.test.mjs +23 -0
  51. package/tests/theme-customizer-static.test.mjs +1 -1
  52. package/webui-rpc-helper.mjs +220 -3
package/public/app.js CHANGED
@@ -358,6 +358,14 @@ const elements = {
358
358
  sidePanelContextMenu: $("#sidePanelContextMenu"),
359
359
  visibilityContextMenu: $("#visibilityContextMenu"),
360
360
  gitFooterContextMenu: $("#gitFooterContextMenu"),
361
+ eventTreeContextMenu: $("#eventTreeContextMenu"),
362
+ eventFilterSelect: $("#eventFilterSelect"),
363
+ eventFilterStatus: $("#eventFilterStatus"),
364
+ eventFilterEmpty: $("#eventFilterEmpty"),
365
+ eventDisplayDetailedAction: $("#eventDisplayDetailedAction"),
366
+ eventDisplayCompactAction: $("#eventDisplayCompactAction"),
367
+ eventTreeContextMenuAction: $("#eventTreeContextMenuAction"),
368
+ eventTreeContextMenuStatus: $("#eventTreeContextMenuStatus"),
361
369
  sidePanelResizeHandle: $("#sidePanelResizeHandle"),
362
370
  sidePanelResizeHandleLeft: $("#sidePanelLeftResizeHandle"),
363
371
  sidePanelLeftExpandButton: $("#sidePanelLeftExpandButton"),
@@ -566,6 +574,12 @@ const elements = {
566
574
  appRunnerInfoDialog: $("#appRunnerInfoDialog"),
567
575
  appRunnerInfoBody: $("#appRunnerInfoBody"),
568
576
  appRunnerInfoCloseButton: $("#appRunnerInfoCloseButton"),
577
+ controlVisibilitySetupDialog: $("#controlVisibilitySetupDialog"),
578
+ controlVisibilitySetupBody: $("#controlVisibilitySetupBody"),
579
+ controlVisibilitySetupStatus: $("#controlVisibilitySetupStatus"),
580
+ controlVisibilitySetupShowAllButton: $("#controlVisibilitySetupShowAllButton"),
581
+ controlVisibilitySetupResetButton: $("#controlVisibilitySetupResetButton"),
582
+ controlVisibilitySetupCloseButton: $("#controlVisibilitySetupCloseButton"),
569
583
  gitFooterVisibilityDialog: $("#gitFooterVisibilityDialog"),
570
584
  gitFooterVisibilityBody: $("#gitFooterVisibilityBody"),
571
585
  gitFooterVisibilityStatus: $("#gitFooterVisibilityStatus"),
@@ -593,6 +607,9 @@ const transcriptRenderer = createTranscriptRenderer({
593
607
  });
594
608
 
595
609
  const PI_WEBUI_NPM_URL = "https://www.npmjs.com/package/@firstpick/pi-package-webui";
610
+ const EVENT_DISPLAY_MODE_STORAGE_KEY = "pi-webui-event-display-mode-v1";
611
+ const EVENT_FILTER_STORAGE_KEY = "pi-webui-event-filter-v1";
612
+ const EVENT_FILTER_VALUES = new Set(["all", "errors", "warnings", "tools", "tree"]);
596
613
 
597
614
  let currentState = null;
598
615
  let tabStateCache = new Map();
@@ -626,6 +643,10 @@ let fileViewerSearchTimer = null;
626
643
  let fileContextMenuState = null;
627
644
  let sidePanelContextMenuState = null;
628
645
  let gitFooterContextMenuState = null;
646
+ let eventTreeContextMenuState = null;
647
+ let eventDisplayMode = readStoredEventDisplayMode();
648
+ let eventFilter = readStoredEventFilter();
649
+ const toolEventStartedAt = new Map();
629
650
  let sidePanelSectionEditMode = false;
630
651
  let sidePanelSectionPointerDrag = null;
631
652
  let sidePanelSectionLastDragOverKey = "";
@@ -1034,6 +1055,7 @@ const supervisorEventCursors = new Map();
1034
1055
  const supervisorRetiredEpochs = new Map();
1035
1056
  const supervisorGapWarnings = new Set();
1036
1057
  const supervisorContinuityRefreshes = new Map();
1058
+ const closingTerminalTabIds = new Set();
1037
1059
  const supervisorEnvelopeWarnings = new Set();
1038
1060
  let activeDialog = null;
1039
1061
  let activeDialogCancel = null;
@@ -3516,6 +3538,12 @@ function createGitWorkflowState() {
3516
3538
  ...resetGitWorkflowManualCommitDefaultPatch(),
3517
3539
  messageRequestedAt: 0,
3518
3540
  messageGenerationId: "",
3541
+ generationId: "",
3542
+ generationKind: "",
3543
+ generationAccepted: false,
3544
+ fallbackStarted: false,
3545
+ fallbackLifecycleKeys: new Set(),
3546
+ pendingFallbackLifecycleEvents: [],
3519
3547
  branchName: "",
3520
3548
  branchNameRequestedAt: 0,
3521
3549
  actionsDone: createGitWorkflowActionsDone(),
@@ -4553,6 +4581,7 @@ function showSidePanelContextMenu(event) {
4553
4581
  closeFileContextMenu({ returnFocus: false });
4554
4582
  closeGitPanelContextMenu({ returnFocus: false });
4555
4583
  closeSidePanelContextMenu({ returnFocus: false });
4584
+ closeEventTreeContextMenu({ returnFocus: false });
4556
4585
 
4557
4586
  const menu = elements.sidePanelContextMenu;
4558
4587
  const eventTrigger = event.currentTarget;
@@ -12777,6 +12806,7 @@ function showFileContextMenu(event, entry) {
12777
12806
  event.stopPropagation();
12778
12807
  closeGitPanelContextMenu({ returnFocus: false });
12779
12808
  closeSidePanelContextMenu({ returnFocus: false });
12809
+ closeEventTreeContextMenu({ returnFocus: false });
12780
12810
  const path = normalizeFileTreePath(entry?.path || "");
12781
12811
  fileContextMenuState = { entry: { ...entry, path }, trigger: event.currentTarget || document.activeElement };
12782
12812
  const menu = elements.fileContextMenu;
@@ -13550,6 +13580,7 @@ function applyControlVisibility(hiddenIdsOverride) {
13550
13580
  }
13551
13581
  // Hiding composer actions leaves grid holes; repack/restore the saved layout.
13552
13582
  if (composerChanged) scheduleComposerActionSlotLayoutRestore();
13583
+ refreshControlVisibilitySetupDialog();
13553
13584
  }
13554
13585
 
13555
13586
  function persistControlVisibilityHiddenIds(hiddenIds) {
@@ -13574,6 +13605,71 @@ function resetControlVisibilityDefaults() {
13574
13605
  }
13575
13606
 
13576
13607
  let visibilityContextMenuState = null;
13608
+ let controlVisibilitySetupFocusReturn = null;
13609
+
13610
+ function setControlVisibilitySetupStatus(message = "") {
13611
+ if (elements.controlVisibilitySetupStatus) elements.controlVisibilitySetupStatus.textContent = message;
13612
+ }
13613
+
13614
+ function renderControlVisibilitySetupDialog() {
13615
+ const body = elements.controlVisibilitySetupBody;
13616
+ if (!body) return;
13617
+ const groups = CONTROL_VISIBILITY_GROUP_LABELS.map(([groupId, groupLabel], groupIndex) => {
13618
+ const fieldset = make("fieldset", "control-visibility-setup-group");
13619
+ fieldset.append(make("legend", "control-visibility-setup-group-label", groupLabel));
13620
+ const grid = make("div", "control-visibility-setup-grid");
13621
+ for (const [entryIndex, entry] of CONTROL_VISIBILITY_CATALOG.filter((item) => item.group === groupId).entries()) {
13622
+ const label = make("label", "control-visibility-setup-toggle");
13623
+ const checkbox = document.createElement("input");
13624
+ checkbox.type = "checkbox";
13625
+ checkbox.id = `controlVisibilitySetupToggle-${groupIndex}-${entryIndex}`;
13626
+ checkbox.dataset.visibilitySetupId = entry.id;
13627
+ checkbox.setAttribute("aria-label", `Show ${entry.label}`);
13628
+ label.htmlFor = checkbox.id;
13629
+ label.append(checkbox, make("span", "control-visibility-setup-toggle-label", entry.label));
13630
+ grid.append(label);
13631
+ }
13632
+ fieldset.append(grid);
13633
+ return fieldset;
13634
+ });
13635
+ body.replaceChildren(...groups);
13636
+ }
13637
+
13638
+ function refreshControlVisibilitySetupDialog() {
13639
+ const dialog = elements.controlVisibilitySetupDialog;
13640
+ const body = elements.controlVisibilitySetupBody;
13641
+ if (!dialog?.open || !body) return;
13642
+ const hiddenSet = new Set(userControlHiddenIds());
13643
+ for (const checkbox of body.querySelectorAll("[data-visibility-setup-id]")) {
13644
+ checkbox.checked = !hiddenSet.has(checkbox.dataset.visibilitySetupId);
13645
+ }
13646
+ const visibleCount = CONTROL_VISIBILITY_CATALOG.filter((entry) => !hiddenSet.has(entry.id)).length;
13647
+ setControlVisibilitySetupStatus(`${visibleCount} of ${CONTROL_VISIBILITY_CATALOG.length} optional controls shown by preference.`);
13648
+ }
13649
+
13650
+ function openControlVisibilitySetupDialog(trigger = null) {
13651
+ const dialog = elements.controlVisibilitySetupDialog;
13652
+ if (!dialog) return;
13653
+ controlVisibilitySetupFocusReturn = trigger instanceof HTMLElement ? trigger : elements.promptInput;
13654
+ if (!elements.controlVisibilitySetupBody?.childElementCount) renderControlVisibilitySetupDialog();
13655
+ if (!dialog.open) dialog.showModal();
13656
+ refreshControlVisibilitySetupDialog();
13657
+ queueMicrotask(() => elements.controlVisibilitySetupBody?.querySelector("input")?.focus({ preventScroll: true }));
13658
+ }
13659
+
13660
+ function restoreControlVisibilitySetupFocus() {
13661
+ const trigger = controlVisibilitySetupFocusReturn;
13662
+ controlVisibilitySetupFocusReturn = null;
13663
+ const triggerSurvives = trigger
13664
+ && trigger.isConnected
13665
+ && !trigger.closest?.("[hidden], .webui-user-hidden")
13666
+ && typeof trigger.focus === "function";
13667
+ requestAnimationFrame(() => {
13668
+ if (triggerSurvives) trigger.focus({ preventScroll: true });
13669
+ else elements.promptInput?.focus({ preventScroll: true });
13670
+ });
13671
+ }
13672
+
13577
13673
 
13578
13674
  function closeVisibilityContextMenu({ returnFocus = true } = {}) {
13579
13675
  const trigger = visibilityContextMenuState?.trigger;
@@ -13620,6 +13716,7 @@ function prepareControlVisibilityMenu(trigger, entryId = null) {
13620
13716
  closeGitPanelContextMenu({ returnFocus: false });
13621
13717
  closeSidePanelContextMenu({ returnFocus: false });
13622
13718
  closeGitFooterContextMenu({ returnFocus: false });
13719
+ closeEventTreeContextMenu({ returnFocus: false });
13623
13720
  closeVisibilityContextMenu({ returnFocus: false });
13624
13721
  // Region hosts are plain non-focusable containers; storing one as the
13625
13722
  // trigger would let Escape focus fall through to <body>. Fall back to the
@@ -13639,12 +13736,13 @@ function prepareControlVisibilityMenu(trigger, entryId = null) {
13639
13736
 
13640
13737
  // Right-clicking a visible registered control offers Hide <label> plus the
13641
13738
  // recovery actions; empty marked regions open the grouped full catalog.
13642
- function showControlVisibilityDirectMenu(entry, directElement, { clientX, clientY }) {
13643
- const menu = prepareControlVisibilityMenu(directElement, entry.id);
13739
+ function showControlVisibilityDirectMenu(entry, focusTrigger, { clientX, clientY }) {
13740
+ const menu = prepareControlVisibilityMenu(focusTrigger, entry.id);
13644
13741
  if (!menu) return;
13645
13742
  const items = [
13646
13743
  controlVisibilityMenuLabel("Hide or restore controls"),
13647
13744
  controlVisibilityMenuAction("hide", `Hide ${entry.label}`),
13745
+ controlVisibilityMenuAction("open-setup", "Open setup"),
13648
13746
  controlVisibilityMenuAction("show-all", "Show all"),
13649
13747
  controlVisibilityMenuAction("reset-defaults", "Reset defaults"),
13650
13748
  ];
@@ -13669,6 +13767,7 @@ function showControlVisibilityRegionMenu(trigger, { clientX, clientY }) {
13669
13767
  children.push(button);
13670
13768
  }
13671
13769
  }
13770
+ children.push(controlVisibilityMenuAction("open-setup", "Open setup"));
13672
13771
  children.push(controlVisibilityMenuAction("show-all", "Show all"));
13673
13772
  children.push(controlVisibilityMenuAction("reset-defaults", "Reset defaults"));
13674
13773
  menu.replaceChildren(...children);
@@ -13687,7 +13786,8 @@ function handleControlVisibilityContextMenu(event) {
13687
13786
  if (entry) {
13688
13787
  event.preventDefault();
13689
13788
  event.stopPropagation();
13690
- showControlVisibilityDirectMenu(entry, direct, { clientX: event.clientX, clientY: event.clientY });
13789
+ const focusTrigger = target.closest?.("button, a, input, select, textarea, [tabindex]");
13790
+ showControlVisibilityDirectMenu(entry, focusTrigger, { clientX: event.clientX, clientY: event.clientY });
13691
13791
  return;
13692
13792
  }
13693
13793
  if (target.closest?.("button, input, textarea, select, [contenteditable='true'], a")) return;
@@ -13716,8 +13816,10 @@ function handleControlVisibilityKeydown(event) {
13716
13816
  const position = { clientX: rect.left + Math.min(rect.width, 24), clientY: rect.bottom };
13717
13817
  event.preventDefault();
13718
13818
  event.stopPropagation();
13719
- if (entry) showControlVisibilityDirectMenu(entry, direct, position);
13720
- else showControlVisibilityRegionMenu(anchor, position);
13819
+ if (entry) {
13820
+ const focusTrigger = target.closest?.("button, a, input, select, textarea, [tabindex]");
13821
+ showControlVisibilityDirectMenu(entry, focusTrigger, position);
13822
+ } else showControlVisibilityRegionMenu(anchor, position);
13721
13823
  }
13722
13824
 
13723
13825
  function initializeControlVisibility() {
@@ -15962,6 +16064,8 @@ function resetActiveTabUi() {
15962
16064
  bindGitWorkflowToActiveTab();
15963
16065
  resetChatOutput();
15964
16066
  elements.stateDetails.replaceChildren();
16067
+ closeEventTreeContextMenu({ returnFocus: false });
16068
+ toolEventStartedAt.clear();
15965
16069
  elements.eventLog.replaceChildren();
15966
16070
  const queuedSnapshot = activeTabId ? latestQueuedMessagesByTab.get(activeTabId) : null;
15967
16071
  if (queuedSnapshot) renderQueue({ tabId: activeTabId, ...queuedSnapshot });
@@ -16335,6 +16439,7 @@ function showGitPanelContextMenu(event, context) {
16335
16439
  closeFileContextMenu({ returnFocus: false });
16336
16440
  closeGitPanelContextMenu({ returnFocus: false });
16337
16441
  closeSidePanelContextMenu({ returnFocus: false });
16442
+ closeEventTreeContextMenu({ returnFocus: false });
16338
16443
  const menu = elements.gitPanelContextMenu;
16339
16444
  const items = gitPanelContextMenuItems(context);
16340
16445
  if (!items.length) return;
@@ -17652,7 +17757,9 @@ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs", all
17652
17757
  if (!quickClose && !(await confirmCloseTerminalTabs(targetTabs, label))) return;
17653
17758
 
17654
17759
  const closedActiveTab = targetTabs.some((tab) => tab.id === activeTabId);
17760
+ const closedActiveCwd = closedActiveTab ? tabs.find((tab) => tab.id === activeTabId)?.cwd || "" : "";
17655
17761
  const fallbackTabId = tabs.find((item) => !targetIds.includes(item.id))?.id || null;
17762
+ for (const id of targetIds) closingTerminalTabIds.add(id);
17656
17763
  try {
17657
17764
  if (closedActiveTab) eventSource?.close();
17658
17765
  const response = await api("/api/tabs/close", { method: "POST", body: { ids: targetIds, allowEmpty }, scoped: false });
@@ -17686,9 +17793,14 @@ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs", all
17686
17793
 
17687
17794
  const activeTabNeedsFallback = closedIds.includes(activeTabId) || !tabs.some((item) => item.id === activeTabId);
17688
17795
  if (activeTabNeedsFallback) {
17689
- const tabContext = setActiveTabId((response.data?.activeTabId && tabs.some((item) => item.id === response.data.activeTabId)
17690
- ? response.data.activeTabId
17691
- : (fallbackTabId && tabs.some((item) => item.id === fallbackTabId) ? fallbackTabId : tabs[0]?.id)) || null, { remember: true });
17796
+ const sameCwdFallbackTabId = closedActiveCwd
17797
+ ? tabs.find((item) => !closedIds.includes(item.id) && item.cwd === closedActiveCwd)?.id || null
17798
+ : null;
17799
+ const tabContext = setActiveTabId((sameCwdFallbackTabId && tabs.some((item) => item.id === sameCwdFallbackTabId)
17800
+ ? sameCwdFallbackTabId
17801
+ : response.data?.activeTabId && tabs.some((item) => item.id === response.data.activeTabId)
17802
+ ? response.data.activeTabId
17803
+ : (fallbackTabId && tabs.some((item) => item.id === fallbackTabId) ? fallbackTabId : tabs[0]?.id)) || null, { remember: true });
17692
17804
  resetActiveTabUi();
17693
17805
  renderTabs();
17694
17806
  restoreActiveDraft();
@@ -17704,6 +17816,8 @@ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs", all
17704
17816
  addEvent(`closed ${closedIds.length || targetTabs.length} terminal ${closedIds.length === 1 ? "tab" : "tabs"}`, "warn");
17705
17817
  } catch (error) {
17706
17818
  addEvent(error.message, "error");
17819
+ } finally {
17820
+ for (const id of targetIds) closingTerminalTabIds.delete(id);
17707
17821
  }
17708
17822
  }
17709
17823
 
@@ -17809,24 +17923,334 @@ function jumpToChatEvent(line) {
17809
17923
  }
17810
17924
  }
17811
17925
 
17812
- function addEvent(message, level = "info", { toolCallId = "", notify = true } = {}) {
17926
+ const TOOL_EVENT_TARGET_FIELDS = new Map([
17927
+ ["read", "path"],
17928
+ ["write", "path"],
17929
+ ["edit", "path"],
17930
+ ["grep", "path"],
17931
+ ["find", "path"],
17932
+ ["ls", "path"],
17933
+ ]);
17934
+
17935
+ function boundedToolEventTarget(event) {
17936
+ const toolName = String(event?.toolName || "").trim().toLowerCase();
17937
+ const field = TOOL_EVENT_TARGET_FIELDS.get(toolName);
17938
+ if (!field) return "";
17939
+ const args = event?.args ?? event?.arguments ?? event?.invocation?.args;
17940
+ const value = args && typeof args === "object" && !Array.isArray(args) ? args[field] : "";
17941
+ if (typeof value !== "string") return "";
17942
+ const singleLine = value.replace(/[\u0000-\u001f\u007f]+/g, " ").trim();
17943
+ return singleLine.length > 96 ? `${singleLine.slice(0, 93)}…` : singleLine;
17944
+ }
17945
+
17946
+ function shortenedToolCallId(value) {
17947
+ const id = String(value || "").trim();
17948
+ if (!id) return "";
17949
+ return id.length <= 14 ? id : `${id.slice(0, 7)}…${id.slice(-5)}`;
17950
+ }
17951
+
17952
+ function toolEventTimerKey(event) {
17953
+ const toolCallId = String(event?.toolCallId || "").trim();
17954
+ return toolCallId ? `${event?.tabId || activeTabId || "tab"}:${toolCallId}` : "";
17955
+ }
17956
+
17957
+ function toolEventDurationMs(event, phase, occurredAt) {
17958
+ if (phase !== "finish") return null;
17959
+ const reportedDurationMs = Number(event?.durationMs);
17960
+ if (Number.isFinite(reportedDurationMs) && reportedDurationMs >= 0) return reportedDurationMs;
17961
+ const startedAt = toolEventStartedAt.get(toolEventTimerKey(event))?.startedAt;
17962
+ return Number.isFinite(startedAt) ? Math.max(0, occurredAt - startedAt) : null;
17963
+ }
17964
+
17965
+ function formatToolEventDuration(durationMs) {
17966
+ if (!Number.isFinite(durationMs)) return "";
17967
+ if (durationMs < 1000) return `${Math.round(durationMs)} ms`;
17968
+ if (durationMs < 10_000) return `${(durationMs / 1000).toFixed(1)} s`;
17969
+ return `${Math.round(durationMs / 1000)} s`;
17970
+ }
17971
+
17972
+ function toolLifecycleEventDetails(event, phase, occurredAt) {
17973
+ const status = phase === "start" ? "started" : event?.isError ? "failed" : "finished";
17974
+ const startRecord = phase === "finish" ? toolEventStartedAt.get(toolEventTimerKey(event)) : null;
17975
+ const target = boundedToolEventTarget(event) || startRecord?.target || "";
17976
+ const duration = formatToolEventDuration(toolEventDurationMs(event, phase, occurredAt));
17977
+ const callId = shortenedToolCallId(event?.toolCallId);
17978
+ return [
17979
+ target ? { label: "target", value: target } : null,
17980
+ { label: "status", value: status, tone: event?.isError ? "error" : phase === "finish" ? "success" : "info" },
17981
+ duration ? { label: "duration", value: duration } : null,
17982
+ callId ? { label: "call", value: callId } : null,
17983
+ ].filter(Boolean);
17984
+ }
17985
+
17986
+ function toolLifecycleEventArguments(event, phase) {
17813
17987
  const occurredAt = Date.now();
17988
+ const timerKey = toolEventTimerKey(event);
17989
+ if (phase === "start" && timerKey) {
17990
+ toolEventStartedAt.set(timerKey, { startedAt: occurredAt, target: boundedToolEventTarget(event) });
17991
+ while (toolEventStartedAt.size > 240) toolEventStartedAt.delete(toolEventStartedAt.keys().next().value);
17992
+ }
17993
+ const toolName = runIndicatorToolName(event?.toolName || "tool");
17994
+ const status = phase === "start" ? "started" : event?.isError ? "failed" : "finished";
17995
+ const args = [`tool ${toolName} ${status}`, event?.isError ? "error" : "info", {
17996
+ toolCallId: event?.toolCallId,
17997
+ toolEventPhase: phase,
17998
+ details: toolLifecycleEventDetails(event, phase, occurredAt),
17999
+ occurredAt,
18000
+ }];
18001
+ if (phase === "finish" && timerKey) toolEventStartedAt.delete(timerKey);
18002
+ return args;
18003
+ }
18004
+
18005
+ function normalizeEventDisplayMode(value) {
18006
+ return value === "compact" ? "compact" : "detailed";
18007
+ }
18008
+
18009
+ function readStoredEventDisplayMode() {
18010
+ try {
18011
+ return normalizeEventDisplayMode(localStorage.getItem(EVENT_DISPLAY_MODE_STORAGE_KEY));
18012
+ } catch {
18013
+ return "detailed";
18014
+ }
18015
+ }
18016
+
18017
+ function normalizeEventFilter(value) {
18018
+ return EVENT_FILTER_VALUES.has(value) ? value : "all";
18019
+ }
18020
+
18021
+ function readStoredEventFilter() {
18022
+ try {
18023
+ return normalizeEventFilter(localStorage.getItem(EVENT_FILTER_STORAGE_KEY));
18024
+ } catch {
18025
+ return "all";
18026
+ }
18027
+ }
18028
+
18029
+ function eventRowMatchesFilter(line, filter = eventFilter) {
18030
+ if (!line?.classList?.contains("event") || filter === "all") return true;
18031
+ if (filter === "errors") return line.dataset.eventLevel === "error";
18032
+ if (filter === "warnings") return line.dataset.eventLevel === "warn";
18033
+ if (filter === "tools") return ["start", "finish"].includes(line.dataset.eventToolPhase);
18034
+ if (filter === "tree") return line.dataset.eventTreeAvailable === "true";
18035
+ return true;
18036
+ }
18037
+
18038
+ function applyEventFilter() {
18039
+ const rows = [...(elements.eventLog?.children || [])].filter((line) => line.classList?.contains("event"));
18040
+ let shown = 0;
18041
+ for (const line of rows) {
18042
+ const matches = eventRowMatchesFilter(line);
18043
+ line.hidden = !matches;
18044
+ if (matches) shown += 1;
18045
+ }
18046
+ const total = rows.length;
18047
+ if (elements.eventFilterStatus) {
18048
+ elements.eventFilterStatus.textContent = total === 0
18049
+ ? "No events yet"
18050
+ : eventFilter === "all"
18051
+ ? `${total} event${total === 1 ? "" : "s"}`
18052
+ : `${shown} of ${total}`;
18053
+ }
18054
+ if (elements.eventFilterEmpty) {
18055
+ elements.eventFilterEmpty.hidden = total === 0 || shown > 0;
18056
+ const label = elements.eventFilterSelect?.selectedOptions?.[0]?.textContent?.trim() || "this filter";
18057
+ elements.eventFilterEmpty.textContent = `No events match ${label.toLowerCase()}.`;
18058
+ }
18059
+ }
18060
+
18061
+ function syncEventFilterUi() {
18062
+ if (elements.eventFilterSelect) elements.eventFilterSelect.value = eventFilter;
18063
+ applyEventFilter();
18064
+ }
18065
+
18066
+ function setEventFilter(value, { persist = true } = {}) {
18067
+ eventFilter = normalizeEventFilter(value);
18068
+ syncEventFilterUi();
18069
+ if (!persist) return;
18070
+ try {
18071
+ localStorage.setItem(EVENT_FILTER_STORAGE_KEY, eventFilter);
18072
+ } catch {
18073
+ // The filter remains active for this page when storage is unavailable.
18074
+ }
18075
+ }
18076
+
18077
+ function syncEventDisplayModeUi() {
18078
+ if (elements.eventLog) elements.eventLog.dataset.displayMode = eventDisplayMode;
18079
+ elements.eventDisplayDetailedAction?.setAttribute("aria-checked", String(eventDisplayMode === "detailed"));
18080
+ elements.eventDisplayCompactAction?.setAttribute("aria-checked", String(eventDisplayMode === "compact"));
18081
+ }
18082
+
18083
+ function setEventDisplayMode(value, { persist = true } = {}) {
18084
+ eventDisplayMode = normalizeEventDisplayMode(value);
18085
+ syncEventDisplayModeUi();
18086
+ if (!persist) return;
18087
+ try {
18088
+ localStorage.setItem(EVENT_DISPLAY_MODE_STORAGE_KEY, eventDisplayMode);
18089
+ } catch {
18090
+ // Display mode remains active for this page when storage is unavailable.
18091
+ }
18092
+ }
18093
+
18094
+ function addEvent(message, level = "info", { toolCallId = "", toolEventPhase = "", details = [], notify = true, occurredAt = Date.now() } = {}) {
17814
18095
  const line = make("button", `event ${level}`.trim());
17815
18096
  line.type = "button";
18097
+ line.dataset.eventLevel = String(level || "info").trim().toLowerCase() || "info";
17816
18098
  line.dataset.chatEventTimestamp = String(occurredAt);
17817
- if (toolCallId) line.dataset.chatToolCallId = String(toolCallId);
17818
- line.textContent = `[${new Date(occurredAt).toLocaleTimeString()}] ${message}`;
17819
- line.title = "Jump to this event in the chat";
17820
- line.setAttribute("aria-label", `${line.textContent}. Jump to this event in the chat.`);
18099
+ const stableToolCallId = String(toolCallId || "").trim();
18100
+ const toolLifecycle = ["start", "finish"].includes(toolEventPhase);
18101
+ const treeEligible = stableToolCallId && toolLifecycle;
18102
+ line.dataset.eventTreeAvailable = String(!!treeEligible);
18103
+ if (stableToolCallId) line.dataset.chatToolCallId = stableToolCallId;
18104
+ if (toolLifecycle) line.dataset.eventToolPhase = toolEventPhase;
18105
+ line.setAttribute("aria-keyshortcuts", "ContextMenu Shift+F10");
18106
+ const time = make("span", "event-time", `[${new Date(occurredAt).toLocaleTimeString()}]`);
18107
+ const summary = make("span", "event-summary", String(message || ""));
18108
+ const main = make("span", "event-main");
18109
+ main.append(time, summary);
18110
+ line.append(main);
18111
+ if (Array.isArray(details) && details.length) {
18112
+ const meta = make("span", "event-details");
18113
+ for (const detail of details) {
18114
+ if (!detail?.label || !detail?.value) continue;
18115
+ const item = make("span", `event-detail${detail.tone ? ` ${detail.tone}` : ""}`);
18116
+ item.append(make("span", "event-detail-label", `${detail.label}:`), document.createTextNode(` ${detail.value}`));
18117
+ meta.append(item);
18118
+ }
18119
+ if (meta.childElementCount) line.append(meta);
18120
+ }
18121
+ const accessibleText = line.textContent.trim();
18122
+ line.title = `Jump to this event in the chat; open the context menu for display options${treeEligible ? " and Tree navigation" : ""}`;
18123
+ line.setAttribute("aria-label", `${accessibleText}. Jump to this event in the chat. Context menu: display options${treeEligible ? " and Tree navigation" : ""}.`);
17821
18124
  line.addEventListener("click", () => jumpToChatEvent(line));
17822
18125
  elements.eventLog.prepend(line);
17823
18126
  while (elements.eventLog.children.length > 120) elements.eventLog.lastElementChild?.remove();
18127
+ applyEventFilter();
17824
18128
  if (notify && (level === "error" || level === "warn")) {
17825
18129
  showNoticeToast(message, level);
17826
18130
  noteUnreadEvent();
17827
18131
  }
17828
18132
  }
17829
18133
 
18134
+ function closeEventTreeContextMenu({ returnFocus = true } = {}) {
18135
+ const trigger = eventTreeContextMenuState?.trigger;
18136
+ eventTreeContextMenuState = null;
18137
+ if (elements.eventTreeContextMenu) elements.eventTreeContextMenu.hidden = true;
18138
+ if (elements.eventTreeContextMenuAction) elements.eventTreeContextMenuAction.disabled = false;
18139
+ if (returnFocus && trigger?.isConnected) queueMicrotask(() => trigger.focus({ preventScroll: true }));
18140
+ }
18141
+
18142
+ function setEventTreeContextMenuStatus(message = "", level = "info") {
18143
+ const status = elements.eventTreeContextMenuStatus;
18144
+ if (!status) return;
18145
+ status.textContent = message;
18146
+ status.hidden = !message;
18147
+ status.className = `event-tree-context-menu-status ${level}`;
18148
+ }
18149
+
18150
+ function closeOtherContextMenusForEventTree() {
18151
+ closeFileContextMenu({ returnFocus: false });
18152
+ closeGitPanelContextMenu({ returnFocus: false });
18153
+ closeSidePanelContextMenu({ returnFocus: false });
18154
+ closeVisibilityContextMenu({ returnFocus: false });
18155
+ closeGitFooterContextMenu({ returnFocus: false });
18156
+ closeEventTreeContextMenu({ returnFocus: false });
18157
+ }
18158
+
18159
+ function showEventTreeContextMenu(event, line = null) {
18160
+ const menu = elements.eventTreeContextMenu;
18161
+ if (!menu || (line && !elements.eventLog?.contains(line))) return;
18162
+ const toolCallId = String(line?.dataset.chatToolCallId || "").trim();
18163
+ const phase = line?.dataset.eventToolPhase || "";
18164
+ const treeEligible = !!toolCallId && ["start", "finish"].includes(phase);
18165
+ event.preventDefault();
18166
+ event.stopPropagation();
18167
+ closeOtherContextMenusForEventTree();
18168
+ eventTreeContextMenuState = {
18169
+ trigger: line,
18170
+ toolCallId,
18171
+ phase,
18172
+ tabContext: treeEligible ? activeTabContext() : null,
18173
+ busy: false,
18174
+ openedAt: performance.now(),
18175
+ };
18176
+ setEventTreeContextMenuStatus("");
18177
+ syncEventDisplayModeUi();
18178
+ if (elements.eventTreeContextMenuAction) elements.eventTreeContextMenuAction.hidden = !treeEligible;
18179
+ menu.hidden = false;
18180
+ const rect = menu.getBoundingClientRect();
18181
+ const left = Math.min(Number(event.clientX) || 0, Math.max(8, window.innerWidth - rect.width - 8));
18182
+ const top = Math.min(Number(event.clientY) || 0, Math.max(8, window.innerHeight - rect.height - 8));
18183
+ menu.style.left = `${Math.max(8, left)}px`;
18184
+ menu.style.top = `${Math.max(8, top)}px`;
18185
+ const displayAction = eventDisplayMode === "compact" ? elements.eventDisplayCompactAction : elements.eventDisplayDetailedAction;
18186
+ displayAction?.focus({ preventScroll: true });
18187
+ }
18188
+
18189
+ function eventTreeTargetEntryId(data, state) {
18190
+ const targets = Array.isArray(data?.eventTargets) ? data.eventTargets : [];
18191
+ const target = targets.find((item) => String(item?.toolCallId || "") === state.toolCallId);
18192
+ const entryId = state.phase === "start" ? target?.startEntryId : target?.finishEntryId || target?.startEntryId;
18193
+ if (typeof entryId !== "string" || !entryId.trim()) return "";
18194
+ const nodes = Array.isArray(data?.nodes) ? data.nodes : [];
18195
+ return nodes.some((node) => node?.id === entryId) ? entryId : "";
18196
+ }
18197
+
18198
+ async function navigateEventTreeBoundary() {
18199
+ const state = eventTreeContextMenuState;
18200
+ const action = elements.eventTreeContextMenuAction;
18201
+ if (!state || state.busy || !action || !isCurrentTabContext(state.tabContext)) return;
18202
+ state.busy = true;
18203
+ action.disabled = true;
18204
+ setEventTreeContextMenuStatus("Resolving this tool boundary…");
18205
+ try {
18206
+ const tree = await api("/api/session-tree", { tabId: state.tabContext.tabId });
18207
+ if (eventTreeContextMenuState !== state || !isCurrentTabContext(state.tabContext)) return;
18208
+ const entryId = eventTreeTargetEntryId(tree.data, state);
18209
+ if (!entryId) {
18210
+ setEventTreeContextMenuStatus("This tool boundary is not available in the current persisted session tree.", "warn");
18211
+ addEvent("Tree navigation target is unavailable or stale; the session was not changed.", "warn");
18212
+ return;
18213
+ }
18214
+ setEventTreeContextMenuStatus("");
18215
+ const confirmed = await appConfirm({
18216
+ title: "Navigate to this tool boundary?",
18217
+ summary: "This changes the current session branch. Later entries stay in the tree, and no automatic branch summary is generated.",
18218
+ affected: "Use /tree to navigate back or choose another branch.",
18219
+ undoable: true,
18220
+ confirmLabel: "Navigate",
18221
+ danger: false,
18222
+ });
18223
+ if (eventTreeContextMenuState !== state || !isCurrentTabContext(state.tabContext)) return;
18224
+ if (!confirmed) {
18225
+ setEventTreeContextMenuStatus("Navigation cancelled; the session was not changed.");
18226
+ return;
18227
+ }
18228
+ setEventTreeContextMenuStatus("Navigating…");
18229
+ const result = await api("/api/tree-navigate", {
18230
+ method: "POST",
18231
+ body: { entryId, summarize: false },
18232
+ tabId: state.tabContext.tabId,
18233
+ });
18234
+ if (!isCurrentTabContext(state.tabContext)) return;
18235
+ applyResponseTab(result);
18236
+ addTransientMessage({ role: "native", title: "/tree", content: result.data?.message || "Navigated to the selected tool boundary.", level: "info" });
18237
+ if (eventTreeContextMenuState === state) closeEventTreeContextMenu();
18238
+ await refreshAll(state.tabContext);
18239
+ } catch (error) {
18240
+ if (eventTreeContextMenuState === state && isCurrentTabContext(state.tabContext)) {
18241
+ const message = error?.message || String(error);
18242
+ setEventTreeContextMenuStatus(`Navigation failed: ${message}`, "error");
18243
+ addEvent(`Tree navigation failed: ${message}`, "error");
18244
+ }
18245
+ } finally {
18246
+ if (eventTreeContextMenuState === state) {
18247
+ state.busy = false;
18248
+ action.disabled = false;
18249
+ action.focus({ preventScroll: true });
18250
+ }
18251
+ }
18252
+ }
18253
+
17830
18254
  // --- Non-blocking warn/error notices -------------------------------------------------------
17831
18255
  // The Events log lives in a collapsed Control Deck section, so on its own it makes failures look
17832
18256
  // like "nothing happened". Warnings and errors additionally surface as a short-lived toast (max 3,
@@ -19361,6 +19785,7 @@ function showGitFooterContextMenu(event, chip, trigger) {
19361
19785
  closeGitPanelContextMenu({ returnFocus: false });
19362
19786
  closeSidePanelContextMenu({ returnFocus: false });
19363
19787
  closeGitFooterContextMenu({ returnFocus: false });
19788
+ closeEventTreeContextMenu({ returnFocus: false });
19364
19789
  hideFooterTooltip();
19365
19790
 
19366
19791
  const label = cleanStatusText(chip?.label) || gitFooterVisibilityLabel(key);
@@ -31630,6 +32055,109 @@ function appendGitWorkflowOutput(text, { tabId = activeTabId } = {}) {
31630
32055
  setGitWorkflow({ output: next.slice(-60000) }, { tabId });
31631
32056
  }
31632
32057
 
32058
+ function gitWorkflowGenerationProfileText(profile) {
32059
+ const provider = String(profile?.provider || "").trim();
32060
+ const modelId = String(profile?.modelId || "").trim();
32061
+ const thinkingLevel = String(profile?.thinkingLevel || "").trim();
32062
+ if (!provider || !modelId) return "no model";
32063
+ return `${provider}/${modelId}${thinkingLevel ? ` at ${thinkingLevel} effort` : ""}`;
32064
+ }
32065
+
32066
+ function gitWorkflowFallbackConfigured(preferences) {
32067
+ return !!preferences?.generation?.fallback?.provider && !!preferences?.generation?.fallback?.modelId;
32068
+ }
32069
+
32070
+ function gitWorkflowConfiguredGenerationText(preferences) {
32071
+ const primary = gitWorkflowGenerationProfileText(preferences?.generation);
32072
+ if (!gitWorkflowFallbackConfigured(preferences)) return `Primary Git-writing model: ${primary}. No fallback is configured.`;
32073
+ return `Primary Git-writing model: ${primary}. Fallback after a final primary generation failure: ${gitWorkflowGenerationProfileText(preferences.generation.fallback)} (one attempt).`;
32074
+ }
32075
+
32076
+ function gitWorkflowGenerationAcceptedText(generation, subject) {
32077
+ const effective = gitWorkflowGenerationProfileText(generation?.generation);
32078
+ if (generation?.fallbackUsed === true) {
32079
+ const primary = gitWorkflowGenerationProfileText(generation.primaryGeneration);
32080
+ return `The primary Git-writing model ${primary} failed. ${subject} continued with the fallback ${effective}.`;
32081
+ }
32082
+ return `${subject} started with the primary Git-writing model ${effective}.`;
32083
+ }
32084
+
32085
+ function gitWorkflowFallbackEventMatchesPendingRequest(workflow, event) {
32086
+ if (!workflow?.active || workflow.generationKind !== event?.kind) return false;
32087
+ const expectedSteps = { commit: "generating", branch: "branchNaming", pr: "prGenerating" };
32088
+ return workflow.step === expectedSteps[event.kind] && !!String(event.generationId || "").trim();
32089
+ }
32090
+
32091
+ function gitWorkflowFallbackEventMatches(workflow, event) {
32092
+ if (!workflow?.generationAccepted || !gitWorkflowFallbackEventMatchesPendingRequest(workflow, event)) return false;
32093
+ return String(event.generationId || "").trim() === String(workflow.generationId || "").trim();
32094
+ }
32095
+
32096
+ function gitWorkflowFallbackLifecycleKey(workflow, event) {
32097
+ return [event.type, workflow.runId, event.kind, event.generationId || "", event.generation?.provider || "", event.generation?.modelId || ""].join(":");
32098
+ }
32099
+
32100
+ function applyGitWorkflowFallbackLifecycleEvent(workflow, event, tabId) {
32101
+ if (!gitWorkflowFallbackEventMatches(workflow, event)) return false;
32102
+ const keys = workflow.fallbackLifecycleKeys instanceof Set ? workflow.fallbackLifecycleKeys : new Set();
32103
+ const key = gitWorkflowFallbackLifecycleKey(workflow, event);
32104
+ if (keys.has(key)) return true;
32105
+ keys.add(key);
32106
+ const primary = gitWorkflowGenerationProfileText(event.primaryGeneration);
32107
+ const fallback = gitWorkflowGenerationProfileText(event.generation);
32108
+ if (event.type === "webui_git_workflow_generation_fallback_started") {
32109
+ setGitWorkflow({ fallbackStarted: true, fallbackLifecycleKeys: keys }, { tabId });
32110
+ appendGitWorkflowOutput(`The primary Git-writing model ${primary} failed${event.reason ? `: ${event.reason}` : "."} Generation continued with the fallback ${fallback}.`, { tabId });
32111
+ } else {
32112
+ setGitWorkflow({ fallbackLifecycleKeys: keys }, { tabId });
32113
+ appendGitWorkflowOutput(`The fallback Git-writing model ${fallback} also failed${event.error ? `: ${event.error}` : "."} No additional model retry will run.`, { tabId });
32114
+ }
32115
+ return true;
32116
+ }
32117
+
32118
+ function flushPendingGitWorkflowFallbackLifecycleEvents(tabId) {
32119
+ const workflow = gitWorkflowForTab(tabId, { create: false });
32120
+ if (!workflow?.generationAccepted) return;
32121
+ const pending = Array.isArray(workflow.pendingFallbackLifecycleEvents) ? workflow.pendingFallbackLifecycleEvents : [];
32122
+ setGitWorkflow({ pendingFallbackLifecycleEvents: [] }, { tabId });
32123
+ for (const event of pending) applyGitWorkflowFallbackLifecycleEvent(gitWorkflowForTab(tabId, { create: false }), event, tabId);
32124
+ }
32125
+
32126
+ function acceptGitWorkflowGenerationCorrelation(generation, tabId) {
32127
+ const workflow = gitWorkflowForTab(tabId, { create: false });
32128
+ const generationId = String(generation?.generationId || "").trim();
32129
+ if (!workflow || !generationId || generation?.kind !== workflow.generationKind) return false;
32130
+ setGitWorkflow({
32131
+ generationId,
32132
+ messageGenerationId: generation.kind === "commit" ? generationId : workflow.messageGenerationId,
32133
+ generationAccepted: true,
32134
+ }, { tabId });
32135
+ flushPendingGitWorkflowFallbackLifecycleEvents(tabId);
32136
+ if (generation.fallbackUsed === true) setGitWorkflow({ fallbackStarted: true }, { tabId });
32137
+ return true;
32138
+ }
32139
+
32140
+ function acceptGitWorkflowGenerationErrorCorrelation(error, tabId) {
32141
+ return acceptGitWorkflowGenerationCorrelation(error?.data?.gitWorkflowGeneration, tabId);
32142
+ }
32143
+
32144
+ function handleGitWorkflowFallbackLifecycleEvent(event) {
32145
+ if (!["webui_git_workflow_generation_fallback_started", "webui_git_workflow_generation_fallback_failed"].includes(event?.type)) return false;
32146
+ const tabId = event.tabId;
32147
+ const workflow = gitWorkflowForTab(tabId, { create: false });
32148
+ if (!tabId || !gitWorkflowFallbackEventMatchesPendingRequest(workflow, event)) return true;
32149
+ if (!workflow.generationAccepted) {
32150
+ const pending = Array.isArray(workflow.pendingFallbackLifecycleEvents) ? workflow.pendingFallbackLifecycleEvents : [];
32151
+ const key = gitWorkflowFallbackLifecycleKey(workflow, event);
32152
+ if (!pending.some((item) => gitWorkflowFallbackLifecycleKey(workflow, item) === key)) {
32153
+ setGitWorkflow({ pendingFallbackLifecycleEvents: [...pending, event].slice(-4) }, { tabId });
32154
+ }
32155
+ return true;
32156
+ }
32157
+ applyGitWorkflowFallbackLifecycleEvent(workflow, event, tabId);
32158
+ return true;
32159
+ }
32160
+
31633
32161
  function formatGitCommandResult(result) {
31634
32162
  if (!result) return "";
31635
32163
  const lines = [`$ ${result.command || "git"}`];
@@ -32707,7 +33235,7 @@ async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {})
32707
33235
  step: "add",
32708
33236
  process: "stage",
32709
33237
  busy: false,
32710
- output: `${gitWorkflowStagingReadyMessage(preferences)}\n\nGit text will use ${preferences.generation.provider}/${preferences.generation.modelId} at ${preferences.generation.thinkingLevel} effort. The active tab model is restored after generation.`,
33238
+ output: `${gitWorkflowStagingReadyMessage(preferences)}\n\n${gitWorkflowConfiguredGenerationText(preferences)} The active tab model and effort are restored after generation.`,
32711
33239
  error: "",
32712
33240
  githubUsername: "",
32713
33241
  repoName: "",
@@ -32721,6 +33249,12 @@ async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {})
32721
33249
  ...resetGitWorkflowManualCommitDefaultPatch(),
32722
33250
  messageRequestedAt: 0,
32723
33251
  messageGenerationId: "",
33252
+ generationId: "",
33253
+ generationKind: "",
33254
+ generationAccepted: false,
33255
+ fallbackStarted: false,
33256
+ fallbackLifecycleKeys: new Set(),
33257
+ pendingFallbackLifecycleEvents: [],
32724
33258
  branchName: "",
32725
33259
  branchNameRequestedAt: 0,
32726
33260
  actionsDone: createGitWorkflowActionsDone(),
@@ -33161,6 +33695,12 @@ async function runGitMessagePrompt(tabId = gitWorkflowActionTabId()) {
33161
33695
  error: "",
33162
33696
  messageRequestedAt: requestedAt,
33163
33697
  messageGenerationId: "",
33698
+ generationId: "",
33699
+ generationKind: "commit",
33700
+ generationAccepted: false,
33701
+ fallbackStarted: false,
33702
+ fallbackLifecycleKeys: new Set(),
33703
+ pendingFallbackLifecycleEvents: [],
33164
33704
  output: "Asking Pi to write the commit message…\n\nCancel stops the request.",
33165
33705
  }, { tabId });
33166
33706
  if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Generating commit message…");
@@ -33168,9 +33708,8 @@ async function runGitMessagePrompt(tabId = gitWorkflowActionTabId()) {
33168
33708
  const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "commit", ...(expectedStagedContentHash ? { expectedStagedContentHash } : {}) }, runId, tabId });
33169
33709
  if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
33170
33710
  const generationId = String(generation.generationId || "").trim();
33171
- if (!generationId) throw new Error("The WebUI server did not return a commit-message generation ID. Restart Pi Web UI and regenerate.");
33172
- setGitWorkflow({ messageGenerationId: generationId }, { tabId });
33173
- appendGitWorkflowOutput(`Commit message generation started with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for Pi to finish, then the short and long messages will be loaded.`, { tabId });
33711
+ if (!acceptGitWorkflowGenerationCorrelation(generation, tabId)) throw new Error("The WebUI server did not return a commit-message generation ID. Restart Pi Web UI and regenerate.");
33712
+ appendGitWorkflowOutput(`${gitWorkflowGenerationAcceptedText(generation, "Commit message generation")} Waiting for Pi to finish, then the short and long messages will be loaded.`, { tabId });
33174
33713
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
33175
33714
  setTimeout(() => {
33176
33715
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
@@ -33182,6 +33721,7 @@ async function runGitMessagePrompt(tabId = gitWorkflowActionTabId()) {
33182
33721
  }, 2500);
33183
33722
  } catch (error) {
33184
33723
  if (isCurrentGitWorkflowRun(runId, tabId)) {
33724
+ acceptGitWorkflowGenerationErrorCorrelation(error, tabId);
33185
33725
  if (isCurrentTabContext(tabContext)) clearRunIndicatorActivity();
33186
33726
  failGitWorkflow(error, "generate", { tabId });
33187
33727
  }
@@ -33326,13 +33866,20 @@ async function runGitBranchNamePrompt(tabId = gitWorkflowActionTabId()) {
33326
33866
  busy: true,
33327
33867
  error: "",
33328
33868
  branchNameRequestedAt: requestedAt,
33869
+ generationId: "",
33870
+ generationKind: "branch",
33871
+ generationAccepted: false,
33872
+ fallbackStarted: false,
33873
+ fallbackLifecycleKeys: new Set(),
33874
+ pendingFallbackLifecycleEvents: [],
33329
33875
  output: "Sending branch-name request to Pi.\n\nCancel will request Pi abort.",
33330
33876
  }, { tabId });
33331
33877
  if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending branch-name request to Pi…");
33332
33878
  try {
33333
33879
  const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "branch", ...(expectedStagedContentHash ? { expectedStagedContentHash } : {}) }, runId, tabId });
33334
33880
  if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
33335
- appendGitWorkflowOutput(`Branch-name request accepted with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for Pi to finish, then the branch name will be loaded.`, { tabId });
33881
+ if (!acceptGitWorkflowGenerationCorrelation(generation, tabId)) throw new Error("The WebUI server did not return a branch-name generation ID. Restart Pi Web UI and regenerate.");
33882
+ appendGitWorkflowOutput(`${gitWorkflowGenerationAcceptedText(generation, "Branch-name generation")} Waiting for Pi to finish, then the branch name will be loaded.`, { tabId });
33336
33883
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
33337
33884
  setTimeout(() => {
33338
33885
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
@@ -33343,6 +33890,7 @@ async function runGitBranchNamePrompt(tabId = gitWorkflowActionTabId()) {
33343
33890
  }, 2500);
33344
33891
  } catch (error) {
33345
33892
  if (isCurrentGitWorkflowRun(runId, tabId)) {
33893
+ acceptGitWorkflowGenerationErrorCorrelation(error, tabId);
33346
33894
  if (isCurrentTabContext(tabContext)) clearRunIndicatorActivity();
33347
33895
  failGitWorkflow(error, "message", { tabId });
33348
33896
  }
@@ -33352,8 +33900,11 @@ async function runGitBranchNamePrompt(tabId = gitWorkflowActionTabId()) {
33352
33900
  async function loadGitWorkflowBranchName({ requireFresh = false, retries = 0, runId, tabId = activeTabId } = {}) {
33353
33901
  const workflow = gitWorkflowForTab(tabId, { create: false });
33354
33902
  const expectedRunId = runId ?? workflow?.runId;
33903
+ const generationId = requireFresh ? String(workflow?.generationId || "").trim() : "";
33904
+ if (requireFresh && !generationId) return;
33355
33905
  try {
33356
- const branchName = await gitWorkflowRequest("/api/git-workflow/branch-name", { method: "GET", runId: expectedRunId, tabId });
33906
+ const query = generationId ? `?generationId=${encodeURIComponent(generationId)}` : "";
33907
+ const branchName = await gitWorkflowRequest(`/api/git-workflow/branch-name${query}`, { method: "GET", runId: expectedRunId, tabId });
33357
33908
  if (!branchName) return;
33358
33909
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
33359
33910
  if (!currentWorkflow) return;
@@ -33669,13 +34220,20 @@ async function runGitPrPrompt(tabId = gitWorkflowActionTabId(), { prefixOutput =
33669
34220
  busy: true,
33670
34221
  error: "",
33671
34222
  prRequestedAt: requestedAt,
34223
+ generationId: "",
34224
+ generationKind: "pr",
34225
+ generationAccepted: false,
34226
+ fallbackStarted: false,
34227
+ fallbackLifecycleKeys: new Set(),
34228
+ pendingFallbackLifecycleEvents: [],
33672
34229
  output: `${prefixOutput ? `${prefixOutput}\n\n` : ""}Sending /pr to Pi.\n\nCancel will request Pi abort.`,
33673
34230
  }, { tabId });
33674
34231
  if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending /pr to Pi…");
33675
34232
  try {
33676
34233
  const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "pr" }, runId, tabId });
33677
34234
  if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
33678
- appendGitWorkflowOutput(`PR text generation started with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for Pi to finish, then the PR description will be loaded.`, { tabId });
34235
+ if (!acceptGitWorkflowGenerationCorrelation(generation, tabId)) throw new Error("The WebUI server did not return a PR-text generation ID. Restart Pi Web UI and regenerate.");
34236
+ appendGitWorkflowOutput(`${gitWorkflowGenerationAcceptedText(generation, "PR text generation")} Waiting for Pi to finish, then the PR description will be loaded.`, { tabId });
33679
34237
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
33680
34238
  setTimeout(() => {
33681
34239
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
@@ -33686,6 +34244,7 @@ async function runGitPrPrompt(tabId = gitWorkflowActionTabId(), { prefixOutput =
33686
34244
  }, 2500);
33687
34245
  } catch (error) {
33688
34246
  if (isCurrentGitWorkflowRun(runId, tabId)) {
34247
+ acceptGitWorkflowGenerationErrorCorrelation(error, tabId);
33689
34248
  if (isCurrentTabContext(tabContext)) clearRunIndicatorActivity();
33690
34249
  failGitWorkflow(error, "push", { tabId });
33691
34250
  }
@@ -33695,8 +34254,11 @@ async function runGitPrPrompt(tabId = gitWorkflowActionTabId(), { prefixOutput =
33695
34254
  async function loadGitWorkflowPr({ requireFresh = false, retries = 0, runId, tabId = activeTabId } = {}) {
33696
34255
  const workflow = gitWorkflowForTab(tabId, { create: false });
33697
34256
  const expectedRunId = runId ?? workflow?.runId;
34257
+ const generationId = requireFresh ? String(workflow?.generationId || "").trim() : "";
34258
+ if (requireFresh && !generationId) return;
33698
34259
  try {
33699
- const pr = await gitWorkflowRequest("/api/git-workflow/pr-description", { method: "GET", runId: expectedRunId, tabId });
34260
+ const query = generationId ? `?generationId=${encodeURIComponent(generationId)}` : "";
34261
+ const pr = await gitWorkflowRequest(`/api/git-workflow/pr-description${query}`, { method: "GET", runId: expectedRunId, tabId });
33700
34262
  if (!pr) return;
33701
34263
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
33702
34264
  if (!currentWorkflow) return;
@@ -37439,6 +38001,11 @@ function handleToolExecutionEnd(event) {
37439
38001
  if (run) renderLiveToolRun(run);
37440
38002
  }
37441
38003
 
38004
+ function thinkingDisclosurePreviewText(message, charLimit = 140) {
38005
+ const raw = visibleThinkingText(message?.thinking || textFromContent(message?.content));
38006
+ return speakableTextFromMarkdown(raw).slice(0, Math.max(0, charLimit));
38007
+ }
38008
+
37442
38009
  function toolResultPreviewText(message, lineLimit = 10) {
37443
38010
  const text = textFromContent(message?.content).replace(/\s+$/g, "");
37444
38011
  if (!text) return "(empty tool result)";
@@ -37592,7 +38159,7 @@ function createMessageBubble(message, { streaming = false, messageIndex = -1, tr
37592
38159
  details.classList.add("thinking-disclosure");
37593
38160
  details.open = compactThinkingDisclosureExpanded(thinkingKey, false);
37594
38161
  details.addEventListener("toggle", () => setCompactThinkingDisclosureExpanded(thinkingKey, details.open, false));
37595
- const previewText = String(message.thinking || textFromContent(message.content) || "").replace(/\s+/g, " ").trim().slice(0, 140);
38162
+ const previewText = thinkingDisclosurePreviewText(message);
37596
38163
  if (previewText) header.append(make("span", "thinking-disclosure-preview", previewText));
37597
38164
  } else if (shouldOpenMessageCollapseByDefault(message)) details.open = true;
37598
38165
  details.append(header, body);
@@ -42567,6 +43134,7 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
42567
43134
  }
42568
43135
 
42569
43136
  const configuredModelKey = `${preferences.generation?.provider || ""}/${preferences.generation?.modelId || ""}`;
43137
+ const configuredFallbackKey = `${preferences.generation?.fallback?.provider || ""}/${preferences.generation?.fallback?.modelId || ""}`;
42570
43138
  const activeModelKey = gitWorkflowSetupModelKey(currentState?.model);
42571
43139
  const modelKeys = new Set(models.map(gitWorkflowSetupModelKey));
42572
43140
  const initialModelKey = modelKeys.has(configuredModelKey)
@@ -42574,14 +43142,21 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
42574
43142
  : modelKeys.has(activeModelKey)
42575
43143
  ? activeModelKey
42576
43144
  : gitWorkflowSetupModelKey(models[0]);
43145
+ const initialFallbackKey = modelKeys.has(configuredFallbackKey) && configuredFallbackKey !== initialModelKey ? configuredFallbackKey : "";
42577
43146
  const modelOptions = models.map((model) => ({
42578
43147
  value: gitWorkflowSetupModelKey(model),
42579
43148
  label: `${gitWorkflowSetupModelKey(model)}${model.name && model.name !== model.id ? ` · ${model.name}` : ""}`,
42580
43149
  }));
43150
+ const fallbackModelOptions = (primaryKey) => [
43151
+ { value: "", label: "No fallback" },
43152
+ ...modelOptions.filter((option) => option.value !== primaryKey),
43153
+ ];
42581
43154
 
42582
43155
  const controls = {
42583
- model: nativeSettingSelect("Git-writing model", initialModelKey, modelOptions, "Exact authenticated provider/model used for commit messages, branch names, and PR descriptions.", { label: "required", tone: "safety" }),
42584
- thinking: nativeSettingSelect("Reasoning effort", preferences.generation?.thinkingLevel || "low", SETTINGS_THINKING_OPTIONS, "Only levels supported by the selected model are shown. Low is recommended for routine commit messages.", { label: "required", tone: "safety" }),
43156
+ model: nativeSettingSelect("Primary Git-writing model", initialModelKey, modelOptions, "Exact authenticated provider/model normally used for commit messages, branch names, and PR descriptions.", { label: "required", tone: "safety" }),
43157
+ thinking: nativeSettingSelect("Primary reasoning effort", preferences.generation?.thinkingLevel || "low", SETTINGS_THINKING_OPTIONS, "Only levels supported by the primary model are shown. Low is recommended for routine commit messages.", { label: "required", tone: "safety" }),
43158
+ fallbackModel: nativeSettingSelect("Fallback model", initialFallbackKey, fallbackModelOptions(initialModelKey), "Optional. After a final primary model-generation failure, Guided Git tries this different model once.", { label: "optional", tone: "browser" }),
43159
+ fallbackThinking: nativeSettingSelect("Fallback reasoning effort", preferences.generation?.fallback?.thinkingLevel || "low", SETTINGS_THINKING_OPTIONS, "Uses only levels supported by the fallback model and is disabled when No fallback is selected.", { label: "optional", tone: "browser" }),
42585
43160
  language: nativeSettingSelect("Generated language", preferences.commit?.language || "en", [
42586
43161
  { value: "en", label: "English" },
42587
43162
  { value: "de", label: "German" },
@@ -42624,13 +43199,30 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
42624
43199
  const levels = thinkingLevelsForModel(controls.model.select.value);
42625
43200
  replaceNativeSettingSelectOptions(controls.thinking.select, levels, current);
42626
43201
  };
42627
- controls.model.select.addEventListener("change", syncThinkingLevels);
43202
+ const syncFallbackThinkingLevels = () => {
43203
+ const fallbackKey = controls.fallbackModel.select.value;
43204
+ const current = controls.fallbackThinking.select.value || preferences.generation?.fallback?.thinkingLevel || "low";
43205
+ const levels = fallbackKey ? thinkingLevelsForModel(fallbackKey) : [preferences.generation?.fallback?.thinkingLevel || "low"];
43206
+ replaceNativeSettingSelectOptions(controls.fallbackThinking.select, levels, current);
43207
+ controls.fallbackThinking.select.disabled = !fallbackKey;
43208
+ };
43209
+ const syncFallbackModelOptions = () => {
43210
+ const current = controls.fallbackModel.select.value;
43211
+ replaceNativeSettingSelectOptions(controls.fallbackModel.select, fallbackModelOptions(controls.model.select.value), current);
43212
+ syncFallbackThinkingLevels();
43213
+ };
43214
+ controls.model.select.addEventListener("change", () => {
43215
+ syncThinkingLevels();
43216
+ syncFallbackModelOptions();
43217
+ });
43218
+ controls.fallbackModel.select.addEventListener("change", syncFallbackThinkingLevels);
42628
43219
  syncThinkingLevels();
43220
+ syncFallbackModelOptions();
42629
43221
 
42630
43222
  const body = make("div", "native-settings-panel");
42631
43223
  body.append(
42632
43224
  nativeSettingsNote("Persistence", `Saved globally in ${data.path || "the Pi Web UI settings file"}. Credentials are never stored here.`),
42633
- nativeSettingsSection("Generation profile", "Required model and effort for generated Git text.", [controls.model, controls.thinking], { open: true }),
43225
+ nativeSettingsSection("Generation profile", "Choose the required primary profile and an optional one-shot fallback with its own effort.", [controls.model, controls.thinking, controls.fallbackModel, controls.fallbackThinking], { open: true }),
42634
43226
  nativeSettingsSection("Commit style", "Conventional Commit output preferences.", [controls.language, controls.defaultVariant, controls.scope], { open: true }),
42635
43227
  nativeSettingsSection("Workflow safety", "Staging, review, delivery, and verification defaults; push and PR confirmation remain mandatory.", [controls.staging, controls.reviewProcess, controls.delivery, controls.verification], { open: true }),
42636
43228
  );
@@ -42643,7 +43235,11 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
42643
43235
  setNativeCommandError("");
42644
43236
  try {
42645
43237
  const selectedModel = models.find((model) => gitWorkflowSetupModelKey(model) === controls.model.select.value);
42646
- if (!selectedModel) throw new Error("Select an available Git-writing model.");
43238
+ if (!selectedModel) throw new Error("Select an available primary Git-writing model.");
43239
+ const selectedFallback = models.find((model) => gitWorkflowSetupModelKey(model) === controls.fallbackModel.select.value) || null;
43240
+ if (selectedFallback && gitWorkflowSetupModelKey(selectedFallback) === gitWorkflowSetupModelKey(selectedModel)) {
43241
+ throw new Error("Select a fallback model different from the primary model.");
43242
+ }
42647
43243
  const response = await nativeCommandApi("/api/git-workflow/preferences", {
42648
43244
  method: "POST",
42649
43245
  body: {
@@ -42653,6 +43249,11 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
42653
43249
  modelId: selectedModel.id,
42654
43250
  thinkingLevel: controls.thinking.select.value,
42655
43251
  unavailablePolicy: "ask",
43252
+ fallback: {
43253
+ provider: selectedFallback?.provider || "",
43254
+ modelId: selectedFallback?.id || "",
43255
+ thinkingLevel: controls.fallbackThinking.select.value || preferences.generation?.fallback?.thinkingLevel || "low",
43256
+ },
42656
43257
  },
42657
43258
  commit: {
42658
43259
  language: controls.language.select.value,
@@ -42670,7 +43271,7 @@ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
42670
43271
  addTransientMessage({
42671
43272
  role: "native",
42672
43273
  title: "/git-workflow-setup",
42673
- content: `Guided Git setup saved for ${gitWorkflowSetupModelKey(selectedModel)} at ${controls.thinking.select.value} effort.`,
43274
+ content: `Guided Git setup saved. Primary: ${gitWorkflowSetupModelKey(selectedModel)} at ${controls.thinking.select.value} effort. ${selectedFallback ? `Fallback: ${gitWorkflowSetupModelKey(selectedFallback)} at ${controls.fallbackThinking.select.value} effort (one attempt after a final primary generation failure).` : "Fallback: none."}`,
42674
43275
  level: "info",
42675
43276
  });
42676
43277
  closeNativeCommandDialog();
@@ -47314,7 +47915,7 @@ function supervisorContinuityKey(event, fallbackTabId = activeTabId) {
47314
47915
  function scheduleSupervisorContinuityRefresh(event, { gap = false } = {}) {
47315
47916
  const tabContext = activeTabContext(event?.tabId || activeTabId);
47316
47917
  const key = supervisorContinuityKey(event, tabContext.tabId);
47317
- if (!key || !tabContext.tabId || !isCurrentTabContext(tabContext)) return;
47918
+ if (!key || !tabContext.tabId || !isCurrentTabContext(tabContext) || closingTerminalTabIds.has(tabContext.tabId)) return;
47318
47919
 
47319
47920
  if (gap && !supervisorGapWarnings.has(key)) {
47320
47921
  supervisorGapWarnings.add(key);
@@ -47324,14 +47925,15 @@ function scheduleSupervisorContinuityRefresh(event, { gap = false } = {}) {
47324
47925
 
47325
47926
  const timer = setTimeout(async () => {
47326
47927
  try {
47928
+ if (closingTerminalTabIds.has(tabContext.tabId)) return;
47327
47929
  const results = await Promise.allSettled([refreshTabs()]);
47328
- if (isCurrentTabContext(tabContext)) {
47930
+ if (isCurrentTabContext(tabContext) && !closingTerminalTabIds.has(tabContext.tabId)) {
47329
47931
  results.push(...(await Promise.allSettled([
47330
47932
  refreshState(tabContext),
47331
47933
  refreshMessages(tabContext, { authoritative: true }),
47332
47934
  ])));
47333
47935
  }
47334
- if (!isCurrentTabContext(tabContext)) return;
47936
+ if (!isCurrentTabContext(tabContext) || closingTerminalTabIds.has(tabContext.tabId)) return;
47335
47937
  for (const result of results) {
47336
47938
  if (result.status === "rejected") addEvent(`continuity refresh failed: ${result.reason?.message || String(result.reason)}`, "error");
47337
47939
  }
@@ -47453,6 +48055,7 @@ function handleEvent(event) {
47453
48055
  // the same run identity semantics as the foreground tab.
47454
48056
  if (event?.type === "agent_start") beginToolBoundaryRun(event);
47455
48057
  if (eventMayAffectSkillUsage(event)) trackSkillsFromEvent(event);
48058
+ if (handleGitWorkflowFallbackLifecycleEvent(event)) return;
47456
48059
  if (!eventTargetsActiveTab(event)) {
47457
48060
  handleInactiveTabEvent(event);
47458
48061
  return;
@@ -47702,7 +48305,7 @@ function handleEvent(event) {
47702
48305
  handleToolExecutionStart(event);
47703
48306
  }
47704
48307
  setRunIndicatorActivity(`Running tool: ${runIndicatorToolName(event.toolName)}…`);
47705
- if (claimToolBoundaryRecord(event, "log:start")) addEvent(`tool ${event.toolName} started`, "info", { toolCallId: event.toolCallId });
48308
+ if (claimToolBoundaryRecord(event, "log:start")) addEvent(...toolLifecycleEventArguments(event, "start"));
47706
48309
  break;
47707
48310
  case "tool_execution_end": {
47708
48311
  if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ toolRunning: false });
@@ -47722,7 +48325,7 @@ function handleEvent(event) {
47722
48325
  handleToolExecutionEnd(event);
47723
48326
  }
47724
48327
  setRunIndicatorActivity(`Tool ${runIndicatorToolName(event.toolName)} ${event.isError ? "failed" : "finished"}; waiting for the agent's next step…`);
47725
- if (claimToolBoundaryRecord(event, "log:end")) addEvent(`tool ${event.toolName} ${event.isError ? "failed" : "finished"}`, event.isError ? "error" : "info", { toolCallId: event.toolCallId });
48328
+ if (claimToolBoundaryRecord(event, "log:end")) addEvent(...toolLifecycleEventArguments(event, "finish"));
47726
48329
  // Compact tool shells deliberately defer rich body construction to the
47727
48330
  // final transcript reconciliation; normal mode retains its live card.
47728
48331
  scheduleSemanticReconcile({ footerData: true }, tabContext);
@@ -49122,6 +49725,9 @@ document.addEventListener("pointerdown", (event) => {
49122
49725
  if (elements.gitFooterContextMenu && !elements.gitFooterContextMenu.hidden && !event.target?.closest?.(".git-footer-context-menu")) {
49123
49726
  closeGitFooterContextMenu();
49124
49727
  }
49728
+ if (elements.eventTreeContextMenu && !elements.eventTreeContextMenu.hidden && !event.target?.closest?.(".event-tree-context-menu")) {
49729
+ closeEventTreeContextMenu();
49730
+ }
49125
49731
  }, { passive: true });
49126
49732
  document.addEventListener("pointermove", (event) => {
49127
49733
  if (openTerminalTabGroupKey && !event.target?.closest?.(".terminal-tab-group")) {
@@ -49620,6 +50226,59 @@ elements.fileTreeSearchInput?.addEventListener("keydown", (event) => {
49620
50226
  }
49621
50227
  });
49622
50228
  elements.fileTreeSearchClearButton?.addEventListener("click", () => clearFileTreeSearch({ focus: true }));
50229
+ syncEventDisplayModeUi();
50230
+ syncEventFilterUi();
50231
+ elements.eventFilterSelect?.addEventListener("change", () => setEventFilter(elements.eventFilterSelect.value));
50232
+ elements.eventLog?.addEventListener("contextmenu", (event) => {
50233
+ const line = event.target?.closest?.(".event") || null;
50234
+ if (!line && event.target !== elements.eventLog) return;
50235
+ showEventTreeContextMenu(event, line);
50236
+ });
50237
+ elements.eventLog?.addEventListener("keydown", (event) => {
50238
+ if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
50239
+ const line = event.target?.closest?.(".event");
50240
+ if (!line || !elements.eventLog.contains(line)) return;
50241
+ const rect = line.getBoundingClientRect();
50242
+ showEventTreeContextMenu({
50243
+ preventDefault: () => event.preventDefault(),
50244
+ stopPropagation: () => event.stopPropagation(),
50245
+ clientX: rect.left + Math.min(rect.width, 24),
50246
+ clientY: rect.bottom,
50247
+ }, line);
50248
+ });
50249
+ elements.eventTreeContextMenu?.addEventListener("keydown", (event) => {
50250
+ const items = [...elements.eventTreeContextMenu.querySelectorAll('[role="menuitem"]:not([disabled]):not([hidden]), [role="menuitemradio"]:not([disabled]):not([hidden])')];
50251
+ const index = items.indexOf(document.activeElement);
50252
+ if (event.key === "Escape") {
50253
+ event.preventDefault();
50254
+ closeEventTreeContextMenu();
50255
+ } else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
50256
+ event.preventDefault();
50257
+ const direction = event.key === "ArrowDown" ? 1 : -1;
50258
+ items[(Math.max(0, index) + direction + items.length) % items.length]?.focus({ preventScroll: true });
50259
+ } else if (event.key === "Home" || event.key === "End") {
50260
+ event.preventDefault();
50261
+ items[event.key === "Home" ? 0 : items.length - 1]?.focus({ preventScroll: true });
50262
+ }
50263
+ });
50264
+ elements.eventDisplayDetailedAction?.addEventListener("click", () => {
50265
+ setEventDisplayMode("detailed");
50266
+ closeEventTreeContextMenu();
50267
+ });
50268
+ elements.eventDisplayCompactAction?.addEventListener("click", () => {
50269
+ setEventDisplayMode("compact");
50270
+ closeEventTreeContextMenu();
50271
+ });
50272
+ elements.eventTreeContextMenuAction?.addEventListener("click", () => void navigateEventTreeBoundary());
50273
+ window.addEventListener("storage", (event) => {
50274
+ if (event.key === EVENT_DISPLAY_MODE_STORAGE_KEY) setEventDisplayMode(event.newValue, { persist: false });
50275
+ if (event.key === EVENT_FILTER_STORAGE_KEY) setEventFilter(event.newValue, { persist: false });
50276
+ });
50277
+ window.addEventListener("resize", () => closeEventTreeContextMenu(), { passive: true });
50278
+ document.addEventListener("scroll", () => {
50279
+ if (!eventTreeContextMenuState || performance.now() - eventTreeContextMenuState.openedAt < 100) return;
50280
+ closeEventTreeContextMenu();
50281
+ }, { capture: true, passive: true });
49623
50282
  elements.fileContextMenu?.addEventListener("keydown", (event) => {
49624
50283
  const items = [...elements.fileContextMenu.querySelectorAll('[role="menuitem"]:not([disabled])')];
49625
50284
  const index = items.indexOf(document.activeElement);
@@ -49694,12 +50353,17 @@ elements.visibilityContextMenu?.addEventListener("click", (event) => {
49694
50353
  return;
49695
50354
  }
49696
50355
  const action = button.dataset.visibilityMenuAction;
49697
- if (action === "hide") {
50356
+ if (action === "open-setup") {
50357
+ const trigger = visibilityContextMenuState?.trigger;
50358
+ closeVisibilityContextMenu({ returnFocus: false });
50359
+ openControlVisibilitySetupDialog(trigger);
50360
+ } else if (action === "hide") {
49698
50361
  const entryId = visibilityContextMenuState?.entryId;
49699
- closeVisibilityContextMenu();
50362
+ closeVisibilityContextMenu({ returnFocus: false });
49700
50363
  if (entryId) {
49701
50364
  const label = CONTROL_VISIBILITY_REGISTRY.get(entryId)?.label || "control";
49702
50365
  setControlVisibilityHidden(entryId, true);
50366
+ elements.promptInput?.focus({ preventScroll: true });
49703
50367
  offerUndo({
49704
50368
  message: `Hid ${label}. Right-click a toolbar area (or use the command palette) to show hidden controls again.`,
49705
50369
  undo: () => setControlVisibilityHidden(entryId, false),
@@ -49714,6 +50378,28 @@ elements.visibilityContextMenu?.addEventListener("click", (event) => {
49714
50378
  resetControlVisibilityDefaults();
49715
50379
  }
49716
50380
  });
50381
+ elements.controlVisibilitySetupBody?.addEventListener("change", (event) => {
50382
+ const checkbox = event.target?.closest?.("[data-visibility-setup-id]");
50383
+ if (!(checkbox instanceof HTMLInputElement)) return;
50384
+ const entry = CONTROL_VISIBILITY_REGISTRY.get(checkbox.dataset.visibilitySetupId);
50385
+ if (!entry) return;
50386
+ setControlVisibilityHidden(entry.id, !checkbox.checked);
50387
+ refreshControlVisibilitySetupDialog();
50388
+ setControlVisibilitySetupStatus(`${entry.label} is ${checkbox.checked ? "shown" : "hidden"} by preference.`);
50389
+ });
50390
+ elements.controlVisibilitySetupShowAllButton?.addEventListener("click", () => {
50391
+ showAllControls();
50392
+ refreshControlVisibilitySetupDialog();
50393
+ setControlVisibilitySetupStatus("All optional controls are shown by preference.");
50394
+ });
50395
+ elements.controlVisibilitySetupResetButton?.addEventListener("click", () => {
50396
+ resetControlVisibilityDefaults();
50397
+ refreshControlVisibilitySetupDialog();
50398
+ setControlVisibilitySetupStatus("Control visibility was reset to its defaults.");
50399
+ });
50400
+ elements.controlVisibilitySetupCloseButton?.addEventListener("click", () => elements.controlVisibilitySetupDialog?.close());
50401
+ elements.controlVisibilitySetupDialog?.querySelector("form")?.addEventListener("submit", (event) => event.preventDefault());
50402
+ elements.controlVisibilitySetupDialog?.addEventListener("close", restoreControlVisibilitySetupFocus);
49717
50403
  elements.gitFooterContextMenu?.addEventListener("keydown", (event) => {
49718
50404
  const items = [...elements.gitFooterContextMenu.querySelectorAll('[role="menuitem"]:not([disabled])')];
49719
50405
  const index = items.indexOf(document.activeElement);