@firstpick/pi-package-webui 0.7.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/app.js CHANGED
@@ -203,6 +203,10 @@ const elements = {
203
203
  fileTreeRefreshButton: $("#fileTreeRefreshButton"),
204
204
  fileTreeSearchInput: $("#fileTreeSearchInput"),
205
205
  fileTreeSearchClearButton: $("#fileTreeSearchClearButton"),
206
+ gitPanelGroups: $("#gitPanelGroups"),
207
+ gitPanelStatus: $("#gitPanelStatus"),
208
+ gitPanelCountBadge: $("#gitPanelCountBadge"),
209
+ gitPanelContextMenu: $("#gitPanelContextMenu"),
206
210
  fileViewerPane: $("#fileViewerPane"),
207
211
  fileViewerResizeHandle: $("#fileViewerResizeHandle"),
208
212
  fileViewerTitle: $("#fileViewerTitle"),
@@ -221,6 +225,7 @@ const elements = {
221
225
  fileSelectionCommentInput: $("#fileSelectionCommentInput"),
222
226
  fileSelectionSendButton: $("#fileSelectionSendButton"),
223
227
  fileContextMenu: $("#fileContextMenu"),
228
+ sidePanelContextMenu: $("#sidePanelContextMenu"),
224
229
  toggleSidePanelButton: $("#toggleSidePanelButton"),
225
230
  sidePanelExpandButton: $("#sidePanelExpandButton"),
226
231
  sidePanelBackdrop: $("#sidePanelBackdrop"),
@@ -360,6 +365,7 @@ let fileTreeState = { root: "", entriesByPath: new Map(), expanded: new Set(), l
360
365
  let activeFileViewer = null;
361
366
  let fileViewerSelection = null;
362
367
  let fileContextMenuState = null;
368
+ let sidePanelContextMenuState = null;
363
369
  let fileTreeDragState = null;
364
370
  let fileViewerResizeState = null;
365
371
  let fileTreeSearchTimer = null;
@@ -386,6 +392,8 @@ let streamToolCallComplete = false;
386
392
  let streamThinkingBubble = null;
387
393
  let streamThinking = null;
388
394
  let streamMessageActive = false;
395
+ let streamProviderErrorText = "";
396
+ let assistantErrorSurfacedThisRun = false;
389
397
  let runIndicatorBubble = null;
390
398
  let runIndicatorText = null;
391
399
  let runIndicatorMeta = null;
@@ -413,8 +421,19 @@ let undoToastFocusReturn = null;
413
421
  const modalSurfaceState = new WeakMap();
414
422
  let activeDrawerModal = null;
415
423
  let activeGitPrDialogResolve = null;
416
- let gitChangesState = { loading: false, pulling: false, fetching: false, error: "", errorCode: "", errorHint: "", message: "", pullResult: null, data: null, operation: null, lastFetch: null, tabId: null };
424
+ let gitChangesState = { loading: false, pulling: false, fetching: false, error: "", errorCode: "", errorHint: "", message: "", pullResult: null, data: null, operation: null, lastFetch: null, tabId: null, mode: "changes", commit: null };
417
425
  let gitToolsState = { tabId: null, openSections: new Set(), cache: {}, busy: new Set(), notice: {} };
426
+ let gitPanelState = {
427
+ expandedCardKey: "",
428
+ discovery: new Map(),
429
+ repositories: new Map(),
430
+ activeViews: new Map(),
431
+ openFolders: new Map(),
432
+ busy: new Set(),
433
+ requestSerial: 0,
434
+ };
435
+ let gitPanelContextMenuState = null;
436
+ let gitPanelRenderSignature = null;
418
437
  let gitChangesRequestSerial = 0;
419
438
  const gitChangesUntrackedContentRequests = new Set();
420
439
  let nativeCommandTabId = null;
@@ -600,6 +619,7 @@ const dialogQueue = [];
600
619
  const SIDE_PANEL_STORAGE_KEY = "pi-webui-side-panel-collapsed";
601
620
  const INTERFACE_DENSITY_STORAGE_KEY = "pi-webui-interface-density";
602
621
  const SIDE_PANEL_SECTION_STORAGE_KEY = "pi-webui-side-panel-sections-collapsed";
622
+ const SIDE_PANEL_SECTION_VISIBILITY_STORAGE_KEY = "pi-webui-side-panel-sections-hidden";
603
623
  const TAB_STORAGE_KEY = "pi-webui-active-tab";
604
624
  const PATH_FAST_PICKS_STORAGE_KEY = "pi-webui-path-fast-picks";
605
625
  const AGENT_DONE_NOTIFICATIONS_STORAGE_KEY = "pi-webui-agent-done-notifications";
@@ -713,6 +733,7 @@ const AUR_REVIEW_RPC_PAYLOAD_TYPE = "firstpick.pi-extension-aur-review.review";
713
733
  const AUR_REVIEW_RPC_PAYLOAD_VERSION = 3;
714
734
  const GIT_CHANGES_RENDER_ROW_LIMIT = 4000;
715
735
  const GIT_PULL_RESULT_FILE_LIMIT = 48;
736
+ const GIT_PANEL_CACHE_MAX_AGE_MS = 5 * 60 * 1000;
716
737
  const LAST_USER_PROMPT_STORAGE_KEY = "pi-webui-last-user-prompts";
717
738
  const PROMPT_HISTORY_STORAGE_KEY = "pi-webui-prompt-history";
718
739
  const PROMPT_LIST_STORAGE_KEY = "pi-webui-prompt-lists";
@@ -818,6 +839,7 @@ const workflowModeByTab = new Map();
818
839
  const workflowModeTogglePendingByTab = new Set();
819
840
  const workflowInspectorByTab = new Map();
820
841
  const workflowInspectorSelectionByTab = new Map();
842
+ const workflowInspectorMinimizedByTab = new Set();
821
843
  const appRunnerInputDraftByRun = new Map();
822
844
  const appRunnerContextLineDraftByRun = new Map();
823
845
  const liveToolRuns = new Map();
@@ -1136,6 +1158,7 @@ function createGitWorkflowState() {
1136
1158
  manualCommitMessage: "",
1137
1159
  ...resetGitWorkflowManualCommitDefaultPatch(),
1138
1160
  messageRequestedAt: 0,
1161
+ messageGenerationId: "",
1139
1162
  branchName: "",
1140
1163
  branchNameRequestedAt: 0,
1141
1164
  actionsDone: createGitWorkflowActionsDone(),
@@ -1151,6 +1174,7 @@ function createGitWorkflowState() {
1151
1174
  }
1152
1175
 
1153
1176
  const gitWorkflowsByTab = new Map();
1177
+ const gitWorkflowMessageLoadsByTab = new Map();
1154
1178
  let gitWorkflow = createGitWorkflowState();
1155
1179
  let gitWorkflowPreferences = null;
1156
1180
 
@@ -1511,6 +1535,46 @@ function persistSidePanelSectionState() {
1511
1535
  }
1512
1536
  }
1513
1537
 
1538
+ function readStoredSidePanelSectionHiddenIds() {
1539
+ try {
1540
+ const stored = localStorage.getItem(SIDE_PANEL_SECTION_VISIBILITY_STORAGE_KEY);
1541
+ if (stored === null) return new Set();
1542
+ const parsed = JSON.parse(stored);
1543
+ return new Set(Array.isArray(parsed) ? parsed.filter((value) => typeof value === "string") : []);
1544
+ } catch {
1545
+ return new Set();
1546
+ }
1547
+ }
1548
+
1549
+ function persistSidePanelSectionVisibility() {
1550
+ try {
1551
+ const hidden = sidePanelSectionRecords()
1552
+ .filter(({ section }) => section.hidden)
1553
+ .map(({ id }) => id);
1554
+ localStorage.setItem(SIDE_PANEL_SECTION_VISIBILITY_STORAGE_KEY, JSON.stringify(hidden));
1555
+ } catch {
1556
+ // Ignore storage failures; visibility toggles should still work for this page load.
1557
+ }
1558
+ }
1559
+
1560
+ function setSidePanelSectionVisible(record, visible, { persist = true } = {}) {
1561
+ record.section.hidden = !visible;
1562
+ if (visible && record.id === "git" && !record.section.classList.contains("collapsed")) {
1563
+ queueMicrotask(() => {
1564
+ renderGitPanel();
1565
+ ensureGitPanelRepositoriesDiscovered({ retryUnavailable: true });
1566
+ });
1567
+ }
1568
+ if (persist) persistSidePanelSectionVisibility();
1569
+ }
1570
+
1571
+ function restoreSidePanelSectionVisibility() {
1572
+ const hiddenIds = readStoredSidePanelSectionHiddenIds();
1573
+ for (const record of sidePanelSectionRecords()) {
1574
+ setSidePanelSectionVisible(record, !hiddenIds.has(record.id), { persist: false });
1575
+ }
1576
+ }
1577
+
1514
1578
  function setSidePanelSectionCollapsed(record, collapsed, { persist = true } = {}) {
1515
1579
  const label = record.button.querySelector(".side-panel-section-label")?.textContent?.trim() || "side panel";
1516
1580
  record.section.classList.toggle("collapsed", collapsed);
@@ -1518,6 +1582,12 @@ function setSidePanelSectionCollapsed(record, collapsed, { persist = true } = {}
1518
1582
  record.button.setAttribute("aria-expanded", collapsed ? "false" : "true");
1519
1583
  record.button.setAttribute("aria-label", `${collapsed ? "Expand" : "Collapse"} ${label} section`);
1520
1584
  record.button.setAttribute("title", `${collapsed ? "Expand" : "Collapse"} ${label} section`);
1585
+ if (!collapsed && record.id === "git" && !record.section.hidden) {
1586
+ queueMicrotask(() => {
1587
+ renderGitPanel();
1588
+ ensureGitPanelRepositoriesDiscovered({ retryUnavailable: true });
1589
+ });
1590
+ }
1521
1591
  if (persist) persistSidePanelSectionState();
1522
1592
  }
1523
1593
 
@@ -1539,6 +1609,58 @@ function restoreSidePanelSectionState() {
1539
1609
  }
1540
1610
  }
1541
1611
 
1612
+ function closeSidePanelContextMenu({ returnFocus = true } = {}) {
1613
+ const trigger = sidePanelContextMenuState?.trigger;
1614
+ sidePanelContextMenuState = null;
1615
+ if (elements.sidePanelContextMenu) elements.sidePanelContextMenu.hidden = true;
1616
+ if (!returnFocus) return;
1617
+ const focusTarget = trigger?.isConnected && !trigger.closest?.("[data-side-panel-section][hidden]")
1618
+ ? trigger
1619
+ : elements.toggleSidePanelButton;
1620
+ if (focusTarget?.isConnected) queueMicrotask(() => focusTarget.focus?.({ preventScroll: true }));
1621
+ }
1622
+
1623
+ function showSidePanelContextMenu(event) {
1624
+ if (!elements.sidePanelContextMenu) return;
1625
+ if (event.target?.closest?.("a, input, textarea, select, [contenteditable='true']")) return;
1626
+ event.preventDefault();
1627
+ event.stopPropagation();
1628
+ closeFileContextMenu({ returnFocus: false });
1629
+ closeGitPanelContextMenu({ returnFocus: false });
1630
+ closeSidePanelContextMenu({ returnFocus: false });
1631
+
1632
+ const menu = elements.sidePanelContextMenu;
1633
+ const eventTrigger = event.currentTarget;
1634
+ const trigger = eventTrigger && eventTrigger !== elements.sidePanel ? eventTrigger : document.activeElement;
1635
+ sidePanelContextMenuState = { trigger: trigger?.focus ? trigger : elements.toggleSidePanelButton };
1636
+ const label = make("div", "side-panel-context-menu-label", "Show sections");
1637
+ label.setAttribute("role", "presentation");
1638
+ label.setAttribute("aria-hidden", "true");
1639
+ const items = sidePanelSectionRecords().map((record) => {
1640
+ const sectionLabel = record.button.querySelector(".side-panel-section-label")?.textContent?.trim() || record.id;
1641
+ const button = make("button", "side-panel-context-menu-item", sectionLabel);
1642
+ const visible = !record.section.hidden;
1643
+ button.type = "button";
1644
+ button.setAttribute("role", "menuitemcheckbox");
1645
+ button.setAttribute("aria-checked", visible ? "true" : "false");
1646
+ button.dataset.sidePanelSectionVisibility = record.id;
1647
+ button.addEventListener("click", () => {
1648
+ const nextVisible = record.section.hidden;
1649
+ setSidePanelSectionVisible(record, nextVisible);
1650
+ button.setAttribute("aria-checked", nextVisible ? "true" : "false");
1651
+ });
1652
+ return button;
1653
+ });
1654
+ menu.replaceChildren(label, ...items);
1655
+ menu.hidden = false;
1656
+ const rect = menu.getBoundingClientRect();
1657
+ const left = Math.min(event.clientX, Math.max(8, window.innerWidth - rect.width - 8));
1658
+ const top = Math.min(event.clientY, Math.max(8, window.innerHeight - rect.height - 8));
1659
+ menu.style.left = `${Math.max(8, left)}px`;
1660
+ menu.style.top = `${Math.max(8, top)}px`;
1661
+ menu.querySelector('[role="menuitemcheckbox"]')?.focus({ preventScroll: true });
1662
+ }
1663
+
1542
1664
  function bindSidePanelSectionToggles() {
1543
1665
  for (const record of sidePanelSectionRecords()) {
1544
1666
  record.button.addEventListener("click", () => {
@@ -1551,6 +1673,23 @@ function bindSidePanelSectionToggles() {
1551
1673
  }
1552
1674
  }
1553
1675
 
1676
+ function bindSidePanelContextMenu() {
1677
+ elements.sidePanel?.addEventListener("contextmenu", showSidePanelContextMenu);
1678
+ elements.sidePanel?.addEventListener("keydown", (event) => {
1679
+ if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
1680
+ const trigger = event.target instanceof Element ? event.target : elements.sidePanel;
1681
+ const rect = trigger.getBoundingClientRect();
1682
+ showSidePanelContextMenu({
1683
+ preventDefault: () => event.preventDefault(),
1684
+ stopPropagation: () => event.stopPropagation(),
1685
+ clientX: rect.left + Math.min(rect.width, 24),
1686
+ clientY: rect.bottom,
1687
+ currentTarget: trigger,
1688
+ target: trigger,
1689
+ });
1690
+ });
1691
+ }
1692
+
1554
1693
  function readStoredAgentDoneNotificationsEnabled() {
1555
1694
  try {
1556
1695
  return localStorage.getItem(AGENT_DONE_NOTIFICATIONS_STORAGE_KEY) === "1";
@@ -2909,6 +3048,7 @@ function setSidePanelCollapsed(collapsed, { persist = true, focusPanel = false }
2909
3048
  elements.toggleSidePanelButton.setAttribute("aria-label", collapsed ? "Expand side panel" : "Collapse side panel");
2910
3049
  elements.sidePanelExpandButton.setAttribute("aria-expanded", collapsed ? "false" : "true");
2911
3050
  syncMobileSidePanelState(collapsed);
3051
+ if (collapsed) closeSidePanelContextMenu({ returnFocus: false });
2912
3052
 
2913
3053
  if (!collapsed && focusPanel && isSidePanelOverlayView()) {
2914
3054
  requestAnimationFrame(() => elements.toggleSidePanelButton.focus());
@@ -3549,6 +3689,9 @@ async function api(path, { method = "GET", body, tabId = activeTabId, scoped = t
3549
3689
  signal,
3550
3690
  });
3551
3691
  } catch (error) {
3692
+ // Aborted autocomplete requests are expected while the user keeps typing;
3693
+ // they do not indicate that the Web UI backend became unreachable.
3694
+ if (signal?.aborted || error?.name === "AbortError") throw error;
3552
3695
  const offlineError = error instanceof Error ? error : new Error(String(error));
3553
3696
  offlineError.backendOffline = true;
3554
3697
  setBackendOffline(true, offlineError);
@@ -6611,6 +6754,8 @@ function showFileContextMenu(event, entry) {
6611
6754
  if (!elements.fileContextMenu) return;
6612
6755
  event.preventDefault();
6613
6756
  event.stopPropagation();
6757
+ closeGitPanelContextMenu({ returnFocus: false });
6758
+ closeSidePanelContextMenu({ returnFocus: false });
6614
6759
  const path = normalizeFileTreePath(entry?.path || "");
6615
6760
  fileContextMenuState = { entry: { ...entry, path }, trigger: event.currentTarget || document.activeElement };
6616
6761
  const menu = elements.fileContextMenu;
@@ -7559,6 +7704,7 @@ function syncTabMetadata(nextTabs = []) {
7559
7704
  workflowModeTogglePendingByTab.delete(tabId);
7560
7705
  workflowInspectorByTab.delete(tabId);
7561
7706
  workflowInspectorSelectionByTab.delete(tabId);
7707
+ workflowInspectorMinimizedByTab.delete(tabId);
7562
7708
  remoteMicConsentTabs.delete(tabId);
7563
7709
  if (voiceConversationTabId === tabId) stopVoiceConversationLoop();
7564
7710
  clearGitWorkflowForTab(tabId);
@@ -8089,6 +8235,621 @@ function terminalDisplayGroupDetail(group, fallback = "group") {
8089
8235
  return `${cwdLabels[0]} + ${cwdLabels.length - 1} cwd${cwdLabels.length === 2 ? "" : "s"}`;
8090
8236
  }
8091
8237
 
8238
+ function gitPanelSectionExpanded() {
8239
+ const section = elements.sidePanel?.querySelector('[data-side-panel-section="git"]');
8240
+ return Boolean(section && !section.hidden && !section.classList.contains("collapsed"));
8241
+ }
8242
+
8243
+ function gitPanelTerminalGroups() {
8244
+ const cwdGroups = tabCwdGroups();
8245
+ const groups = [];
8246
+ for (const group of cwdGroups) {
8247
+ if (shouldRenderTerminalTabGroup(group, cwdGroups.length)) {
8248
+ groups.push({ ...group, title: terminalDisplayGroupTitle(group), detail: terminalDisplayGroupDetail(group) });
8249
+ continue;
8250
+ }
8251
+ for (const tab of group.tabs || []) {
8252
+ groups.push({
8253
+ key: `tab:${tab.id}`,
8254
+ custom: false,
8255
+ cwd: tab.cwd || "",
8256
+ tabs: [tab],
8257
+ title: tabGroupTitle(tab.cwd, "Working directory"),
8258
+ detail: normalizeDisplayPath(tab.cwd || ""),
8259
+ });
8260
+ }
8261
+ }
8262
+ return groups;
8263
+ }
8264
+
8265
+ function gitPanelCandidates(groups = gitPanelTerminalGroups()) {
8266
+ const byCwd = new Map();
8267
+ for (const group of groups) {
8268
+ for (const tab of group.tabs || []) {
8269
+ const cwd = String(tab.cwd || "").trim();
8270
+ if (!cwd || byCwd.has(cwd)) continue;
8271
+ byCwd.set(cwd, {
8272
+ key: `cwd:${cwd}`,
8273
+ cwd,
8274
+ tabId: tab.id,
8275
+ tabTitle: tabGroupTitle(cwd, "Working directory"),
8276
+ });
8277
+ }
8278
+ }
8279
+ return [...byCwd.values()];
8280
+ }
8281
+
8282
+ function gitPanelRepositoryCards(groups = gitPanelTerminalGroups()) {
8283
+ const byIdentity = new Map();
8284
+ for (const candidate of gitPanelCandidates(groups)) {
8285
+ const discovery = gitPanelState.discovery.get(candidate.key);
8286
+ const root = String(discovery?.root || "");
8287
+ const identity = root ? `root:${root}` : candidate.key;
8288
+ let card = byIdentity.get(identity);
8289
+ if (!card) {
8290
+ card = {
8291
+ key: identity,
8292
+ root,
8293
+ cwd: candidate.cwd,
8294
+ tabId: candidate.tabId,
8295
+ candidates: [],
8296
+ discovery,
8297
+ };
8298
+ byIdentity.set(identity, card);
8299
+ }
8300
+ card.candidates.push(candidate);
8301
+ if (!card.discovery && discovery) card.discovery = discovery;
8302
+ }
8303
+ return [...byIdentity.values()];
8304
+ }
8305
+
8306
+ function gitPanelRootLabel(root, fallback = "Repository") {
8307
+ const normalized = normalizeDisplayPath(root || "").replace(/\/+$/, "");
8308
+ return normalized.split("/").filter(Boolean).pop() || normalized || fallback;
8309
+ }
8310
+
8311
+ function gitPanelSnapshot(root) {
8312
+ return root ? gitPanelState.repositories.get(root) || null : null;
8313
+ }
8314
+
8315
+ function gitPanelSnapshotFresh(snapshot) {
8316
+ return Boolean(snapshot?.data && Date.now() - Number(snapshot.loadedAt || 0) < GIT_PANEL_CACHE_MAX_AGE_MS);
8317
+ }
8318
+
8319
+ async function discoverGitPanelCandidate(candidate, { force = false } = {}) {
8320
+ const current = gitPanelState.discovery.get(candidate.key);
8321
+ if (current?.loading || (!force && (current?.root || current?.resolved))) return;
8322
+ const requestSerial = ++gitPanelState.requestSerial;
8323
+ gitPanelState.discovery.set(candidate.key, { loading: true, resolved: false, requestSerial, root: "", error: "" });
8324
+ renderGitPanel();
8325
+ try {
8326
+ const response = await api("/api/git-root", { tabId: candidate.tabId });
8327
+ const latest = gitPanelState.discovery.get(candidate.key);
8328
+ if (latest?.requestSerial !== requestSerial) return;
8329
+ if (!response.ok || !response.data?.root) throw new Error(response.error || "Not a Git repository");
8330
+ gitPanelState.discovery.set(candidate.key, { loading: false, resolved: true, requestSerial, checkedAt: Date.now(), root: response.data.root, error: "" });
8331
+ } catch (error) {
8332
+ const latest = gitPanelState.discovery.get(candidate.key);
8333
+ if (latest?.requestSerial !== requestSerial) return;
8334
+ gitPanelState.discovery.set(candidate.key, { loading: false, resolved: true, requestSerial, checkedAt: Date.now(), root: "", error: error.message || String(error) });
8335
+ }
8336
+ renderGitPanel();
8337
+ }
8338
+
8339
+ function ensureGitPanelRepositoriesDiscovered({ retryUnavailable = false } = {}) {
8340
+ if (!gitPanelSectionExpanded()) return;
8341
+ for (const candidate of gitPanelCandidates()) {
8342
+ const discovery = gitPanelState.discovery.get(candidate.key);
8343
+ if (!discovery || (!discovery.loading && !discovery.resolved)) {
8344
+ void discoverGitPanelCandidate(candidate);
8345
+ } else if (retryUnavailable && !discovery.loading && !discovery.root) {
8346
+ void discoverGitPanelCandidate(candidate, { force: true });
8347
+ }
8348
+ }
8349
+ }
8350
+
8351
+ async function loadGitPanelRepository(card, { force = false } = {}) {
8352
+ if (!card?.root || !card.tabId) return;
8353
+ const existing = gitPanelSnapshot(card.root);
8354
+ if (!force && gitPanelSnapshotFresh(existing)) return;
8355
+ if (existing?.loading) {
8356
+ if (force && !existing.refreshPending) {
8357
+ gitPanelState.repositories.set(card.root, { ...existing, refreshPending: true });
8358
+ }
8359
+ return;
8360
+ }
8361
+ const requestSerial = ++gitPanelState.requestSerial;
8362
+ gitPanelState.repositories.set(card.root, { ...existing, loading: true, error: "", requestSerial, refreshPending: false });
8363
+ renderGitPanel();
8364
+ let refreshAgain = false;
8365
+ try {
8366
+ const response = await api("/api/git-panel", { tabId: card.tabId });
8367
+ const latest = gitPanelSnapshot(card.root);
8368
+ if (latest?.requestSerial !== requestSerial) return;
8369
+ refreshAgain = latest.refreshPending === true;
8370
+ if (!response.ok || !response.data?.root) throw new Error(response.error || "Failed to load Git repository");
8371
+ gitPanelState.repositories.set(card.root, {
8372
+ loading: false,
8373
+ error: "",
8374
+ requestSerial,
8375
+ loadedAt: Date.now(),
8376
+ refreshPending: false,
8377
+ data: response.data,
8378
+ });
8379
+ } catch (error) {
8380
+ const latest = gitPanelSnapshot(card.root);
8381
+ if (latest?.requestSerial !== requestSerial) return;
8382
+ refreshAgain = refreshAgain || latest.refreshPending === true;
8383
+ gitPanelState.repositories.set(card.root, {
8384
+ ...latest,
8385
+ loading: false,
8386
+ error: error.message || String(error),
8387
+ requestSerial,
8388
+ refreshPending: false,
8389
+ });
8390
+ }
8391
+ renderGitPanel();
8392
+ if (refreshAgain) queueMicrotask(() => loadGitPanelRepository(card, { force: true }));
8393
+ }
8394
+
8395
+ function invalidateGitPanelRepository(root) {
8396
+ const repositoryRoot = String(root || "");
8397
+ const snapshot = gitPanelSnapshot(repositoryRoot);
8398
+ if (!snapshot) return;
8399
+ gitPanelState.repositories.set(repositoryRoot, {
8400
+ ...snapshot,
8401
+ error: "",
8402
+ loadedAt: 0,
8403
+ refreshPending: snapshot.loading === true,
8404
+ });
8405
+ if (!gitPanelSectionExpanded()) return;
8406
+ const card = gitPanelRepositoryCards().find((candidate) => candidate.root === repositoryRoot);
8407
+ if (card) void loadGitPanelRepository(card, { force: true });
8408
+ }
8409
+
8410
+ function ensureGitPanelVisibleRepositoriesFresh(cards = gitPanelRepositoryCards()) {
8411
+ for (const card of cards) {
8412
+ const snapshot = gitPanelSnapshot(card.root);
8413
+ const expanded = gitPanelState.expandedCardKey === card.key;
8414
+ if (snapshot?.loading || snapshot?.error || (!snapshot?.data && !expanded) || gitPanelSnapshotFresh(snapshot)) continue;
8415
+ void loadGitPanelRepository(card);
8416
+ }
8417
+ }
8418
+
8419
+ function toggleGitPanelRepository(card) {
8420
+ if (!card?.root) return;
8421
+ if (gitPanelState.expandedCardKey === card.key) {
8422
+ gitPanelState.expandedCardKey = "";
8423
+ renderGitPanel();
8424
+ return;
8425
+ }
8426
+ gitPanelState.expandedCardKey = card.key;
8427
+ renderGitPanel();
8428
+ const snapshot = gitPanelSnapshot(card.root);
8429
+ if (!gitPanelSnapshotFresh(snapshot)) void loadGitPanelRepository(card);
8430
+ }
8431
+
8432
+ function gitPanelChangeCount(data) {
8433
+ return Array.isArray(data?.changes) ? data.changes.length : 0;
8434
+ }
8435
+
8436
+ function gitPanelStatsText(entry = {}, category = "") {
8437
+ const prefix = category === "staged" ? "staged" : category === "changes" ? "unstaged" : "";
8438
+ const binary = prefix ? entry[`${prefix}Binary`] === true : entry.binary === true;
8439
+ if (binary) return "binary";
8440
+ const additions = Number(prefix ? entry[`${prefix}Additions`] : entry.additions || 0) || 0;
8441
+ const deletions = Number(prefix ? entry[`${prefix}Deletions`] : entry.deletions || 0) || 0;
8442
+ if (!additions && !deletions) return entry.untracked ? "new" : "";
8443
+ return `${additions ? `+${additions}` : "+0"} ${deletions ? `−${deletions}` : "−0"}`;
8444
+ }
8445
+
8446
+ function gitPanelTree(entries = []) {
8447
+ const root = { name: "", path: "", folders: new Map(), files: [] };
8448
+ for (const entry of entries) {
8449
+ const parts = String(entry.path || "").split("/").filter(Boolean);
8450
+ if (!parts.length) continue;
8451
+ const fileName = parts.pop();
8452
+ let node = root;
8453
+ let currentPath = "";
8454
+ for (const part of parts) {
8455
+ currentPath = currentPath ? `${currentPath}/${part}` : part;
8456
+ if (!node.folders.has(part)) node.folders.set(part, { name: part, path: currentPath, folders: new Map(), files: [] });
8457
+ node = node.folders.get(part);
8458
+ }
8459
+ node.files.push({ ...entry, name: fileName });
8460
+ }
8461
+ return root;
8462
+ }
8463
+
8464
+ function closeGitPanelContextMenu({ returnFocus = true } = {}) {
8465
+ const trigger = gitPanelContextMenuState?.trigger;
8466
+ gitPanelContextMenuState = null;
8467
+ if (elements.gitPanelContextMenu) elements.gitPanelContextMenu.hidden = true;
8468
+ if (returnFocus && trigger?.isConnected) queueMicrotask(() => trigger.focus({ preventScroll: true }));
8469
+ }
8470
+
8471
+ function gitPanelContextMenuItems(context) {
8472
+ const { card, category = "", kind = "file", path = "" } = context || {};
8473
+ if (!card?.root) return [];
8474
+ if (kind === "repository") {
8475
+ const snapshot = gitPanelSnapshot(card.root);
8476
+ return [
8477
+ { label: "View Diff", run: () => openGitChangesDialog(card.tabId) },
8478
+ { label: snapshot?.loading ? "Refreshing…" : "Refresh", disabled: snapshot?.loading, run: () => loadGitPanelRepository(card, { force: true }) },
8479
+ { label: "Stage All", disabled: gitPanelActionBusy(card, "stage-all"), run: () => runGitPanelAction(card, "stage-all") },
8480
+ { label: "Unstage All", disabled: gitPanelActionBusy(card, "unstage-all"), run: () => runGitPanelAction(card, "unstage-all") },
8481
+ ];
8482
+ }
8483
+ const target = kind === "folder" ? "folder" : "file";
8484
+ if (category === "staged") {
8485
+ return [{ label: `Unstage ${target}`, disabled: gitPanelActionBusy(card, "unstage", path), run: () => runGitPanelAction(card, "unstage", path) }];
8486
+ }
8487
+ const stageLabel = category === "conflicted" ? `Stage ${target} / mark resolved` : `Stage ${target}`;
8488
+ const items = [{ label: stageLabel, disabled: gitPanelActionBusy(card, "stage", path), run: () => runGitPanelAction(card, "stage", path) }];
8489
+ if (kind === "file" && category === "changes") {
8490
+ items.push({ label: "Discard changes…", danger: true, disabled: gitPanelActionBusy(card, "discard", path), run: () => runGitPanelAction(card, "discard", path) });
8491
+ }
8492
+ if (kind === "file" && category === "untracked") {
8493
+ items.push({ label: "Delete file…", danger: true, disabled: gitPanelActionBusy(card, "delete", path), run: () => runGitPanelAction(card, "delete", path) });
8494
+ }
8495
+ return items;
8496
+ }
8497
+
8498
+ function showGitPanelContextMenu(event, context) {
8499
+ if (!elements.gitPanelContextMenu) return;
8500
+ event.preventDefault();
8501
+ event.stopPropagation();
8502
+ closeFileContextMenu({ returnFocus: false });
8503
+ closeGitPanelContextMenu({ returnFocus: false });
8504
+ closeSidePanelContextMenu({ returnFocus: false });
8505
+ const menu = elements.gitPanelContextMenu;
8506
+ const items = gitPanelContextMenuItems(context);
8507
+ if (!items.length) return;
8508
+ const trigger = event.currentTarget || document.activeElement;
8509
+ gitPanelContextMenuState = { ...context, trigger };
8510
+ const labelText = context.kind === "repository" ? gitPanelRootLabel(context.card.root) : context.path;
8511
+ const label = make("div", "git-side-panel-context-label", labelText);
8512
+ const buttons = items.map((item) => {
8513
+ const button = make("button", item.danger ? "danger" : "", item.label);
8514
+ button.type = "button";
8515
+ button.setAttribute("role", "menuitem");
8516
+ button.disabled = Boolean(item.disabled);
8517
+ button.addEventListener("click", () => {
8518
+ closeGitPanelContextMenu();
8519
+ void item.run();
8520
+ });
8521
+ return button;
8522
+ });
8523
+ menu.replaceChildren(label, ...buttons);
8524
+ menu.hidden = false;
8525
+ const rect = menu.getBoundingClientRect();
8526
+ const left = Math.min(event.clientX, Math.max(8, window.innerWidth - rect.width - 8));
8527
+ const top = Math.min(event.clientY, Math.max(8, window.innerHeight - rect.height - 8));
8528
+ menu.style.left = `${Math.max(8, left)}px`;
8529
+ menu.style.top = `${Math.max(8, top)}px`;
8530
+ menu.querySelector('[role="menuitem"]:not([disabled])')?.focus({ preventScroll: true });
8531
+ }
8532
+
8533
+ function bindGitPanelContextMenu(trigger, context) {
8534
+ trigger.setAttribute("aria-haspopup", "menu");
8535
+ trigger.addEventListener("contextmenu", (event) => showGitPanelContextMenu(event, context));
8536
+ trigger.addEventListener("keydown", (event) => {
8537
+ if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
8538
+ const rect = trigger.getBoundingClientRect();
8539
+ showGitPanelContextMenu({
8540
+ preventDefault: () => event.preventDefault(),
8541
+ stopPropagation: () => event.stopPropagation(),
8542
+ clientX: rect.left + Math.min(rect.width, 24),
8543
+ clientY: rect.bottom,
8544
+ currentTarget: trigger,
8545
+ }, context);
8546
+ });
8547
+ }
8548
+
8549
+ function gitPanelActionBusy(card, action, path = "") {
8550
+ return gitPanelState.busy.has(`${card.root}\u0000${action}\u0000${path}`);
8551
+ }
8552
+
8553
+ async function runGitPanelAction(card, action, path = "") {
8554
+ const config = {
8555
+ stage: { url: "/api/git-changes/stage-file", body: { path }, past: `Staged ${path}.` },
8556
+ unstage: { url: "/api/git-changes/unstage-file", body: { path }, past: `Unstaged ${path}.` },
8557
+ "stage-all": { url: "/api/git-changes/stage-all", body: {}, past: `Staged all changes in ${card.root}.` },
8558
+ "unstage-all": { url: "/api/git-changes/unstage-all", body: {}, past: `Unstaged all changes in ${card.root}.` },
8559
+ discard: {
8560
+ url: "/api/git-changes/discard-file",
8561
+ body: { path, confirmed: true },
8562
+ past: `Discarded tracked changes in ${path}.`,
8563
+ confirm: `Discard tracked working-tree changes in ${path}?\n\nRepository: ${card.root}\nCommand: git restore -- ${path}\n\nThis permanently reverts unstaged edits to this path.`,
8564
+ confirmLabel: "Discard changes",
8565
+ },
8566
+ delete: {
8567
+ url: "/api/git-changes/delete-untracked",
8568
+ body: { path, confirmed: true },
8569
+ past: `Deleted untracked file ${path}.`,
8570
+ confirm: `Delete untracked file ${path}?\n\nRepository: ${card.root}\n\nThis permanently removes the file from disk.`,
8571
+ confirmLabel: "Delete file",
8572
+ },
8573
+ }[action];
8574
+ if (!config || !card?.root || !card.tabId) return;
8575
+ if (config.confirm && !(await appConfirmText(config.confirm, { affected: path || card.root, confirmLabel: config.confirmLabel }))) return;
8576
+ const busyKey = `${card.root}\u0000${action}\u0000${path}`;
8577
+ if (gitPanelState.busy.has(busyKey)) return;
8578
+ gitPanelState.busy.add(busyKey);
8579
+ renderGitPanel();
8580
+ try {
8581
+ const response = await api(config.url, { method: "POST", body: config.body, tabId: card.tabId });
8582
+ if (!response.ok) throw new Error([response.error, response.hint].filter(Boolean).join("\n") || `Git ${action} failed`);
8583
+ addEvent(config.past, "success");
8584
+ await loadGitPanelRepository(card, { force: true });
8585
+ requestGitFooterWebuiPayload({ tabId: card.tabId }, { force: true });
8586
+ } catch (error) {
8587
+ addEvent(error.message || String(error), "error");
8588
+ const snapshot = gitPanelSnapshot(card.root);
8589
+ gitPanelState.repositories.set(card.root, { ...snapshot, error: error.message || String(error), loading: false });
8590
+ } finally {
8591
+ gitPanelState.busy.delete(busyKey);
8592
+ renderGitPanel();
8593
+ }
8594
+ }
8595
+
8596
+ function renderGitPanelFolder(node, card, category, depth = 0) {
8597
+ const details = make("details", "git-side-panel-folder");
8598
+ const folderKey = `${card.root}\u0000${category}\u0000${node.path}`;
8599
+ const defaultOpen = true;
8600
+ details.open = gitPanelState.openFolders.has(folderKey) ? gitPanelState.openFolders.get(folderKey) : defaultOpen;
8601
+ details.addEventListener("toggle", () => {
8602
+ if (details.open === defaultOpen) gitPanelState.openFolders.delete(folderKey);
8603
+ else gitPanelState.openFolders.set(folderKey, details.open);
8604
+ });
8605
+ const summary = make("summary", "git-side-panel-folder-summary");
8606
+ summary.title = `${node.path} · Right-click for Git actions`;
8607
+ const chevron = make("span", "git-side-panel-folder-chevron", "›");
8608
+ chevron.setAttribute("aria-hidden", "true");
8609
+ summary.append(chevron, make("span", "git-side-panel-folder-name", node.name));
8610
+ const folderEntries = [];
8611
+ const collect = (current) => {
8612
+ folderEntries.push(...current.files);
8613
+ for (const child of current.folders.values()) collect(child);
8614
+ };
8615
+ collect(node);
8616
+ summary.append(make("span", "git-side-panel-folder-count", String(folderEntries.length)));
8617
+ bindGitPanelContextMenu(summary, { card, category, kind: "folder", path: node.path });
8618
+ details.append(summary);
8619
+ const body = make("div", "git-side-panel-folder-body");
8620
+ for (const child of [...node.folders.values()].sort((a, b) => a.name.localeCompare(b.name))) body.append(renderGitPanelFolder(child, card, category, depth + 1));
8621
+ for (const file of [...node.files].sort((a, b) => a.name.localeCompare(b.name))) body.append(renderGitPanelFile(file, card, category));
8622
+ details.append(body);
8623
+ return details;
8624
+ }
8625
+
8626
+ function renderGitPanelFile(entry, card, category) {
8627
+ const row = make("div", `git-side-panel-file ${category}`);
8628
+ const fullPath = entry.oldPath ? `${entry.oldPath} → ${entry.path}` : entry.path;
8629
+ row.title = `${fullPath} · Right-click for Git actions`;
8630
+ row.tabIndex = 0;
8631
+ row.setAttribute("aria-label", `${entry.name || entry.path}, ${gitPanelStatsText(entry, category) || "no line statistics"}`);
8632
+ const status = make("span", "git-side-panel-file-status", entry.status?.trim() || (entry.untracked ? "?" : "•"));
8633
+ const name = make("span", "git-side-panel-file-name", entry.name || entry.path);
8634
+ const statsText = gitPanelStatsText(entry, category);
8635
+ const stats = make("span", "git-side-panel-file-stats", statsText);
8636
+ stats.hidden = !statsText;
8637
+ bindGitPanelContextMenu(row, { card, category, kind: "file", path: entry.path });
8638
+ row.append(status, name, stats);
8639
+ return row;
8640
+ }
8641
+
8642
+ function renderGitPanelTreeSection(label, category, entries, card) {
8643
+ if (!entries.length) return null;
8644
+ const section = make("section", `git-side-panel-tree-section ${category}`);
8645
+ const heading = make("div", "git-side-panel-tree-heading");
8646
+ heading.append(make("strong", undefined, label), make("span", undefined, String(entries.length)));
8647
+ section.append(heading);
8648
+ const tree = gitPanelTree(entries);
8649
+ const body = make("div", "git-side-panel-tree", undefined);
8650
+ body.setAttribute("aria-label", `${label} files`);
8651
+ for (const folder of [...tree.folders.values()].sort((a, b) => a.name.localeCompare(b.name))) body.append(renderGitPanelFolder(folder, card, category));
8652
+ for (const file of [...tree.files].sort((a, b) => a.name.localeCompare(b.name))) body.append(renderGitPanelFile(file, card, category));
8653
+ section.append(body);
8654
+ return section;
8655
+ }
8656
+
8657
+ function renderGitPanelChanges(card, data) {
8658
+ const wrapper = make("div", "git-side-panel-changes");
8659
+ const changes = Array.isArray(data?.changes) ? data.changes : [];
8660
+ const categories = [
8661
+ ["Conflicts", "conflicted", changes.filter((entry) => entry.conflicted)],
8662
+ ["Staged", "staged", changes.filter((entry) => entry.staged && !entry.conflicted)],
8663
+ ["Changes", "changes", changes.filter((entry) => entry.unstaged && !entry.untracked && !entry.conflicted)],
8664
+ ["Untracked", "untracked", changes.filter((entry) => entry.untracked)],
8665
+ ];
8666
+ for (const [label, category, entries] of categories) {
8667
+ const section = renderGitPanelTreeSection(label, category, entries, card);
8668
+ if (section) wrapper.append(section);
8669
+ }
8670
+ if (!changes.length) wrapper.append(make("p", "git-side-panel-empty success", "Working tree clean."));
8671
+ return wrapper;
8672
+ }
8673
+
8674
+ function gitPanelHistoryDate(value) {
8675
+ const date = new Date(value || "");
8676
+ return Number.isNaN(date.getTime()) ? String(value || "") : date.toLocaleString();
8677
+ }
8678
+
8679
+ function renderGitPanelHistory(card, data) {
8680
+ const wrapper = make("div", "git-side-panel-history");
8681
+ const history = Array.isArray(data?.history) ? data.history : [];
8682
+ if (!history.length) {
8683
+ wrapper.append(make("p", "git-side-panel-empty", "No commits yet."));
8684
+ return wrapper;
8685
+ }
8686
+ for (const commit of history) {
8687
+ const button = make("button", "git-side-panel-commit");
8688
+ button.type = "button";
8689
+ button.title = `View commit ${commit.hash}`;
8690
+ button.append(
8691
+ make("code", "git-side-panel-commit-hash", commit.shortHash || String(commit.hash || "").slice(0, 12)),
8692
+ make("span", "git-side-panel-commit-subject", commit.subject || "(no subject)"),
8693
+ make("span", "git-side-panel-commit-meta", [commit.author, gitPanelHistoryDate(commit.authoredAt)].filter(Boolean).join(" · ")),
8694
+ );
8695
+ button.addEventListener("click", () => openGitCommitDialog(card.tabId, commit));
8696
+ wrapper.append(button);
8697
+ }
8698
+ return wrapper;
8699
+ }
8700
+
8701
+ function renderGitPanelRepositoryContent(card, snapshot) {
8702
+ const content = make("div", "git-side-panel-repository-content");
8703
+ if (snapshot?.error) content.append(make("p", "git-side-panel-error", snapshot.error));
8704
+ if (snapshot?.loading && !snapshot?.data) {
8705
+ content.append(make("p", "git-side-panel-empty", "Loading local Git status and history…"));
8706
+ return content;
8707
+ }
8708
+ const data = snapshot?.data;
8709
+ if (!data) {
8710
+ content.append(make("p", "git-side-panel-empty", "Expand this repository to load Git status."));
8711
+ return content;
8712
+ }
8713
+ const tabs = make("div", "git-side-panel-tabs");
8714
+ tabs.setAttribute("role", "tablist");
8715
+ tabs.setAttribute("aria-label", `${gitPanelRootLabel(card.root)} repository view`);
8716
+ const views = ["changes", "history"];
8717
+ const activeView = gitPanelState.activeViews.get(card.root) || "changes";
8718
+ for (const view of views) {
8719
+ const label = view === "changes" ? `Changes (${gitPanelChangeCount(data)})` : `History (${data.history?.length || 0})`;
8720
+ const button = make("button", "git-side-panel-tab", label);
8721
+ button.id = `git-side-panel-${view}-tab`;
8722
+ button.type = "button";
8723
+ button.setAttribute("role", "tab");
8724
+ button.setAttribute("aria-controls", `git-side-panel-${view}-panel`);
8725
+ button.setAttribute("aria-selected", activeView === view ? "true" : "false");
8726
+ button.tabIndex = activeView === view ? 0 : -1;
8727
+ button.addEventListener("click", () => {
8728
+ gitPanelState.activeViews.set(card.root, view);
8729
+ renderGitPanel();
8730
+ });
8731
+ tabs.append(button);
8732
+ }
8733
+ tabs.addEventListener("keydown", (event) => {
8734
+ const currentIndex = views.indexOf(gitPanelState.activeViews.get(card.root) || "changes");
8735
+ let nextIndex = -1;
8736
+ if (event.key === "ArrowRight") nextIndex = (currentIndex + 1) % views.length;
8737
+ else if (event.key === "ArrowLeft") nextIndex = (currentIndex - 1 + views.length) % views.length;
8738
+ else if (event.key === "Home") nextIndex = 0;
8739
+ else if (event.key === "End") nextIndex = views.length - 1;
8740
+ if (nextIndex < 0) return;
8741
+ event.preventDefault();
8742
+ const nextView = views[nextIndex];
8743
+ gitPanelState.activeViews.set(card.root, nextView);
8744
+ renderGitPanel();
8745
+ queueMicrotask(() => document.getElementById(`git-side-panel-${nextView}-tab`)?.focus({ preventScroll: true }));
8746
+ });
8747
+ const meta = make("div", "git-side-panel-repository-meta");
8748
+ meta.append(
8749
+ make("strong", undefined, data.branch || "detached"),
8750
+ make("span", undefined, snapshot.loading ? "Refreshing…" : `Updated ${gitPanelHistoryDate(data.generatedAt)}`),
8751
+ );
8752
+ const changesPanel = renderGitPanelChanges(card, data);
8753
+ changesPanel.id = "git-side-panel-changes-panel";
8754
+ changesPanel.setAttribute("role", "tabpanel");
8755
+ changesPanel.setAttribute("aria-labelledby", "git-side-panel-changes-tab");
8756
+ changesPanel.hidden = activeView !== "changes";
8757
+ const historyPanel = renderGitPanelHistory(card, data);
8758
+ historyPanel.id = "git-side-panel-history-panel";
8759
+ historyPanel.setAttribute("role", "tabpanel");
8760
+ historyPanel.setAttribute("aria-labelledby", "git-side-panel-history-tab");
8761
+ historyPanel.hidden = activeView !== "history";
8762
+ content.append(tabs, meta, changesPanel, historyPanel);
8763
+ return content;
8764
+ }
8765
+
8766
+ function renderGitPanelRepositoryCard(card) {
8767
+ const discovery = card.discovery;
8768
+ if (!card.root) {
8769
+ const row = make("div", `git-side-panel-repository unavailable${discovery?.loading ? " loading" : ""}`);
8770
+ row.append(
8771
+ make("strong", undefined, gitPanelRootLabel(card.cwd, card.tabTitle)),
8772
+ make("span", "git-side-panel-repository-path", card.cwd),
8773
+ make("span", "git-side-panel-repository-state", discovery?.loading ? "Discovering repository…" : discovery?.error || "Waiting for repository discovery…"),
8774
+ );
8775
+ return row;
8776
+ }
8777
+ const snapshot = gitPanelSnapshot(card.root);
8778
+ const expanded = gitPanelState.expandedCardKey === card.key;
8779
+ const section = make("section", `git-side-panel-repository${expanded ? " expanded" : ""}`);
8780
+ const button = make("button", "git-side-panel-repository-toggle");
8781
+ button.type = "button";
8782
+ button.setAttribute("aria-expanded", expanded ? "true" : "false");
8783
+ button.title = `${expanded ? "Collapse" : "Expand"} ${card.root} · Right-click for repository actions`;
8784
+ const count = gitPanelChangeCount(snapshot?.data);
8785
+ button.append(
8786
+ make("span", "git-side-panel-repository-chevron", "›"),
8787
+ make("span", "git-side-panel-repository-copy", undefined),
8788
+ make("span", "git-side-panel-repository-count", String(count)),
8789
+ );
8790
+ const copy = button.querySelector(".git-side-panel-repository-copy");
8791
+ copy.append(make("strong", undefined, gitPanelRootLabel(card.root)), make("span", undefined, card.root));
8792
+ button.addEventListener("click", () => toggleGitPanelRepository(card));
8793
+ bindGitPanelContextMenu(button, { card, kind: "repository", path: card.root });
8794
+ section.append(button);
8795
+ if (expanded) section.append(renderGitPanelRepositoryContent(card, snapshot));
8796
+ return section;
8797
+ }
8798
+
8799
+ function renderGitPanel() {
8800
+ if (!elements.gitPanelGroups || !gitPanelSectionExpanded()) return;
8801
+ if (gitPanelContextMenuState && !elements.gitPanelContextMenu?.hidden) return;
8802
+ const groups = gitPanelTerminalGroups();
8803
+ const candidates = gitPanelCandidates(groups);
8804
+ const cards = gitPanelRepositoryCards(groups);
8805
+ const liveCandidateKeys = new Set(candidates.map((candidate) => candidate.key));
8806
+ const liveRoots = new Set(cards.map((card) => card.root).filter(Boolean));
8807
+ for (const key of [...gitPanelState.discovery.keys()]) if (!liveCandidateKeys.has(key)) gitPanelState.discovery.delete(key);
8808
+ for (const key of [...gitPanelState.activeViews.keys()]) if (!liveRoots.has(key)) gitPanelState.activeViews.delete(key);
8809
+ for (const key of [...gitPanelState.repositories.keys()]) if (!liveRoots.has(key)) gitPanelState.repositories.delete(key);
8810
+ for (const key of [...gitPanelState.openFolders.keys()]) if (!liveRoots.has(key.split("\u0000", 1)[0])) gitPanelState.openFolders.delete(key);
8811
+ const liveCardKeys = new Set(cards.filter((card) => card.root).map((card) => card.key));
8812
+ if (gitPanelState.expandedCardKey && !liveCardKeys.has(gitPanelState.expandedCardKey)) gitPanelState.expandedCardKey = "";
8813
+ closeGitPanelContextMenu({ returnFocus: false });
8814
+ const repositoryCount = cards.filter((card) => card.root).length;
8815
+ const discovering = [...gitPanelState.discovery.values()].some((entry) => entry.loading);
8816
+ const signature = JSON.stringify({
8817
+ expandedCardKey: gitPanelState.expandedCardKey,
8818
+ groups: groups.map((group) => [group.key, group.cwd, group.title, group.detail]),
8819
+ candidates: candidates.map((candidate) => {
8820
+ const discovery = gitPanelState.discovery.get(candidate.key);
8821
+ return [candidate.key, candidate.cwd, candidate.tabId, candidate.tabTitle, discovery?.root || "", !!discovery?.loading, discovery?.error || ""];
8822
+ }),
8823
+ cards: cards.map((card) => {
8824
+ const snapshot = gitPanelSnapshot(card.root);
8825
+ const data = snapshot?.data;
8826
+ return [card.key, card.root, card.cwd, card.tabId, snapshot?.loadedAt || 0, !!snapshot?.loading, snapshot?.error || "", gitPanelChangeCount(data), data?.history?.length || 0, data?.branch || "", data?.generatedAt || "", gitPanelState.activeViews.get(card.root) || "changes"];
8827
+ }),
8828
+ repositoryCount,
8829
+ discovering,
8830
+ });
8831
+ if (signature === gitPanelRenderSignature && elements.gitPanelGroups.childElementCount === cards.length) {
8832
+ ensureGitPanelRepositoriesDiscovered();
8833
+ ensureGitPanelVisibleRepositoriesFresh(cards);
8834
+ return;
8835
+ }
8836
+ gitPanelRenderSignature = signature;
8837
+ elements.gitPanelGroups.replaceChildren(...cards.map(renderGitPanelRepositoryCard));
8838
+ if (elements.gitPanelCountBadge) {
8839
+ elements.gitPanelCountBadge.textContent = String(repositoryCount);
8840
+ elements.gitPanelCountBadge.hidden = repositoryCount === 0;
8841
+ }
8842
+ if (elements.gitPanelStatus) {
8843
+ elements.gitPanelStatus.textContent = !groups.length
8844
+ ? "No terminal tabs are open."
8845
+ : discovering
8846
+ ? "Discovering repositories…"
8847
+ : `${repositoryCount} Git ${repositoryCount === 1 ? "repository" : "repositories"} · Right-click for actions`;
8848
+ }
8849
+ ensureGitPanelRepositoriesDiscovered();
8850
+ ensureGitPanelVisibleRepositoriesFresh(cards);
8851
+ }
8852
+
8092
8853
  function tabAppRunnerRun(tab) {
8093
8854
  if (!tab?.id) return null;
8094
8855
  const cached = appRunnerDataByTab.get(tab.id);
@@ -8428,6 +9189,7 @@ function renderTabs() {
8428
9189
  updateDocumentTitle();
8429
9190
  renderWorkspaceDashboard();
8430
9191
  renderContextMeter();
9192
+ renderGitPanel();
8431
9193
  if (elements.commandPaletteDialog?.open) renderCommandPalette({ preserveScroll: true });
8432
9194
  syncTabPolling();
8433
9195
  }
@@ -9426,7 +10188,7 @@ async function toggleFooterAutoCompaction(tabContext = activeTabContext()) {
9426
10188
  }
9427
10189
  }
9428
10190
 
9429
- function scheduleGitFooterPiCalibrationRefresh(tabContext, delays = [600, 1600]) {
10191
+ function scheduleGitFooterPiCalibrationRefresh(tabContext, delays = [5000, 14000, 30000]) {
9430
10192
  for (const delayMs of delays) {
9431
10193
  setTimeout(() => {
9432
10194
  if (isCurrentTabContext(tabContext)) requestGitFooterWebuiPayload(tabContext, { force: true });
@@ -9434,7 +10196,8 @@ function scheduleGitFooterPiCalibrationRefresh(tabContext, delays = [600, 1600])
9434
10196
  }
9435
10197
  }
9436
10198
 
9437
- async function runGitFooterPiCalibration(mode = "current", tabContext = activeTabContext()) {
10199
+
10200
+ async function runGitFooterPiCalibration(tabContext = activeTabContext()) {
9438
10201
  if (!tabContext.tabId) return;
9439
10202
  if (gitFooterPiCalibrationInFlightByTab.has(tabContext.tabId)) return;
9440
10203
  if (currentState?.isStreaming || currentState?.isCompacting) {
@@ -9447,16 +10210,14 @@ async function runGitFooterPiCalibration(mode = "current", tabContext = activeTa
9447
10210
  addEvent("PI calibration unavailable: /calibrate is not loaded in this Pi tab.", "warn");
9448
10211
  return;
9449
10212
  }
9450
- if (mode === "probe" && !(await appConfirmText("Start an isolated PI calibration probe? This sends one tiny model request and may incur provider token usage.", { affected: "Provider token allowance and this tab's calibration result", confirmLabel: "Start probe", danger: false }))) return;
9451
10213
 
9452
- const command = mode === "probe" ? `/${commandName}` : `/${commandName} current`;
9453
10214
  gitFooterPiCalibrationInFlightByTab.add(tabContext.tabId);
9454
10215
  renderFooter();
9455
10216
  try {
9456
- await sendPrompt("prompt", command, { targetTabId: tabContext.tabId, throwOnError: true });
10217
+ await sendPrompt("prompt", `/${commandName}`, { targetTabId: tabContext.tabId, throwOnError: true });
10218
+ scheduleGitFooterPiCalibrationRefresh(tabContext);
9457
10219
  if (!isCurrentTabContext(tabContext)) return;
9458
- addEvent(mode === "probe" ? "PI calibration probe started; refreshing git footer value after it records…" : "PI calibration requested; refreshing git footer value…", "info");
9459
- scheduleGitFooterPiCalibrationRefresh(tabContext, mode === "probe" ? [5000, 14000] : [600, 1600]);
10220
+ addEvent("PI calibration started in the background; refreshing the footer value after it records…", "info");
9460
10221
  } catch (error) {
9461
10222
  if (isCurrentTabContext(tabContext)) addEvent(error.message || String(error), "error");
9462
10223
  } finally {
@@ -9466,16 +10227,16 @@ async function runGitFooterPiCalibration(mode = "current", tabContext = activeTa
9466
10227
  }
9467
10228
 
9468
10229
  function applyGitFooterPiCalibrationOptions(chip, options) {
9469
- if (chip?.key !== "pi" || !FOOTER_PAYLOAD_ACTIONS.has(chip?.action)) return "";
10230
+ if (chip?.key !== "pi") return "";
9470
10231
  const tabContext = activeTabContext();
9471
10232
  const busy = !!tabContext.tabId && gitFooterPiCalibrationInFlightByTab.has(tabContext.tabId);
9472
- const mode = chip.action === "calibrate-probe" ? "probe" : "current";
9473
- options.onClick = () => runGitFooterPiCalibration(mode);
10233
+ options.onClick = () => {
10234
+ void runGitFooterPiCalibration();
10235
+ };
9474
10236
  if (busy) options.ariaBusy = true;
9475
- if (busy) return "Calibrating PI estimate and refreshing this value…";
9476
- return mode === "probe"
9477
- ? "Click to start an isolated PI calibration probe, then refresh this value."
9478
- : "Click to calibrate this uncalibrated PI estimate from the current session, then refresh this value.";
10237
+ return busy
10238
+ ? "Calibrating PI estimate in the background and refreshing this value…"
10239
+ : "Click to run /calibrate in the background and refresh this PI token count.";
9479
10240
  }
9480
10241
 
9481
10242
  function applyGitFooterContextToggleOptions(chip, options) {
@@ -9704,6 +10465,43 @@ function applyFooterContextUsage(node, contextUsage) {
9704
10465
  return node;
9705
10466
  }
9706
10467
 
10468
+ const FOOTER_MIDDLE_TRUNCATION_END_CHARS = 16;
10469
+ const FOOTER_MIDDLE_TRUNCATION_MIN_START_CHARS = 6;
10470
+
10471
+ function splitMiddleTruncationText(value, endChars = FOOTER_MIDDLE_TRUNCATION_END_CHARS) {
10472
+ const characters = Array.from(String(value ?? ""));
10473
+ const minimumSuffixLength = Math.max(0, Math.min(Math.trunc(Number(endChars) || 0), characters.length));
10474
+ if (!minimumSuffixLength) return { start: characters.join(""), end: "" };
10475
+ let componentEnd = characters.length - 1;
10476
+ while (componentEnd >= 0 && (characters[componentEnd] === "/" || characters[componentEnd] === "\\")) componentEnd -= 1;
10477
+ let separatorIndex = -1;
10478
+ for (let index = componentEnd; index >= 0; index -= 1) {
10479
+ if (characters[index] === "/" || characters[index] === "\\") {
10480
+ separatorIndex = index;
10481
+ break;
10482
+ }
10483
+ }
10484
+ const componentSuffixLength = separatorIndex >= 0 ? characters.length - separatorIndex : 0;
10485
+ const suffixLength = Math.min(characters.length, Math.max(minimumSuffixLength, componentSuffixLength));
10486
+ if (!suffixLength || characters.length <= suffixLength + FOOTER_MIDDLE_TRUNCATION_MIN_START_CHARS) return { start: characters.join(""), end: "" };
10487
+ return { start: characters.slice(0, -suffixLength).join(""), end: characters.slice(-suffixLength).join("") };
10488
+ }
10489
+
10490
+ function setMiddleTruncatedText(node, value, endChars = FOOTER_MIDDLE_TRUNCATION_END_CHARS) {
10491
+ const parts = splitMiddleTruncationText(value, endChars);
10492
+ if (!parts.end) {
10493
+ node.classList.remove("middle-truncate-value");
10494
+ node.textContent = parts.start;
10495
+ return node;
10496
+ }
10497
+ node.classList.add("middle-truncate-value");
10498
+ node.replaceChildren(
10499
+ make("span", "middle-truncate-start", parts.start),
10500
+ make("span", "middle-truncate-end", parts.end),
10501
+ );
10502
+ return node;
10503
+ }
10504
+
9707
10505
  function footerMeta(label, value, className = "", options = {}) {
9708
10506
  const isAction = typeof options.onClick === "function";
9709
10507
  const node = make(isAction ? "button" : "span", ["footer-meta", className, isAction ? "footer-meta-action" : ""].filter(Boolean).join(" "));
@@ -9717,7 +10515,10 @@ function footerMeta(label, value, className = "", options = {}) {
9717
10515
  node.setAttribute("aria-disabled", "true");
9718
10516
  }
9719
10517
  }
9720
- node.append(make("span", "footer-meta-label", label), make("span", "footer-meta-value", value));
10518
+ const valueNode = make("span", "footer-meta-value");
10519
+ if (options.middleTruncate) setMiddleTruncatedText(valueNode, value);
10520
+ else valueNode.textContent = String(value ?? "");
10521
+ node.append(make("span", "footer-meta-label", label), valueNode);
9721
10522
  return applyFooterTooltip(node, options.title || `${label}: ${value}`, { align: options.tooltipAlign });
9722
10523
  }
9723
10524
 
@@ -10323,7 +11124,9 @@ function gitFooterTooltipAlign(chip) {
10323
11124
  function footerTuiItem(value, className = "", options = {}) {
10324
11125
  const text = cleanStatusText(value);
10325
11126
  const isAction = typeof options.onClick === "function";
10326
- const node = make(isAction ? "button" : "span", `footer-tui-item ${className}${isAction ? " footer-tui-action" : ""}`.trim(), text);
11127
+ const node = make(isAction ? "button" : "span", `footer-tui-item ${className}${isAction ? " footer-tui-action" : ""}`.trim());
11128
+ if (options.middleTruncate) setMiddleTruncatedText(node, text);
11129
+ else node.textContent = text;
10327
11130
  if (isAction) {
10328
11131
  node.type = "button";
10329
11132
  node.addEventListener("click", options.onClick);
@@ -10340,7 +11143,8 @@ function renderTuiFooterLine({ cwd, cwdTitle, message = "", stats = [], model =
10340
11143
  line.append(footerTuiItem(cwd || "loading…", "footer-tui-cwd", tab ? {
10341
11144
  onClick: changeActiveTabCwd,
10342
11145
  title: cwdTitle || `Change cwd for ${tab.title}: ${cwd}`,
10343
- } : { title: cwdTitle }));
11146
+ middleTruncate: true,
11147
+ } : { title: cwdTitle, middleTruncate: true }));
10344
11148
  if (worktreeLabel) line.append(footerTuiItem(worktreeLabel, "footer-tui-worktree", { title: workspace?.worktreePath || worktreeLabel }));
10345
11149
  if (message) line.append(footerTuiItem(message, "footer-tui-status"));
10346
11150
  for (const stat of stats.filter(Boolean)) line.append(footerTuiItem(stat, "footer-tui-stat"));
@@ -10531,10 +11335,10 @@ function renderGitFooterPayloadMeta(chip, tab, payload) {
10531
11335
  options.disabled = inFlight;
10532
11336
  action = inFlight ? "Pushing local commits to the configured remote." : "Click to push local commits to the configured remote.";
10533
11337
  } else if (chip.key === "changes" && visible("webui-changes-modal")) {
10534
- options.onClick = openGitChangesDialog;
11338
+ options.onClick = () => openGitChangesDialog(tab?.id || activeTabId);
10535
11339
  action = "Click to view the current git diff.";
10536
11340
  } else if (chip.key === "git-state" && visible("webui-changes-modal")) {
10537
- options.onClick = openGitChangesDialog;
11341
+ options.onClick = () => openGitChangesDialog(tab?.id || activeTabId);
10538
11342
  action = "Click to open the conflicts and operation panel with continue/abort actions.";
10539
11343
  } else if (chip.key === "git-extra" && visible("webui-git-tools-modal")) {
10540
11344
  const toolsSection = gitToolsSectionForExtraChip(chip.value);
@@ -10550,6 +11354,7 @@ function renderGitFooterPayloadMeta(chip, tab, payload) {
10550
11354
  action = (visible("webui-context-auto-compaction") ? applyGitFooterContextToggleOptions(chip, options) : "") || action;
10551
11355
  options.title = gitFooterPayloadTooltip(chip, { action });
10552
11356
  options.tooltipAlign = gitFooterTooltipAlign(chip);
11357
+ options.middleTruncate = chip.key === "cwd";
10553
11358
  const node = footerMeta(chip.label, chip.value, footerMetaClassForPayload(chip), options);
10554
11359
  applyFooterChangedFilesDropdown(node, chip, payload);
10555
11360
  if (["git", "worktree"].includes(chip.key) && options.onClick && cleanFooterPayloadText(chip.value, "").toLowerCase() !== "no repo") {
@@ -10579,14 +11384,24 @@ function gitFooterPickerStateKey(payload) {
10579
11384
  const tabContext = activeTabContext();
10580
11385
  const refreshInFlight = tabContext.tabId ? gitFooterPayloadRefreshInFlightByTab.has(tabContext.tabId) : false;
10581
11386
  const syncPushInFlight = tabContext.tabId ? gitFooterSyncPushInFlightByTab.has(tabContext.tabId) : false;
11387
+ const piCalibrationInFlight = tabContext.tabId ? gitFooterPiCalibrationInFlightByTab.has(tabContext.tabId) : false;
10582
11388
  const refreshAvailable = hasLoadedRpcCommand("git-footer-refresh");
10583
- return `${footerModelPickerOpen ? 1 : 0}|${footerThinkingPickerOpen ? 1 : 0}|${footerBranchPickerOpen ? 1 : 0}|${mobileFooterExpanded ? 1 : 0}|${refreshInFlight ? 1 : 0}|${syncPushInFlight ? 1 : 0}|${refreshAvailable ? 1 : 0}|${gitFooterPayloadVisibilityKey(payload)}`;
11389
+ return `${footerModelPickerOpen ? 1 : 0}|${footerThinkingPickerOpen ? 1 : 0}|${footerBranchPickerOpen ? 1 : 0}|${mobileFooterExpanded ? 1 : 0}|${refreshInFlight ? 1 : 0}|${syncPushInFlight ? 1 : 0}|${piCalibrationInFlight ? 1 : 0}|${refreshAvailable ? 1 : 0}|${gitFooterPayloadVisibilityKey(payload)}`;
10584
11390
  }
10585
11391
 
10586
11392
  function updateGitFooterChipNodeValue(node, chip, valueSelector) {
10587
11393
  if (!node) return;
10588
11394
  const valueNode = node.querySelector(valueSelector);
10589
- if (valueNode && valueNode.textContent !== String(chip.value ?? "")) valueNode.textContent = String(chip.value ?? "");
11395
+ const nextValue = String(chip.value ?? "");
11396
+ const middleTruncate = chip.key === "cwd";
11397
+ const middleTruncateActive = middleTruncate && !!splitMiddleTruncationText(nextValue).end;
11398
+ if (valueNode && (valueNode.textContent !== nextValue || valueNode.classList.contains("middle-truncate-value") !== middleTruncateActive)) {
11399
+ if (middleTruncate) setMiddleTruncatedText(valueNode, nextValue);
11400
+ else {
11401
+ valueNode.classList.remove("middle-truncate-value");
11402
+ valueNode.textContent = nextValue;
11403
+ }
11404
+ }
10590
11405
  if (chip.contextUsage) applyFooterContextUsage(node, chip.contextUsage);
10591
11406
  }
10592
11407
 
@@ -10952,7 +11767,7 @@ function gitChangesFileActionsFor(sectionKey, path) {
10952
11767
  ...gitChangesCommonFileActions(path),
10953
11768
  ];
10954
11769
  }
10955
- if (sectionKey === "incoming") return [{ label: "Copy path", title: "Copy the repo-relative path", onClick: () => copyGitPathToClipboard(path) }];
11770
+ if (sectionKey === "incoming" || sectionKey === "commit") return [{ label: "Copy path", title: "Copy the repo-relative path", onClick: () => copyGitPathToClipboard(path) }];
10956
11771
  return [];
10957
11772
  }
10958
11773
 
@@ -11336,28 +12151,34 @@ function renderGitPullResultPanel(result) {
11336
12151
 
11337
12152
  function renderGitChangesDialog() {
11338
12153
  if (!elements.gitChangesDialog || !elements.gitChangesBody) return;
11339
- const { loading, pulling, fetching, error, message, pullResult, data, operation } = gitChangesState;
12154
+ const { loading, pulling, fetching, error, message, pullResult, data, operation, mode, commit } = gitChangesState;
12155
+ const commitView = mode === "commit";
11340
12156
  const busyAction = pulling || fetching;
11341
12157
  const behind = Number(data?.remote?.behind ?? data?.summary?.behind ?? 0) || 0;
11342
12158
  const diverged = data?.remote?.diverged === true;
11343
12159
  const canPull = behind > 0 && data?.remote?.canPull !== false && !diverged;
11344
- const hasOperation = Boolean(operation?.operation);
11345
- const remoteNotice = !error && data?.remote?.error ? `Incoming diff unavailable: ${data.remote.error}` : "";
11346
- if (elements.gitChangesTitle) elements.gitChangesTitle.textContent = "Git Changes";
12160
+ const hasOperation = !commitView && Boolean(operation?.operation);
12161
+ const remoteNotice = !commitView && !error && data?.remote?.error ? `Incoming diff unavailable: ${data.remote.error}` : "";
12162
+ if (elements.gitChangesTitle) elements.gitChangesTitle.textContent = commitView ? "Git Commit" : "Git Changes";
11347
12163
  if (elements.gitChangesSubtitle) {
11348
- const base = data?.root ? `${data.branch || "detached"} · ${data.root}` : "Current tab git diff";
11349
- elements.gitChangesSubtitle.textContent = data?.remote?.upstream ? `${base} · upstream ${data.remote.upstream}` : base;
12164
+ const commitData = data?.commit || commit;
12165
+ const base = commitView
12166
+ ? [commitData?.shortHash || String(commitData?.hash || "").slice(0, 12), commitData?.subject, data?.root].filter(Boolean).join(" · ") || "Commit diff"
12167
+ : data?.root ? `${data.branch || "detached"} · ${data.root}` : "Current tab git diff";
12168
+ elements.gitChangesSubtitle.textContent = !commitView && data?.remote?.upstream ? `${base} · upstream ${data.remote.upstream}` : base;
11350
12169
  }
11351
12170
  if (elements.gitChangesRefreshButton) {
11352
12171
  elements.gitChangesRefreshButton.disabled = loading || busyAction;
11353
- elements.gitChangesRefreshButton.textContent = loading ? "Refreshing…" : "Refresh";
12172
+ elements.gitChangesRefreshButton.textContent = loading ? "Refreshing…" : commitView ? "Reload" : "Refresh";
11354
12173
  }
11355
12174
  if (elements.gitChangesFetchButton) {
12175
+ elements.gitChangesFetchButton.hidden = commitView;
11356
12176
  elements.gitChangesFetchButton.disabled = loading || busyAction || !data?.root;
11357
12177
  elements.gitChangesFetchButton.textContent = fetching ? "Fetching…" : "Fetch";
11358
12178
  elements.gitChangesFetchButton.title = "Run git fetch --prune to refresh remote tracking state";
11359
12179
  }
11360
12180
  if (elements.gitChangesPullButton) {
12181
+ elements.gitChangesPullButton.hidden = commitView;
11361
12182
  elements.gitChangesPullButton.disabled = loading || busyAction || !canPull;
11362
12183
  elements.gitChangesPullButton.textContent = pulling ? "Pulling…" : behind > 0 ? `Pull ↓${behind}` : "Pull";
11363
12184
  elements.gitChangesPullButton.title = canPull
@@ -11367,7 +12188,7 @@ function renderGitChangesDialog() {
11367
12188
  : "No remote commits to pull";
11368
12189
  }
11369
12190
  if (elements.gitChangesStatus) {
11370
- const statusText = error || (pulling ? "Pulling changes…" : fetching ? "Fetching from remote…" : loading ? "Loading git diff…" : message || remoteNotice || (data ? gitChangesGeneratedLabel(data) : ""));
12191
+ const statusText = error || (pulling ? "Pulling changes…" : fetching ? "Fetching from remote…" : loading ? `Loading ${commitView ? "commit" : "git"} diff…` : message || remoteNotice || (data ? gitChangesGeneratedLabel(data) : ""));
11371
12192
  elements.gitChangesStatus.className = `git-changes-status ${error || remoteNotice ? "error" : message ? "success" : "muted"}`;
11372
12193
  elements.gitChangesStatus.textContent = statusText;
11373
12194
  elements.gitChangesStatus.hidden = !elements.gitChangesStatus.textContent;
@@ -11388,19 +12209,21 @@ function renderGitChangesDialog() {
11388
12209
  return;
11389
12210
  }
11390
12211
 
11391
- if (pullResult) body.append(renderGitPullResultPanel(pullResult));
12212
+ if (pullResult && !commitView) body.append(renderGitPullResultPanel(pullResult));
11392
12213
  if (hasOperation) {
11393
12214
  const panel = renderGitOperationPanel(operation);
11394
12215
  if (panel) body.append(panel);
11395
12216
  }
11396
- body.append(renderGitChangesOverview(data));
11397
- const fetchStateLines = gitChangesFetchStateLines();
11398
- if (fetchStateLines.length) {
11399
- const fetchNote = make("div", "git-tools-note git-fetch-state-note");
11400
- for (const line of fetchStateLines) fetchNote.append(make("div", undefined, line));
11401
- body.append(fetchNote);
12217
+ if (!commitView) {
12218
+ body.append(renderGitChangesOverview(data));
12219
+ const fetchStateLines = gitChangesFetchStateLines();
12220
+ if (fetchStateLines.length) {
12221
+ const fetchNote = make("div", "git-tools-note git-fetch-state-note");
12222
+ for (const line of fetchStateLines) fetchNote.append(make("div", undefined, line));
12223
+ body.append(fetchNote);
12224
+ }
12225
+ if (diverged && !hasOperation) body.append(renderGitDivergedBar(data));
11402
12226
  }
11403
- if (diverged && !hasOperation) body.append(renderGitDivergedBar(data));
11404
12227
  const parsedSections = (Array.isArray(data.sections) ? data.sections : [])
11405
12228
  .map((section) => ({ section, files: parseGitUnifiedDiff(section.diff || "") }))
11406
12229
  .filter((entry) => entry.files.length > 0);
@@ -11417,14 +12240,14 @@ function renderGitChangesDialog() {
11417
12240
  const emptyMessage = behind > 0 ? "No textual incoming diff was available for the remote commits." : "Working tree is clean. No staged, unstaged, untracked, or incoming diff.";
11418
12241
  body.append(make("div", "git-changes-empty success", emptyMessage));
11419
12242
  }
11420
- body.append(renderGitToolsSection());
12243
+ if (!commitView) body.append(renderGitToolsSection());
11421
12244
  if (hasVisibleFiles) requestAnimationFrame(updateGitChangesCurrentFileHeader);
11422
12245
  }
11423
12246
 
11424
12247
  async function loadGitChangesDialog(tabContext = activeTabContext()) {
11425
12248
  const requestSerial = ++gitChangesRequestSerial;
11426
12249
  gitChangesUntrackedContentRequests.clear();
11427
- gitChangesState = { ...gitChangesState, loading: true, error: "", errorCode: "", errorHint: "", message: "", pullResult: null, tabId: tabContext.tabId || activeTabId };
12250
+ gitChangesState = { ...gitChangesState, loading: true, error: "", errorCode: "", errorHint: "", message: "", pullResult: null, tabId: tabContext.tabId || activeTabId, mode: "changes", commit: null };
11428
12251
  renderGitChangesDialog();
11429
12252
  try {
11430
12253
  const [response, operationResponse] = await Promise.all([
@@ -11454,11 +12277,11 @@ async function loadGitChangesDialog(tabContext = activeTabContext()) {
11454
12277
  renderGitChangesDialog();
11455
12278
  }
11456
12279
 
11457
- function openGitChangesDialog() {
12280
+ function openGitChangesDialog(requestedTabId = activeTabId) {
11458
12281
  if (!elements.gitChangesDialog) return;
11459
12282
  hideFooterTooltip();
11460
- const tabContext = activeTabContext();
11461
- const tabId = tabContext.tabId || activeTabId;
12283
+ const tabId = typeof requestedTabId === "string" && requestedTabId ? requestedTabId : activeTabId;
12284
+ const tabContext = activeTabContext(tabId);
11462
12285
  if (gitToolsState.tabId !== tabId) resetGitToolsState(tabId);
11463
12286
  gitChangesState = {
11464
12287
  ...gitChangesState,
@@ -11474,15 +12297,47 @@ function openGitChangesDialog() {
11474
12297
  operation: gitChangesState.tabId === tabId ? gitChangesState.operation : null,
11475
12298
  lastFetch: gitChangesState.tabId === tabId ? gitChangesState.lastFetch : null,
11476
12299
  tabId,
12300
+ mode: "changes",
12301
+ commit: null,
11477
12302
  };
11478
12303
  renderGitChangesDialog();
11479
12304
  if (!elements.gitChangesDialog.open) elements.gitChangesDialog.showModal();
11480
12305
  loadGitChangesDialog(tabContext).catch((error) => addEvent(error.message || String(error), "error"));
11481
12306
  }
11482
12307
 
12308
+ async function loadGitCommitDialog(tabId, commit) {
12309
+ const requestSerial = ++gitChangesRequestSerial;
12310
+ const hash = String(commit?.hash || "");
12311
+ gitChangesState = { ...gitChangesState, loading: true, error: "", message: "", data: null, operation: null, tabId, mode: "commit", commit };
12312
+ renderGitChangesDialog();
12313
+ try {
12314
+ const response = await api(`/api/git-commit?hash=${encodeURIComponent(hash)}`, { tabId });
12315
+ if (requestSerial !== gitChangesRequestSerial) return;
12316
+ if (!response.ok) throw new Error(response.error || "Failed to load Git commit");
12317
+ gitChangesState = { ...gitChangesState, loading: false, error: "", data: response.data || null, tabId, mode: "commit", commit: response.data?.commit || commit };
12318
+ } catch (error) {
12319
+ if (requestSerial !== gitChangesRequestSerial) return;
12320
+ gitChangesState = { ...gitChangesState, loading: false, error: error.message || String(error), tabId, mode: "commit", commit };
12321
+ }
12322
+ renderGitChangesDialog();
12323
+ }
12324
+
12325
+ function openGitCommitDialog(tabId, commit) {
12326
+ if (!elements.gitChangesDialog || !tabId || !commit?.hash) return;
12327
+ hideFooterTooltip();
12328
+ gitChangesState = { ...gitChangesState, loading: true, pulling: false, fetching: false, error: "", message: "", data: null, operation: null, tabId, mode: "commit", commit };
12329
+ renderGitChangesDialog();
12330
+ if (!elements.gitChangesDialog.open) elements.gitChangesDialog.showModal();
12331
+ loadGitCommitDialog(tabId, commit).catch((error) => addEvent(error.message || String(error), "error"));
12332
+ }
12333
+
11483
12334
  function refreshGitChangesDialog() {
11484
- const tabContext = { tabId: gitChangesState.tabId || activeTabId };
11485
- loadGitChangesDialog(tabContext).catch((error) => addEvent(error.message || String(error), "error"));
12335
+ const tabId = gitChangesState.tabId || activeTabId;
12336
+ if (gitChangesState.mode === "commit" && gitChangesState.commit?.hash) {
12337
+ loadGitCommitDialog(tabId, gitChangesState.commit).catch((error) => addEvent(error.message || String(error), "error"));
12338
+ return;
12339
+ }
12340
+ loadGitChangesDialog({ tabId }).catch((error) => addEvent(error.message || String(error), "error"));
11486
12341
  }
11487
12342
 
11488
12343
  async function pullGitChangesDialog() {
@@ -12413,20 +13268,29 @@ async function requestManualCompaction({ triggerButton = null } = {}) {
12413
13268
  }
12414
13269
  }
12415
13270
 
13271
+ let contextMeterSignature = null;
13272
+
12416
13273
  function renderContextMeter() {
12417
13274
  if (deferUiRenderDuringPointerActivation("context-meter", renderContextMeter)) return;
12418
13275
  const root = elements.contextMeterBar;
12419
13276
  if (!root) return;
12420
13277
  const tab = activeTab();
12421
- if (!tab) {
12422
- root.hidden = true;
12423
- root.replaceChildren();
12424
- return;
12425
- }
12426
- root.hidden = false;
12427
13278
  const snapshot = contextUsageSnapshot();
12428
- if (!snapshot || typeof snapshot.percent !== "number" || snapshot.percent <= 50) {
12429
- root.hidden = true;
13279
+ const visible = Boolean(tab && snapshot && typeof snapshot.percent === "number" && snapshot.percent > 50);
13280
+ const autoCompactionEnabled = footerAutoCompactionEnabled();
13281
+ const signature = JSON.stringify({
13282
+ tabId: tab?.id || "",
13283
+ visible,
13284
+ snapshot,
13285
+ isCompacting: !!currentState?.isCompacting,
13286
+ autoCompactionEnabled,
13287
+ autoCompactionToggleInFlight: footerAutoCompactionToggleInFlight,
13288
+ theme: [currentThemeName, effectiveScheme()],
13289
+ });
13290
+ if (signature === contextMeterSignature && root.hidden === !visible && (!visible || root.childElementCount > 0)) return;
13291
+ contextMeterSignature = signature;
13292
+ root.hidden = !visible;
13293
+ if (!visible) {
12430
13294
  root.replaceChildren();
12431
13295
  return;
12432
13296
  }
@@ -12445,9 +13309,9 @@ function renderContextMeter() {
12445
13309
  compact.disabled = !!currentState?.isCompacting;
12446
13310
  compact.title = "Manually compact this tab's conversation context";
12447
13311
  compact.addEventListener("click", () => requestManualCompaction({ triggerButton: compact }));
12448
- const auto = make("button", "context-meter-auto", footerAutoCompactionEnabled() ? "Auto on" : "Auto off");
13312
+ const auto = make("button", "context-meter-auto", autoCompactionEnabled ? "Auto on" : "Auto off");
12449
13313
  auto.type = "button";
12450
- auto.setAttribute("aria-pressed", footerAutoCompactionEnabled() ? "true" : "false");
13314
+ auto.setAttribute("aria-pressed", autoCompactionEnabled ? "true" : "false");
12451
13315
  auto.disabled = footerAutoCompactionToggleInFlight;
12452
13316
  auto.title = footerAutoCompactionToggleInFlight ? "Updating auto-compaction…" : footerAutoCompactionToggleAction();
12453
13317
  auto.addEventListener("click", () => toggleFooterAutoCompaction());
@@ -12560,11 +13424,14 @@ function renderWorkspaceDashboard() {
12560
13424
  queueCount,
12561
13425
  modelLabel,
12562
13426
  modelTitle: currentState?.model ? shortModelLabel(currentState.model) : "Model loading…",
13427
+ hasModel: !!currentState?.model,
12563
13428
  thinking: currentState?.thinkingLevel || "",
12564
- context: { display: contextUsageDisplay(snapshot), detail: contextUsageDetail(snapshot), tone: contextDashboardTone(snapshot) },
13429
+ context: { snapshot, display: contextUsageDisplay(snapshot), detail: contextUsageDetail(snapshot), tone: contextDashboardTone(snapshot) },
13430
+ theme: [currentThemeName, effectiveScheme()],
12565
13431
  session: sessionSummary,
13432
+ hasSession: !!(currentState?.sessionId || currentState?.sessionName),
12566
13433
  activeTabId,
12567
- tabs: tabs.slice(0, 8).map((item) => ({ id: item.id, title: item.title, state: tabIndicator(item).state, active: item.id === activeTabId, cwd: item.cwd ? normalizeDisplayPath(item.cwd) : "" })),
13434
+ tabs: tabs.slice(0, 8).map((item) => ({ id: item.id, title: item.title, indicator: tabIndicator(item), active: item.id === activeTabId, cwd: item.cwd ? normalizeDisplayPath(item.cwd) : "" })),
12568
13435
  overflow: tabs.length > 8 ? tabs.length - 8 : 0,
12569
13436
  });
12570
13437
  if (signature === workspaceDashboardSignature && root.childElementCount > 0) return;
@@ -14427,7 +15294,7 @@ function initializeClaudeUsage() {
14427
15294
 
14428
15295
  function subagentTabsWithRunningAgents() {
14429
15296
  return (Array.isArray(latestSubagents?.tabs) ? latestSubagents.tabs : [])
14430
- .filter((tab) => Number(tab?.agentCount || 0) > 0)
15297
+ .filter((tab) => Number(tab?.agentCount || 0) > 0 || Number(tab?.gateCount || 0) > 0)
14431
15298
  .sort((a, b) => Number(a.tabIndex || 0) - Number(b.tabIndex || 0) || String(a.tabTitle || "").localeCompare(String(b.tabTitle || "")));
14432
15299
  }
14433
15300
 
@@ -14447,6 +15314,16 @@ function subagentRunElapsed(run) {
14447
15314
  return Number.isFinite(startedAt) ? formatDuration(Math.max(0, Date.now() - startedAt)) : "";
14448
15315
  }
14449
15316
 
15317
+ function subagentExecutionFacts(agent = {}) {
15318
+ const thinking = String(agent?.thinking || "").trim();
15319
+ let model = String(agent?.model || "").trim();
15320
+ const suffixIndex = model.lastIndexOf(":");
15321
+ if (thinking && suffixIndex > model.indexOf("/") && model.slice(suffixIndex + 1).toLowerCase() === thinking.toLowerCase()) {
15322
+ model = model.slice(0, suffixIndex);
15323
+ }
15324
+ return [`model ${model || "unknown"}`, `reasoning ${thinking || "unknown"}`];
15325
+ }
15326
+
14450
15327
  function subagentOverlayTranscriptMessages(data = subagentOverlayData) {
14451
15328
  const agent = data?.agent || subagentOverlaySelection?.agent || {};
14452
15329
  return (Array.isArray(agent.transcript) ? agent.transcript : [])
@@ -14580,6 +15457,7 @@ function subagentOverlayStateFacts(data = subagentOverlayData) {
14580
15457
  data?.mode || subagentOverlaySelection?.run?.mode,
14581
15458
  data?.source || subagentOverlaySelection?.run?.source,
14582
15459
  agent.nested ? "nested" : "",
15460
+ ...subagentExecutionFacts(agent),
14583
15461
  agent.currentTool ? `tool ${agent.currentTool}` : "",
14584
15462
  Number.isFinite(agent.turnCount) ? `${agent.turnCount} turns` : "",
14585
15463
  Number.isFinite(agent.toolCount) ? `${agent.toolCount} tools` : "",
@@ -14833,6 +15711,7 @@ function renderSubagentTerminalView() {
14833
15711
  view.run?.mode,
14834
15712
  view.run?.source === "foreground" ? "foreground" : "async",
14835
15713
  agent.nested ? "nested" : "",
15714
+ ...subagentExecutionFacts(agent),
14836
15715
  agent.currentTool ? `tool ${agent.currentTool}` : "",
14837
15716
  ].filter(Boolean);
14838
15717
 
@@ -15028,7 +15907,7 @@ function renderSubagentTerminalTab(view) {
15028
15907
  appendTerminalTabContent(button, {
15029
15908
  title: subagentTerminalViewTitle(view),
15030
15909
  indicator: { state: running ? "working" : "done" },
15031
- meta: `Subagent · ${view.parentTitle || "parent terminal"}`,
15910
+ meta: ["Subagent", ...subagentExecutionFacts(view.data?.agent || view.agent), view.parentTitle || "parent terminal"].join(" · "),
15032
15911
  subagent: true,
15033
15912
  });
15034
15913
  button.addEventListener("click", () => activateSubagentTerminalView(view.id));
@@ -15059,6 +15938,7 @@ function renderSubagentAgent(tab, run, agent) {
15059
15938
  agent?.nested ? "nested" : "",
15060
15939
  run?.mode && run.mode !== "single" ? run.mode : "",
15061
15940
  run?.source === "foreground" ? "foreground" : "async",
15941
+ ...subagentExecutionFacts(agent),
15062
15942
  agent?.currentTool ? `tool: ${agent.currentTool}` : "",
15063
15943
  elapsed ? `running ${elapsed}` : "",
15064
15944
  ].filter(Boolean);
@@ -15071,6 +15951,50 @@ function renderSubagentAgent(tab, run, agent) {
15071
15951
  return row;
15072
15952
  }
15073
15953
 
15954
+ function subagentGateStatusLabel(status) {
15955
+ return status === "satisfied" ? "satisfied" : status === "running" ? "running" : status === "cancelled" ? "cancelled" : "failed";
15956
+ }
15957
+
15958
+ function renderSubagentGateAttempt(attempt) {
15959
+ const row = make("div", `subagent-gate-attempt ${attempt?.status || "failed"}`);
15960
+ const marker = make("span", "subagent-gate-attempt-marker");
15961
+ marker.setAttribute("aria-hidden", "true");
15962
+ const content = make("div", "subagent-gate-attempt-content");
15963
+ const title = attempt?.label || attempt?.agent || "subagent";
15964
+ content.append(make("strong", undefined, `${title} · attempt ${attempt?.attempt || 1}/${attempt?.maxAttempts || 1}`));
15965
+ const facts = [
15966
+ attempt?.status,
15967
+ attempt?.phase ? `phase ${attempt.phase}` : "",
15968
+ attempt?.provider ? `provider ${attempt.provider}` : "provider unknown",
15969
+ attempt?.model ? `model ${attempt.model}` : "model unknown",
15970
+ attempt?.retrySafety,
15971
+ attempt?.failureKind ? `failure ${attempt.failureKind}` : "",
15972
+ attempt?.runId ? `run ${attempt.runId}` : "",
15973
+ ].filter(Boolean);
15974
+ content.append(make("span", "subagent-gate-attempt-meta", facts.join(" · ")));
15975
+ if (attempt?.error) content.append(make("span", "subagent-gate-attempt-error", attempt.error));
15976
+ row.append(marker, content);
15977
+ return row;
15978
+ }
15979
+
15980
+ function renderSubagentGate(gate) {
15981
+ const status = subagentGateStatusLabel(gate?.status);
15982
+ const card = make("section", `subagent-gate-card ${status}`);
15983
+ const header = make("div", "subagent-gate-header");
15984
+ const title = make("div", "subagent-gate-title");
15985
+ title.append(
15986
+ make("strong", undefined, `Retry gate · ${gate?.qualifyingSuccesses || 0}/${gate?.requiredSuccesses || 1}`),
15987
+ make("span", undefined, `${status}${gate?.requireDistinctProviders ? " · distinct providers" : ""}`),
15988
+ );
15989
+ header.append(title, make("span", `subagent-gate-status ${status}`, status));
15990
+ card.append(header);
15991
+ const attempts = make("div", "subagent-gate-attempts");
15992
+ for (const attempt of Array.isArray(gate?.attempts) ? gate.attempts : []) attempts.append(renderSubagentGateAttempt(attempt));
15993
+ if (!attempts.childElementCount) attempts.append(make("div", "subagents-empty", "Waiting for the first attempt…"));
15994
+ card.append(attempts);
15995
+ return card;
15996
+ }
15997
+
15074
15998
  function renderSubagentTabGroup(tab) {
15075
15999
  const group = make("section", `subagent-tab-group${tab.tabId === activeTabId ? " active" : ""}`);
15076
16000
  const header = make("button", "subagent-tab-header");
@@ -15081,7 +16005,8 @@ function renderSubagentTabGroup(tab) {
15081
16005
  make("strong", undefined, tab.tabTitle || `Terminal ${tab.tabIndex || "?"}`),
15082
16006
  make("span", "subagent-tab-session", `Terminal ${tab.tabIndex || "?"} · ${subagentTabMeta(tab)}`),
15083
16007
  );
15084
- header.append(title, make("span", "subagent-tab-count", String(tab.agentCount || 0)));
16008
+ const countLabel = Number(tab.gateCount || 0) > 0 ? `${tab.agentCount || 0} agents · ${tab.gateCount} gates` : String(tab.agentCount || 0);
16009
+ header.append(title, make("span", "subagent-tab-count", countLabel));
15085
16010
  header.addEventListener("click", () => switchTab(tab.tabId));
15086
16011
  group.append(header);
15087
16012
 
@@ -15095,6 +16020,9 @@ function renderSubagentTabGroup(tab) {
15095
16020
  .sort((a, b) => Number(a.index || 0) - Number(b.index || 0) || String(a.name || "").localeCompare(String(b.name || "")));
15096
16021
  for (const agent of agents) list.append(renderSubagentAgent(tab, run, agent));
15097
16022
  }
16023
+ for (const gate of (Array.isArray(tab.gates) ? tab.gates : []).slice().sort((a, b) => Number(a.startedAt || 0) - Number(b.startedAt || 0))) {
16024
+ list.append(renderSubagentGate(gate));
16025
+ }
15098
16026
  group.append(list);
15099
16027
  return group;
15100
16028
  }
@@ -15104,23 +16032,25 @@ function renderSubagents() {
15104
16032
  if (!box) return;
15105
16033
  const activeTabs = subagentTabsWithRunningAgents();
15106
16034
  const totalAgents = activeTabs.reduce((count, tab) => count + Number(tab.agentCount || 0), 0);
16035
+ const totalGates = activeTabs.reduce((count, tab) => count + Number(tab.gateCount || 0), 0);
16036
+ const totalItems = totalAgents + totalGates;
15107
16037
  if (elements.subagentCountBadge) {
15108
- elements.subagentCountBadge.textContent = String(totalAgents);
15109
- elements.subagentCountBadge.hidden = totalAgents === 0;
16038
+ elements.subagentCountBadge.textContent = String(totalItems);
16039
+ elements.subagentCountBadge.hidden = totalItems === 0;
15110
16040
  }
15111
16041
  if (elements.subagentsStatus) {
15112
- elements.subagentsStatus.textContent = totalAgents > 0
15113
- ? `${totalAgents} running across ${activeTabs.length} ${activeTabs.length === 1 ? "terminal" : "terminals"}`
16042
+ elements.subagentsStatus.textContent = totalItems > 0
16043
+ ? [`${totalAgents} running`, totalGates ? `${totalGates} retry ${totalGates === 1 ? "gate" : "gates"}` : "", `across ${activeTabs.length} ${activeTabs.length === 1 ? "terminal" : "terminals"}`].filter(Boolean).join(" · ")
15114
16044
  : subagentsLoading && !latestSubagents
15115
- ? "Checking running subagents…"
15116
- : "No running subagents.";
16045
+ ? "Checking subagents and retry gates…"
16046
+ : "No running subagents or retained retry gates.";
15117
16047
  }
15118
16048
 
15119
16049
  box.replaceChildren();
15120
- box.classList.toggle("muted", totalAgents === 0);
15121
- box.classList.toggle("has-items", totalAgents > 0);
15122
- if (totalAgents === 0) {
15123
- box.append(make("div", "subagents-empty", subagentsError ? `Subagent status unavailable: ${subagentsError.message || subagentsError}` : "Running subagents will appear here, grouped by terminal and session."));
16050
+ box.classList.toggle("muted", totalItems === 0);
16051
+ box.classList.toggle("has-items", totalItems > 0);
16052
+ if (totalItems === 0) {
16053
+ box.append(make("div", "subagents-empty", subagentsError ? `Subagent status unavailable: ${subagentsError.message || subagentsError}` : "Running subagents and retry-gate attempts will appear here, grouped by terminal and session."));
15124
16054
  return;
15125
16055
  }
15126
16056
  for (const tab of activeTabs) box.append(renderSubagentTabGroup(tab));
@@ -15147,7 +16077,8 @@ async function refreshSubagents() {
15147
16077
  function scheduleRefreshSubagents(delay) {
15148
16078
  clearTimeout(refreshSubagentsTimer);
15149
16079
  const totalAgents = Number(latestSubagents?.totalAgents || 0);
15150
- const nextDelay = delay ?? (document.visibilityState === "hidden" ? SUBAGENTS_HIDDEN_REFRESH_MS : totalAgents > 0 ? SUBAGENTS_ACTIVE_REFRESH_MS : SUBAGENTS_IDLE_REFRESH_MS);
16080
+ const hasRunningGate = (Array.isArray(latestSubagents?.tabs) ? latestSubagents.tabs : []).some((tab) => (Array.isArray(tab?.gates) ? tab.gates : []).some((gate) => gate?.status === "running"));
16081
+ const nextDelay = delay ?? (document.visibilityState === "hidden" ? SUBAGENTS_HIDDEN_REFRESH_MS : totalAgents > 0 || hasRunningGate ? SUBAGENTS_ACTIVE_REFRESH_MS : SUBAGENTS_IDLE_REFRESH_MS);
15151
16082
  refreshSubagentsTimer = setTimeout(() => {
15152
16083
  refreshSubagents().finally(() => scheduleRefreshSubagents());
15153
16084
  }, nextDelay);
@@ -15964,6 +16895,18 @@ function workflowInspectorSetSelection(patch) {
15964
16895
  renderWidgets();
15965
16896
  }
15966
16897
 
16898
+ function workflowInspectorSetMinimized(minimized) {
16899
+ if (!activeTabId) return;
16900
+ const tabId = activeTabId;
16901
+ if (minimized) workflowInspectorMinimizedByTab.add(tabId);
16902
+ else workflowInspectorMinimizedByTab.delete(tabId);
16903
+ renderWidgets();
16904
+ requestAnimationFrame(() => {
16905
+ if (activeTabId !== tabId) return;
16906
+ elements.widgetArea.querySelector(".workflow-inspector-minimize-button")?.focus({ preventScroll: true });
16907
+ });
16908
+ }
16909
+
15967
16910
  function workflowInspectorJson(value) {
15968
16911
  if (value === undefined) return "—";
15969
16912
  if (typeof value === "string") return value;
@@ -16027,9 +16970,13 @@ function renderWorkflowInspectorWidget() {
16027
16970
  if (!payload?.runs?.length) return null;
16028
16971
  const { run, phase } = workflowInspectorSelection(payload);
16029
16972
  if (!run) return null;
16973
+ const minimized = Boolean(activeTabId && workflowInspectorMinimizedByTab.has(activeTabId));
16030
16974
 
16031
- const node = make("section", "widget release-npm-widget workflow-widget workflow-inspector-widget");
16975
+ const node = make("section", `widget release-npm-widget workflow-widget workflow-inspector-widget${minimized ? " minimized" : ""}`);
16032
16976
  node.setAttribute("aria-label", "workflow run inspector");
16977
+ const body = make("div", "workflow-inspector-body");
16978
+ body.id = "workflowInspectorBody";
16979
+ body.hidden = minimized;
16033
16980
  const header = make("div", "release-npm-header");
16034
16981
  const titleWrap = make("div", "release-npm-title-wrap");
16035
16982
  titleWrap.append(make("span", "release-npm-kicker", "workflows"), make("strong", "release-npm-title", `${payload.runs.length} run${payload.runs.length === 1 ? "" : "s"}`));
@@ -16037,7 +16984,17 @@ function renderWorkflowInspectorWidget() {
16037
16984
  meta.append(make("span", "release-npm-pill", payload.mode?.enabled ? `mode ${payload.mode.phase}` : "mode off"));
16038
16985
  const liveCount = payload.runs.filter(workflowRunIsLive).length;
16039
16986
  if (liveCount) meta.append(make("span", "release-npm-pill workflow-status running", `${liveCount} active`));
16987
+ const minimizeButton = make("button", "release-npm-action workflow-inspector-minimize-button", minimized ? "Restore" : "Minimize");
16988
+ minimizeButton.type = "button";
16989
+ minimizeButton.setAttribute("aria-controls", body.id);
16990
+ minimizeButton.setAttribute("aria-expanded", minimized ? "false" : "true");
16991
+ minimizeButton.setAttribute("aria-label", minimized ? "Restore workflow inspector" : "Minimize workflow inspector");
16992
+ minimizeButton.setAttribute("title", minimized ? "Restore workflow inspector" : "Minimize workflow inspector");
16993
+ minimizeButton.addEventListener("click", () => workflowInspectorSetMinimized(!minimized));
16994
+ meta.append(minimizeButton);
16040
16995
  header.append(titleWrap, meta);
16996
+ node.append(header, body);
16997
+ if (minimized) return node;
16041
16998
 
16042
16999
  const layout = make("div", "workflow-inspector-layout");
16043
17000
  const runList = make("nav", "workflow-inspector-run-list");
@@ -16089,7 +17046,7 @@ function renderWorkflowInspectorWidget() {
16089
17046
  detail.append(raw);
16090
17047
  }
16091
17048
  layout.append(runList, detail);
16092
- node.append(header, layout);
17049
+ body.append(layout);
16093
17050
  return node;
16094
17051
  }
16095
17052
 
@@ -18516,6 +19473,7 @@ function selectGitInitWorkflowProcess(processValue, tabId, workflow) {
18516
19473
  manualCommitMessage: "",
18517
19474
  ...resetGitWorkflowManualCommitDefaultPatch(),
18518
19475
  messageRequestedAt: 0,
19476
+ messageGenerationId: "",
18519
19477
  branchName: "",
18520
19478
  branchNameRequestedAt: 0,
18521
19479
  prMode: false,
@@ -18567,7 +19525,7 @@ function selectGitWorkflowProcess(processValue, tabId = gitWorkflowActionTabId()
18567
19525
  if (!guidedReviewPatch) return;
18568
19526
  workflow.runId += 1;
18569
19527
  const runId = workflow.runId;
18570
- const base = { mode: "standard", active: true, process, busy: false, error: "", githubUsername: "", repoName: "", remoteUrl: "", stack: "", readmeRequestedAt: 0, gitignoreRequestedAt: 0, initFilesStatus: null, manualCommitMessage: "", ...resetGitWorkflowManualCommitDefaultPatch(), messageRequestedAt: 0, branchName: "", branchNameRequestedAt: 0, prMode: false, prBranch: "", pr: null, prRequestedAt: 0, ...guidedReviewPatch };
19528
+ const base = { mode: "standard", active: true, process, busy: false, error: "", githubUsername: "", repoName: "", remoteUrl: "", stack: "", readmeRequestedAt: 0, gitignoreRequestedAt: 0, initFilesStatus: null, manualCommitMessage: "", ...resetGitWorkflowManualCommitDefaultPatch(), messageRequestedAt: 0, messageGenerationId: "", branchName: "", branchNameRequestedAt: 0, prMode: false, prBranch: "", pr: null, prRequestedAt: 0, ...guidedReviewPatch };
18571
19529
 
18572
19530
  if (process === "stage") {
18573
19531
  setGitWorkflow({ ...base, step: "add", message: null, output: "Ready to stage all changes with git add ." }, { tabId });
@@ -18797,7 +19755,11 @@ function renderGitWorkflow() {
18797
19755
  addGitWorkflowAction("Preview current message files", () => loadGitWorkflowMessage({ requireFresh: false }), "", false);
18798
19756
  elements.gitWorkflowActions.append(commitInputButton);
18799
19757
  } else if (gitWorkflow.step === "generating") {
18800
- addGitWorkflowAction("Refresh message preview", () => loadGitWorkflowMessage({ requireFresh: true }), "", false);
19758
+ if (gitWorkflow.messageGenerationId) {
19759
+ addGitWorkflowAction("Refresh message preview", () => loadGitWorkflowMessage({ requireFresh: true }), "", false);
19760
+ } else {
19761
+ addGitWorkflowAction("Starting message generation…", () => {}, "", true);
19762
+ }
18801
19763
  } else if (gitWorkflow.step === "message") {
18802
19764
  const deliveryMode = preferences.deliveryMode || "ask";
18803
19765
  const preferredVariant = preferences.commit?.defaultVariant || "short";
@@ -19134,6 +20096,7 @@ async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {})
19134
20096
  manualCommitMessage: "",
19135
20097
  ...resetGitWorkflowManualCommitDefaultPatch(),
19136
20098
  messageRequestedAt: 0,
20099
+ messageGenerationId: "",
19137
20100
  branchName: "",
19138
20101
  branchNameRequestedAt: 0,
19139
20102
  actionsDone: createGitWorkflowActionsDone(),
@@ -19181,6 +20144,7 @@ async function startGitInitWorkflow(tabId = activeTabId) {
19181
20144
  manualCommitMessage: "",
19182
20145
  ...resetGitWorkflowManualCommitDefaultPatch(),
19183
20146
  messageRequestedAt: 0,
20147
+ messageGenerationId: "",
19184
20148
  branchName: "",
19185
20149
  branchNameRequestedAt: 0,
19186
20150
  actionsDone: createGitWorkflowActionsDone(),
@@ -19573,19 +20537,24 @@ async function runGitMessagePrompt(tabId = gitWorkflowActionTabId()) {
19573
20537
  busy: true,
19574
20538
  error: "",
19575
20539
  messageRequestedAt: requestedAt,
20540
+ messageGenerationId: "",
19576
20541
  output: "Sending /git-staged-msg to Pi.\n\nCancel will request Pi abort.",
19577
20542
  }, { tabId });
19578
20543
  if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending /git-staged-msg to Pi…");
19579
20544
  try {
19580
20545
  const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "commit", ...(expectedStagedContentHash ? { expectedStagedContentHash } : {}) }, runId, tabId });
19581
20546
  if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
19582
- appendGitWorkflowOutput(`/git-staged-msg accepted with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for agent_end, then the message files will be loaded.`, { tabId });
20547
+ const generationId = String(generation.generationId || "").trim();
20548
+ if (!generationId) throw new Error("The WebUI server did not return a commit-message generation ID. Restart Pi Web UI and regenerate.");
20549
+ setGitWorkflow({ messageGenerationId: generationId }, { tabId });
20550
+ appendGitWorkflowOutput(`/git-staged-msg accepted with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for agent_end, then both correlated message files will be loaded.`, { tabId });
19583
20551
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
19584
20552
  setTimeout(() => {
19585
20553
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
19586
- const targetStillBusy = tabId === activeTabId && currentState?.isStreaming;
19587
- if (isCurrentGitWorkflowRun(runId, tabId) && currentWorkflow?.step === "generating" && !targetStillBusy) {
19588
- loadGitWorkflowMessage({ requireFresh: true, retries: 1, runId, tabId });
20554
+ const targetTab = tabs.find((tab) => tab.id === tabId);
20555
+ const targetStillBusy = tabId === activeTabId ? !!currentState?.isStreaming : activityForTab(targetTab).isWorking;
20556
+ if (isCurrentGitWorkflowRun(runId, tabId) && currentWorkflow?.step === "generating" && currentWorkflow.messageGenerationId === generationId && !targetStillBusy) {
20557
+ loadGitWorkflowMessage({ requireFresh: true, generationId, runId, tabId });
19589
20558
  }
19590
20559
  }, 2500);
19591
20560
  } catch (error) {
@@ -19596,35 +20565,93 @@ async function runGitMessagePrompt(tabId = gitWorkflowActionTabId()) {
19596
20565
  }
19597
20566
  }
19598
20567
 
19599
- async function loadGitWorkflowMessage({ requireFresh = false, retries = 0, runId, tabId = activeTabId } = {}) {
20568
+ const GIT_WORKFLOW_MESSAGE_POLL_TIMEOUT_MS = 30_000;
20569
+ const GIT_WORKFLOW_MESSAGE_POLL_DELAYS_MS = [250, 500, 800, 1200];
20570
+
20571
+ function gitWorkflowMessageLoadIsCurrent(tabId, runId, generationId = "") {
20572
+ const workflow = gitWorkflowForTab(tabId, { create: false });
20573
+ return !!workflow
20574
+ && isCurrentGitWorkflowRun(runId, tabId)
20575
+ && (!generationId || workflow.messageGenerationId === generationId);
20576
+ }
20577
+
20578
+ function waitForGitWorkflowMessagePoll(attempt) {
20579
+ const delayMs = GIT_WORKFLOW_MESSAGE_POLL_DELAYS_MS[Math.min(attempt, GIT_WORKFLOW_MESSAGE_POLL_DELAYS_MS.length - 1)];
20580
+ return new Promise((resolve) => setTimeout(resolve, delayMs));
20581
+ }
20582
+
20583
+ async function loadGitWorkflowMessage({ requireFresh = false, generationId, runId, tabId = activeTabId } = {}) {
19600
20584
  const workflow = gitWorkflowForTab(tabId, { create: false });
19601
20585
  const expectedRunId = runId ?? workflow?.runId;
19602
- try {
19603
- const message = await gitWorkflowRequest("/api/git-workflow/message", { method: "GET", runId: expectedRunId, tabId });
19604
- if (!message) return;
19605
- const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
19606
- if (!currentWorkflow) return;
19607
- const newestMtime = Math.max(message.shortMtimeMs || 0, message.longMtimeMs || 0);
19608
- if (requireFresh && currentWorkflow.messageRequestedAt && newestMtime + 10000 < currentWorkflow.messageRequestedAt) {
19609
- throw new Error("Generated message files have not refreshed yet.");
19610
- }
19611
- setGitWorkflow({
19612
- step: "message",
19613
- busy: false,
19614
- error: "",
19615
- message,
19616
- ...(requireFresh && currentWorkflow.messageRequestedAt ? gitWorkflowActionDonePatch(currentWorkflow, "message") : {}),
19617
- output: formatCommitMessagePreview(message),
19618
- }, { tabId });
19619
- } catch (error) {
19620
- if (!isCurrentGitWorkflowRun(expectedRunId, tabId)) return;
19621
- if (retries > 0) {
19622
- setTimeout(() => loadGitWorkflowMessage({ requireFresh, retries: retries - 1, runId: expectedRunId, tabId }), 1400);
19623
- return;
20586
+ const expectedGenerationId = requireFresh ? String(generationId ?? workflow?.messageGenerationId ?? "").trim() : "";
20587
+ if (!workflow || expectedRunId === undefined) return;
20588
+ if (requireFresh && !expectedGenerationId) {
20589
+ // The generation POST can be accepted just before its correlation ID is
20590
+ // returned to the browser. Timer/event wakeups in that narrow window are
20591
+ // harmless; the accepted-request continuation and fallback timer retry.
20592
+ if (workflow.step === "generating") return;
20593
+ failGitWorkflow(new Error("No correlated commit-message generation is active. Run /git-staged-msg again."), "generate", { tabId });
20594
+ return;
20595
+ }
20596
+
20597
+ const loadKey = `${expectedRunId}:${expectedGenerationId || "preview"}`;
20598
+ const existing = gitWorkflowMessageLoadsByTab.get(tabId);
20599
+ if (existing?.key === loadKey) return existing.promise;
20600
+
20601
+ const promise = (async () => {
20602
+ const deadline = Date.now() + (requireFresh ? GIT_WORKFLOW_MESSAGE_POLL_TIMEOUT_MS : 0);
20603
+ const baseOutput = workflow.output || "Waiting for generated commit message files…";
20604
+ let attempt = 0;
20605
+ while (gitWorkflowMessageLoadIsCurrent(tabId, expectedRunId, expectedGenerationId)) {
20606
+ try {
20607
+ const query = expectedGenerationId ? `?generationId=${encodeURIComponent(expectedGenerationId)}` : "";
20608
+ const message = await gitWorkflowRequest(`/api/git-workflow/message${query}`, { method: "GET", runId: expectedRunId, tabId });
20609
+ if (!message || !gitWorkflowMessageLoadIsCurrent(tabId, expectedRunId, expectedGenerationId)) return;
20610
+ if (message.ready === false) {
20611
+ if (message.expired) throw new Error(message.reason || "This commit-message generation has expired. Regenerate the message files.");
20612
+ if (!requireFresh || Date.now() >= deadline) {
20613
+ throw new Error(`${message.reason || "Generated commit message files are not ready."} Regenerate, or use Preview current message files after verifying both files.`);
20614
+ }
20615
+ const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
20616
+ const reason = message.reason || "Waiting for both correlated commit message files…";
20617
+ if (currentWorkflow?.output !== `${baseOutput}\n\n${reason}`) {
20618
+ setGitWorkflow({ busy: true, error: "", output: `${baseOutput}\n\n${reason}` }, { tabId });
20619
+ }
20620
+ await waitForGitWorkflowMessagePoll(attempt++);
20621
+ continue;
20622
+ }
20623
+ const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
20624
+ if (!currentWorkflow || !gitWorkflowMessageLoadIsCurrent(tabId, expectedRunId, expectedGenerationId)) return;
20625
+ setGitWorkflow({
20626
+ step: "message",
20627
+ busy: false,
20628
+ error: "",
20629
+ message,
20630
+ ...(requireFresh ? gitWorkflowActionDonePatch(currentWorkflow, "message") : {}),
20631
+ output: formatCommitMessagePreview(message),
20632
+ }, { tabId });
20633
+ return;
20634
+ } catch (error) {
20635
+ if (!gitWorkflowMessageLoadIsCurrent(tabId, expectedRunId, expectedGenerationId)) return;
20636
+ if (!requireFresh || Date.now() >= deadline || /expired|no longer active/i.test(error?.message || "")) throw error;
20637
+ const reason = error?.message || String(error);
20638
+ const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
20639
+ if (currentWorkflow?.output !== `${baseOutput}\n\nWaiting for both correlated message files. ${reason}`) {
20640
+ setGitWorkflow({ busy: true, error: "", output: `${baseOutput}\n\nWaiting for both correlated message files. ${reason}` }, { tabId });
20641
+ }
20642
+ await waitForGitWorkflowMessagePoll(attempt++);
20643
+ }
19624
20644
  }
20645
+ })().catch((error) => {
20646
+ if (!gitWorkflowMessageLoadIsCurrent(tabId, expectedRunId, expectedGenerationId)) return;
19625
20647
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
19626
20648
  failGitWorkflow(error, currentWorkflow?.step === "generating" ? "generate" : currentWorkflow?.step, { tabId });
19627
- }
20649
+ }).finally(() => {
20650
+ if (gitWorkflowMessageLoadsByTab.get(tabId)?.key === loadKey) gitWorkflowMessageLoadsByTab.delete(tabId);
20651
+ });
20652
+
20653
+ gitWorkflowMessageLoadsByTab.set(tabId, { key: loadKey, promise });
20654
+ return promise;
19628
20655
  }
19629
20656
 
19630
20657
  function gitBranchNamePromptMessage() {
@@ -19811,6 +20838,7 @@ async function createGitPrBranchWithSuggestion(suggestion, tabId = gitWorkflowAc
19811
20838
  manualCommitMessageDefaultRequestedAt: sourceWorkflow.manualCommitMessageDefaultRequestedAt || 0,
19812
20839
  manualCommitMessageDefaultLoading: false,
19813
20840
  messageRequestedAt: sourceWorkflow.messageRequestedAt || 0,
20841
+ messageGenerationId: sourceWorkflow.messageGenerationId || "",
19814
20842
  branchName: prBranch || branch,
19815
20843
  branchNameRequestedAt: sourceWorkflow.branchNameRequestedAt || 0,
19816
20844
  actionsDone: createGitWorkflowActionsDone({ ...sourceWorkflow.actionsDone, branch: true }),
@@ -20040,7 +21068,7 @@ function resumeGitWorkflowForActiveTab(tabContext = activeTabContext()) {
20040
21068
  setTimeout(() => resumeGitWorkflowForActiveTab(tabContext), retryDelayMs);
20041
21069
  return;
20042
21070
  }
20043
- loadGitWorkflowMessage({ requireFresh: true, retries: 3, runId: gitWorkflow.runId, tabId: workflowTabId });
21071
+ loadGitWorkflowMessage({ requireFresh: true, generationId: gitWorkflow.messageGenerationId, runId: gitWorkflow.runId, tabId: workflowTabId });
20044
21072
  }
20045
21073
  if (workflowTabId === tabContext.tabId && gitWorkflow.active && gitWorkflow.step === "branchNaming" && !currentState?.isStreaming) {
20046
21074
  const retryDelayMs = Math.max(0, 2500 - (Date.now() - (gitWorkflow.branchNameRequestedAt || 0)));
@@ -23499,6 +24527,45 @@ function addTransientMessage({ role = "notice", title, content, level = "info",
23499
24527
  renderAllMessages();
23500
24528
  }
23501
24529
 
24530
+ function surfaceRuntimeDiagnostic(title, content, level = "error") {
24531
+ const message = String(content || "").trim();
24532
+ if (!message) return;
24533
+ addEvent(message, level);
24534
+ addTransientMessage({ role: level === "error" ? "error" : "warn", title, content: message, level });
24535
+ }
24536
+
24537
+ function stderrDiagnosticLevel(content) {
24538
+ return /(?:^|\b)(?:error|failed|failure|fatal|exception|invalid)(?:\b|:)/i.test(String(content || "")) ? "error" : "warn";
24539
+ }
24540
+
24541
+ function toolImagePayloadError(event) {
24542
+ const blocks = Array.isArray(event?.result?.content) ? event.result.content : [];
24543
+ for (const [index, block] of blocks.entries()) {
24544
+ if (block?.type !== "image") continue;
24545
+ const data = typeof block.data === "string" ? block.data.replace(/\s+/g, "") : "";
24546
+ let canonical = data.length > 0 && data.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(data);
24547
+ if (canonical) {
24548
+ try {
24549
+ canonical = btoa(atob(data)) === data;
24550
+ } catch {
24551
+ canonical = false;
24552
+ }
24553
+ }
24554
+ if (!canonical) {
24555
+ const toolName = String(event.toolName || "Tool");
24556
+ return `${toolName} returned image output ${index + 1} with invalid base64 data. The next model request may fail. Upgrade or fix the tool, then start a new session or fork before this tool result to remove it from context.`;
24557
+ }
24558
+ }
24559
+ return "";
24560
+ }
24561
+
24562
+ function assistantErrorFromAgentEnd(event) {
24563
+ const messages = Array.isArray(event?.messages) ? event.messages : [];
24564
+ const message = messages.findLast((item) => item?.role === "assistant");
24565
+ if (message?.stopReason !== "error") return "";
24566
+ return String(message.errorMessage || "The assistant request failed without an error message.").trim();
24567
+ }
24568
+
23502
24569
  function addAbortTranscriptNotice({ activeRun = false, errorMessage = "" } = {}) {
23503
24570
  if (errorMessage) {
23504
24571
  addTransientMessage({ role: "error", title: "Abort failed", content: `Abort request failed: ${errorMessage}`, level: "error" });
@@ -23901,7 +24968,7 @@ function requestGitFooterWebuiPayload(tabContext = activeTabContext(), { force =
23901
24968
 
23902
24969
  gitFooterPayloadRefreshInFlightByTab.add(tabContext.tabId);
23903
24970
  if (isCurrentTabContext(tabContext)) renderFooter();
23904
- api("/api/prompt", {
24971
+ return api("/api/prompt", {
23905
24972
  method: "POST",
23906
24973
  body: { message: `/${refreshCommand}${silent ? " --webui-silent" : ""}`, streamingBehavior: "steer" },
23907
24974
  tabId: tabContext.tabId,
@@ -26026,6 +27093,7 @@ function resetStreamBubble() {
26026
27093
  streamThinkingBubble = null;
26027
27094
  streamThinking = null;
26028
27095
  streamMessageActive = false;
27096
+ streamProviderErrorText = "";
26029
27097
  }
26030
27098
 
26031
27099
  function liveStreamRenderActive() {
@@ -26202,6 +27270,17 @@ function syncStreamingThinkingFromUpdate(event, update, { placeholder = "" } = {
26202
27270
  return setStreamingThinkingText(streamThinkingRawText || placeholder);
26203
27271
  }
26204
27272
 
27273
+ function assistantStreamErrorMessage(event, update = event?.assistantMessageEvent || {}) {
27274
+ return String(
27275
+ update.error?.errorMessage ||
27276
+ update.errorMessage ||
27277
+ update.partial?.errorMessage ||
27278
+ event?.message?.errorMessage ||
27279
+ update.reason ||
27280
+ "assistant error"
27281
+ ).trim();
27282
+ }
27283
+
26205
27284
  function handleMessageUpdate(event) {
26206
27285
  const update = event.assistantMessageEvent || {};
26207
27286
  if (update.type === "thinking_start") {
@@ -26246,8 +27325,9 @@ function handleMessageUpdate(event) {
26246
27325
  const name = updateStreamingToolCallFromEvent(event, { complete: true, scroll: true });
26247
27326
  setRunIndicatorActivity(`Tool call ready: ${name}; waiting to run…`, { scroll: false });
26248
27327
  } else if (update.type === "error") {
27328
+ streamProviderErrorText = assistantStreamErrorMessage(event, update);
26249
27329
  setRunIndicatorActivity("Assistant stream reported an error…");
26250
- appendMessage({ role: "error", title: "assistant error", timestamp: Date.now(), content: update.reason || update.errorMessage || "assistant error", level: "error" }, { streaming: true });
27330
+ appendMessage({ role: "error", title: "assistant error", timestamp: Date.now(), content: streamProviderErrorText, level: "error" }, { streaming: true });
26251
27331
  renderRunIndicator({ scroll: false });
26252
27332
  scheduleChatFollowScroll();
26253
27333
  }
@@ -28370,6 +29450,9 @@ function handleEvent(event) {
28370
29450
  renderWidgets();
28371
29451
  renderTabs();
28372
29452
  break;
29453
+ case "webui_git_changed":
29454
+ invalidateGitPanelRepository(event.root);
29455
+ break;
28373
29456
  case "webui_cwd_changed":
28374
29457
  addEvent(`${event.tabTitle || "terminal"} cwd changed to ${event.cwd}`);
28375
29458
  setAppRunnerData(event.tabId || activeTabId, { cwd: event.cwd, activeRun: null, runners: [] });
@@ -28402,21 +29485,24 @@ function handleEvent(event) {
28402
29485
  renderNetworkStatus();
28403
29486
  break;
28404
29487
  case "pi_process_exit":
28405
- addEvent(`pi rpc exited (${event.code ?? event.signal ?? "unknown"})`, "error");
29488
+ surfaceRuntimeDiagnostic("Pi process exited", `Pi RPC exited (${event.code ?? event.signal ?? "unknown"}).`);
28406
29489
  clearRunIndicatorActivity();
28407
29490
  refreshTabs().catch((error) => addEvent(error.message, "error"));
28408
29491
  break;
28409
29492
  case "pi_process_error":
28410
- addEvent(event.error || "pi rpc process error", "error");
29493
+ surfaceRuntimeDiagnostic("Pi process error", event.error || "Pi RPC process error.");
28411
29494
  clearRunIndicatorActivity();
28412
29495
  refreshTabs().catch((error) => addEvent(error.message, "error"));
28413
29496
  break;
28414
- case "pi_stderr":
28415
- addEvent(event.text.trim(), "warn");
29497
+ case "pi_stderr": {
29498
+ const message = String(event.text || "").trim();
29499
+ if (message) surfaceRuntimeDiagnostic("Pi runtime diagnostic", message, stderrDiagnosticLevel(message));
28416
29500
  break;
29501
+ }
28417
29502
  case "pi_stderr_sink_error":
28418
29503
  case "pi_stdout_line_too_large":
28419
- addEvent(event.error || "Pi RPC transport diagnostic", "error");
29504
+ case "pi_stdout_parse_error":
29505
+ surfaceRuntimeDiagnostic("Pi RPC transport error", event.error || "Pi RPC transport diagnostic.");
28420
29506
  break;
28421
29507
  case "queue_update":
28422
29508
  renderQueue(event);
@@ -28440,6 +29526,7 @@ function handleEvent(event) {
28440
29526
  scheduleRefreshState();
28441
29527
  break;
28442
29528
  case "agent_start":
29529
+ assistantErrorSurfacedThisRun = false;
28443
29530
  if (currentState) currentState = { ...currentState, isStreaming: true };
28444
29531
  if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ streaming: true });
28445
29532
  setRunIndicatorActivity("Agent run started; waiting for first output or action…");
@@ -28450,6 +29537,13 @@ function handleEvent(event) {
28450
29537
  break;
28451
29538
  case "agent_end":
28452
29539
  streamMessageActive = false;
29540
+ if (!assistantErrorSurfacedThisRun && event.willRetry !== true) {
29541
+ const message = assistantErrorFromAgentEnd(event);
29542
+ if (message) {
29543
+ surfaceRuntimeDiagnostic("Assistant error", message);
29544
+ assistantErrorSurfacedThisRun = true;
29545
+ }
29546
+ }
28453
29547
  addEvent("agent finished");
28454
29548
  notifyAgentDone(event.tabId || activeTabId, { activity: event.tabActivity, tabTitle: event.tabTitle });
28455
29549
  clearContextUsageUnknownAfterCompaction(event.tabId || activeTabId);
@@ -28471,7 +29565,7 @@ function handleEvent(event) {
28471
29565
  const workflowTabId = event.tabId || activeTabId;
28472
29566
  const workflow = gitWorkflowForTab(workflowTabId, { create: false });
28473
29567
  if (workflow?.active && workflow.step === "generating") {
28474
- loadGitWorkflowMessage({ requireFresh: true, retries: 3, runId: workflow.runId, tabId: workflowTabId });
29568
+ loadGitWorkflowMessage({ requireFresh: true, generationId: workflow.messageGenerationId, runId: workflow.runId, tabId: workflowTabId });
28475
29569
  } else if (workflow?.active && workflow.step === "branchNaming") {
28476
29570
  loadGitWorkflowBranchName({ requireFresh: true, retries: 3, runId: workflow.runId, tabId: workflowTabId });
28477
29571
  } else if (workflow?.active && workflow.step === "prGenerating") {
@@ -28489,13 +29583,20 @@ function handleEvent(event) {
28489
29583
  case "message_update":
28490
29584
  handleMessageUpdate(event);
28491
29585
  break;
28492
- case "message_end":
29586
+ case "message_end": {
28493
29587
  streamMessageActive = false;
29588
+ if (event.message?.role === "assistant" && event.message.stopReason === "error") {
29589
+ const message = String(event.message.errorMessage || streamProviderErrorText || "The assistant request failed without an error message.").trim();
29590
+ surfaceRuntimeDiagnostic("Assistant error", message);
29591
+ assistantErrorSurfacedThisRun = true;
29592
+ }
29593
+ streamProviderErrorText = "";
28494
29594
  if (runIndicatorIsActive()) setRunIndicatorActivity("Assistant message finished; waiting for the next step…", { scroll: false });
28495
29595
  scheduleRefreshMessages();
28496
29596
  scheduleRefreshState();
28497
29597
  scheduleRefreshFooter();
28498
29598
  break;
29599
+ }
28499
29600
  case "tool_execution_start":
28500
29601
  streamToolCallSeen = true;
28501
29602
  if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ toolRunning: true });
@@ -28509,8 +29610,10 @@ function handleEvent(event) {
28509
29610
  handleToolExecutionUpdate(event);
28510
29611
  setRunIndicatorActivity(`Running tool: ${runIndicatorToolName(event.toolName)}…`, { scroll: false });
28511
29612
  break;
28512
- case "tool_execution_end":
29613
+ case "tool_execution_end": {
28513
29614
  if (voiceConversationActiveFor(event.tabId || activeTabId)) voiceConversation.setAssistantActivity({ toolRunning: false });
29615
+ const imagePayloadError = toolImagePayloadError(event);
29616
+ if (imagePayloadError) surfaceRuntimeDiagnostic("Tool image payload error", imagePayloadError);
28514
29617
  handleToolExecutionEnd(event);
28515
29618
  setRunIndicatorActivity(`Tool ${runIndicatorToolName(event.toolName)} ${event.isError ? "failed" : "finished"}; waiting for the agent's next step…`);
28516
29619
  addEvent(`tool ${event.toolName} ${event.isError ? "failed" : "finished"}`, event.isError ? "error" : "info", { toolCallId: event.toolCallId });
@@ -28519,6 +29622,7 @@ function handleEvent(event) {
28519
29622
  // transcript. This avoids one fetch+render per tool call.
28520
29623
  scheduleRefreshFooter();
28521
29624
  break;
29625
+ }
28522
29626
  case "compaction_start":
28523
29627
  if (currentState) currentState = { ...currentState, isCompacting: true };
28524
29628
  markContextUsageUnknownAfterCompaction(event.tabId || activeTabId);
@@ -28530,7 +29634,8 @@ function handleEvent(event) {
28530
29634
  if (currentState) currentState = { ...currentState, isCompacting: false };
28531
29635
  if (event.aborted) clearContextUsageUnknownAfterCompaction(event.tabId || activeTabId);
28532
29636
  else markContextUsageUnknownAfterCompaction(event.tabId || activeTabId);
28533
- addEvent(`compaction ${event.aborted ? "aborted" : "finished"}`);
29637
+ if (event.errorMessage) surfaceRuntimeDiagnostic("Compaction error", event.errorMessage);
29638
+ else addEvent(`compaction ${event.aborted ? "aborted" : "finished"}`);
28534
29639
  if (!currentState?.isStreaming) clearRunIndicatorActivity();
28535
29640
  markTabOutputSeen();
28536
29641
  renderStatus();
@@ -28565,7 +29670,7 @@ function handleEvent(event) {
28565
29670
  handleExtensionUiRequest(event);
28566
29671
  break;
28567
29672
  case "response":
28568
- if (event.success === false) addEvent(`${event.command} failed: ${event.error || "unknown error"}`, "error");
29673
+ if (event.success === false) surfaceRuntimeDiagnostic(`${event.command || "Pi command"} failed`, event.error || "Unknown RPC command error.");
28569
29674
  else if (event.command === "get_state" && event.tabId === activeTabId) {
28570
29675
  currentState = event.data || currentState;
28571
29676
  syncActiveTabActivityFromState(currentState);
@@ -29459,6 +30564,7 @@ elements.sidePanelExpandButton.addEventListener("click", () => {
29459
30564
  elements.sidePanelBackdrop.addEventListener("click", () => {
29460
30565
  setSidePanelCollapsed(true);
29461
30566
  });
30567
+ bindSidePanelContextMenu();
29462
30568
  elements.stickyUserPromptButton?.addEventListener("click", jumpToStickyUserPrompt);
29463
30569
  elements.jumpToLatestButton.addEventListener("click", jumpToLatest);
29464
30570
  elements.chat.addEventListener("wheel", noteChatUserScrollIntent, { passive: true });
@@ -29515,6 +30621,12 @@ document.addEventListener("pointerdown", (event) => {
29515
30621
  if (elements.fileContextMenu && !elements.fileContextMenu.hidden && !event.target?.closest?.(".file-context-menu")) {
29516
30622
  closeFileContextMenu();
29517
30623
  }
30624
+ if (elements.gitPanelContextMenu && !elements.gitPanelContextMenu.hidden && !event.target?.closest?.(".git-side-panel-context-menu")) {
30625
+ closeGitPanelContextMenu();
30626
+ }
30627
+ if (elements.sidePanelContextMenu && !elements.sidePanelContextMenu.hidden && !event.target?.closest?.(".side-panel-context-menu")) {
30628
+ closeSidePanelContextMenu();
30629
+ }
29518
30630
  }, { passive: true });
29519
30631
  document.addEventListener("pointermove", (event) => {
29520
30632
  if (openTerminalTabGroupKey && !event.target?.closest?.(".terminal-tab-group")) {
@@ -29713,6 +30825,7 @@ window.addEventListener("focus", () => scheduleForegroundReconcile("window focus
29713
30825
  window.addEventListener("online", () => scheduleForegroundReconcile("network online", 0));
29714
30826
  window.addEventListener("storage", (event) => {
29715
30827
  if (event.key === OPTIONAL_FEATURES_STORAGE_KEY) reconcileDisabledOptionalFeaturesFromStorage();
30828
+ if (event.key === SIDE_PANEL_SECTION_VISIBILITY_STORAGE_KEY) restoreSidePanelSectionVisibility();
29716
30829
  });
29717
30830
  window.addEventListener("resize", syncFileViewerWidthForViewport, { passive: true });
29718
30831
  window.addEventListener("keydown", (event) => {
@@ -29877,6 +30990,36 @@ elements.fileContextMenu?.addEventListener("keydown", (event) => {
29877
30990
  items[event.key === "Home" ? 0 : items.length - 1]?.focus({ preventScroll: true });
29878
30991
  }
29879
30992
  });
30993
+ elements.gitPanelContextMenu?.addEventListener("keydown", (event) => {
30994
+ const items = [...elements.gitPanelContextMenu.querySelectorAll('[role="menuitem"]:not([disabled])')];
30995
+ const index = items.indexOf(document.activeElement);
30996
+ if (event.key === "Escape") {
30997
+ event.preventDefault();
30998
+ closeGitPanelContextMenu();
30999
+ } else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
31000
+ event.preventDefault();
31001
+ const direction = event.key === "ArrowDown" ? 1 : -1;
31002
+ items[(Math.max(0, index) + direction + items.length) % items.length]?.focus({ preventScroll: true });
31003
+ } else if (event.key === "Home" || event.key === "End") {
31004
+ event.preventDefault();
31005
+ items[event.key === "Home" ? 0 : items.length - 1]?.focus({ preventScroll: true });
31006
+ }
31007
+ });
31008
+ elements.sidePanelContextMenu?.addEventListener("keydown", (event) => {
31009
+ const items = [...elements.sidePanelContextMenu.querySelectorAll('[role="menuitemcheckbox"]')];
31010
+ const index = items.indexOf(document.activeElement);
31011
+ if (event.key === "Escape") {
31012
+ event.preventDefault();
31013
+ closeSidePanelContextMenu();
31014
+ } else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
31015
+ event.preventDefault();
31016
+ const direction = event.key === "ArrowDown" ? 1 : -1;
31017
+ items[(Math.max(0, index) + direction + items.length) % items.length]?.focus({ preventScroll: true });
31018
+ } else if (event.key === "Home" || event.key === "End") {
31019
+ event.preventDefault();
31020
+ items[event.key === "Home" ? 0 : items.length - 1]?.focus({ preventScroll: true });
31021
+ }
31022
+ });
29880
31023
  elements.fileContextMenu?.addEventListener("click", (event) => {
29881
31024
  const button = event.target?.closest?.("[data-file-menu-action]");
29882
31025
  if (!button) return;
@@ -30058,6 +31201,7 @@ restoreToolOutputExpansionSetting();
30058
31201
  restoreWorkspaceDashboardState();
30059
31202
  restoreInterfaceDensity();
30060
31203
  initializeTerminalHeaderTooltips();
31204
+ restoreSidePanelSectionVisibility();
30061
31205
  restoreSidePanelSectionState();
30062
31206
  bindSidePanelSectionToggles();
30063
31207
  restoreSidePanelState();