@firstpick/pi-package-webui 0.6.4 → 0.6.5

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
@@ -112,6 +112,7 @@ const elements = {
112
112
  optionsForkButton: $("#optionsForkButton"),
113
113
  optionsTreeButton: $("#optionsTreeButton"),
114
114
  optionsStatsButton: $("#optionsStatsButton"),
115
+ optionsFooterVisibilityButton: $("#optionsFooterVisibilityButton"),
115
116
  gitWorkflowPanel: $("#gitWorkflowPanel"),
116
117
  gitWorkflowKicker: $("#gitWorkflowKicker"),
117
118
  gitWorkflowTitle: $("#gitWorkflowTitle"),
@@ -132,6 +133,7 @@ const elements = {
132
133
  gitChangesStatus: $("#gitChangesStatus"),
133
134
  gitChangesBody: $("#gitChangesBody"),
134
135
  gitChangesRefreshButton: $("#gitChangesRefreshButton"),
136
+ gitChangesFetchButton: $("#gitChangesFetchButton"),
135
137
  gitChangesPullButton: $("#gitChangesPullButton"),
136
138
  gitChangesCloseButton: $("#gitChangesCloseButton"),
137
139
  modelControlLabel: $("#modelControlLabel"),
@@ -278,6 +280,14 @@ const elements = {
278
280
  appRunnerInfoDialog: $("#appRunnerInfoDialog"),
279
281
  appRunnerInfoBody: $("#appRunnerInfoBody"),
280
282
  appRunnerInfoCloseButton: $("#appRunnerInfoCloseButton"),
283
+ gitFooterVisibilityDialog: $("#gitFooterVisibilityDialog"),
284
+ gitFooterVisibilityBody: $("#gitFooterVisibilityBody"),
285
+ gitFooterVisibilityStatus: $("#gitFooterVisibilityStatus"),
286
+ gitFooterVisibilitySelectAllButton: $("#gitFooterVisibilitySelectAllButton"),
287
+ gitFooterVisibilitySelectNoneButton: $("#gitFooterVisibilitySelectNoneButton"),
288
+ gitFooterVisibilityCloseButton: $("#gitFooterVisibilityCloseButton"),
289
+ gitFooterVisibilityResetButton: $("#gitFooterVisibilityResetButton"),
290
+ gitFooterVisibilityApplyButton: $("#gitFooterVisibilityApplyButton"),
281
291
  statsOverlayDialog: $("#statsOverlayDialog"),
282
292
  statsOverlaySubtitle: $("#statsOverlaySubtitle"),
283
293
  statsOverlayScope: $("#statsOverlayScope"),
@@ -297,10 +307,11 @@ let tabDrafts = new Map();
297
307
  let tabAttachments = new Map();
298
308
  let activeTextAttachmentEditor = null;
299
309
  let activeSkillEditor = null;
300
- let fileTreeState = { root: "", entriesByPath: new Map(), expanded: new Set(), loading: new Set(), selectedPath: "", requestSerial: 0, searchQuery: "", searchEntries: [], searchLoading: false, searchTruncated: false, searchTotal: 0 };
310
+ let fileTreeState = { root: "", entriesByPath: new Map(), expanded: new Set(), loading: new Set(), selectedPath: "", requestSerial: 0, searchQuery: "", searchEntries: [], searchLoading: false, searchTruncated: false, searchTotal: 0, gitStatusRoot: "", gitStatusByPath: new Map() };
301
311
  let activeFileViewer = null;
302
312
  let fileViewerSelection = null;
303
313
  let fileContextMenuState = null;
314
+ let fileTreeDragState = null;
304
315
  let fileViewerResizeState = null;
305
316
  let fileTreeSearchTimer = null;
306
317
  let fileTreeSearchRequestSerial = 0;
@@ -346,7 +357,8 @@ let foregroundReconcileTimer = null;
346
357
  let eventSource = null;
347
358
  let activeDialog = null;
348
359
  let activeGitPrDialogResolve = null;
349
- let gitChangesState = { loading: false, pulling: false, error: "", message: "", pullResult: null, data: null, tabId: null };
360
+ let gitChangesState = { loading: false, pulling: false, fetching: false, error: "", errorCode: "", errorHint: "", message: "", pullResult: null, data: null, operation: null, lastFetch: null, tabId: null };
361
+ let gitToolsState = { tabId: null, openSections: new Set(), cache: {}, busy: new Set(), notice: {} };
350
362
  let gitChangesRequestSerial = 0;
351
363
  const gitChangesUntrackedContentRequests = new Set();
352
364
  let nativeCommandTabId = null;
@@ -541,6 +553,58 @@ const GIT_FOOTER_WEBUI_PAYLOAD_TYPE = "firstpick.git-footer-status.footer";
541
553
  const GIT_FOOTER_WEBUI_PAYLOAD_VERSION = 1;
542
554
  const GIT_FOOTER_WEBUI_PAYLOAD_CACHE_KEY = "pi-webui-git-footer-webui-payload-cache";
543
555
  const GIT_FOOTER_STATUS_SETUP_STORAGE_KEY = "pi-webui-git-footer-status-setup";
556
+ const GIT_FOOTER_WEBUI_VISIBILITY_DEFAULTS = Object.freeze({
557
+ tokens: true,
558
+ cache: true,
559
+ pi: true,
560
+ speed: true,
561
+ cost: true,
562
+ context: true,
563
+ model: true,
564
+ thinking: true,
565
+ cwd: true,
566
+ "cwd-branch": true,
567
+ "git-status": true,
568
+ "extension-statuses": true,
569
+ git: true,
570
+ "git-state": true,
571
+ sync: true,
572
+ changes: true,
573
+ "git-extra": true,
574
+ worktree: true,
575
+ "context-meta": true,
576
+ "git-branch-indicator": false,
577
+ "git-detached": true,
578
+ "git-operation": true,
579
+ "git-ahead": true,
580
+ "git-behind": true,
581
+ "git-upstream": true,
582
+ "git-staged": true,
583
+ "git-unstaged": true,
584
+ "git-untracked": true,
585
+ "git-conflicted": true,
586
+ "git-clean": true,
587
+ "git-stash": true,
588
+ "git-submodules": true,
589
+ "git-worktrees": true,
590
+ "git-tag": true,
591
+ "git-last-commit-age": true,
592
+ "git-signing-mismatch": true,
593
+ "webui-fetch-state": true,
594
+ "webui-refresh-button": true,
595
+ "webui-details-button": true,
596
+ "webui-cwd-picker": true,
597
+ "webui-pi-calibration": true,
598
+ "webui-context-auto-compaction": true,
599
+ "webui-branch-picker": true,
600
+ "webui-git-init": true,
601
+ "webui-sync-push": true,
602
+ "webui-changes-modal": true,
603
+ "webui-git-tools-modal": true,
604
+ "webui-model-picker": true,
605
+ "webui-thinking-picker": true,
606
+ "webui-changed-files-popover": true,
607
+ });
544
608
  const GIT_INIT_STACK_STORAGE_KEY = "pi-webui-git-init-stack";
545
609
  const STATS_WEBUI_STATUS_KEY = "stats-webui";
546
610
  const STATS_WEBUI_PAYLOAD_TYPE = "firstpick.pi-extension-stats.overlay";
@@ -569,6 +633,7 @@ const FILE_VIEWER_WIDTH_DEFAULT_PX = 520;
569
633
  const FILE_VIEWER_WIDTH_MIN_PX = 384;
570
634
  const FILE_VIEWER_CONTEXT_RADIUS_LINES = 6;
571
635
  const FILE_TREE_ROOT_PATH = "";
636
+ const FILE_TREE_DRAG_MIME = "application/x-pi-webui-file-path";
572
637
  const POINTER_ACTIVATION_SELECTOR = "button, a[href], input, select, textarea, summary, [role='button'], [tabindex]:not([tabindex='-1'])";
573
638
  const POINTER_ACTIVATION_RENDER_DEFER_MAX_MS = 1200;
574
639
  const PROMPT_HISTORY_LIMIT_PER_TAB = 50;
@@ -798,6 +863,38 @@ const OPTIONAL_FEATURES = [
798
863
  },
799
864
  ];
800
865
  const OPTIONAL_FEATURE_BY_ID = new Map(OPTIONAL_FEATURES.map((feature) => [feature.id, feature]));
866
+ const OPTIONAL_FEATURE_SECTIONS = [
867
+ {
868
+ id: "composer-commands",
869
+ label: "Composer & commands",
870
+ description: "Input helpers and lightweight commands that change how prompts and shell actions are launched.",
871
+ featureIds: ["bangCommandAutocomplete", "fishUserBash", "btwCommand"],
872
+ },
873
+ {
874
+ id: "workflows-releases",
875
+ label: "Workflows & releases",
876
+ description: "Guided workflows, task runners, and publishing actions with visible execution state.",
877
+ featureIds: ["gitWorkflow", "workflows", "releaseNpm", "releaseAur"],
878
+ },
879
+ {
880
+ id: "safety-access",
881
+ label: "Safety & access",
882
+ description: "Guardrails and network-facing helpers that affect trust boundaries.",
883
+ featureIds: ["safetyGuard", "remoteWebui"],
884
+ },
885
+ {
886
+ id: "widgets-native-parity",
887
+ label: "UI widgets & native parity",
888
+ description: "Status widgets, dashboards, themes, and browser access to terminal-native controls.",
889
+ featureIds: ["tuiSkillsCommand", "todoProgressWidget", "tuiToolsCommand", "gitFooterStatus", "statsCommand", "themeBundle"],
890
+ },
891
+ {
892
+ id: "conversation",
893
+ label: "Conversation",
894
+ description: "Talk and voice-oriented interaction modes.",
895
+ featureIds: ["naturalConversation"],
896
+ },
897
+ ];
801
898
  const OPTIONAL_COMMAND_FEATURES = new Map([
802
899
  ["bang-refresh", "bangCommandAutocomplete"],
803
900
  ["bang-status", "bangCommandAutocomplete"],
@@ -821,6 +918,7 @@ const OPTIONAL_COMMAND_FEATURES = new Map([
821
918
  ["conversation", "naturalConversation"],
822
919
  ["stats", "statsCommand"],
823
920
  ["git-footer-refresh", "gitFooterStatus"],
921
+ ["git-footer-visibility", "gitFooterStatus"],
824
922
  ["todo-progress-status", "todoProgressWidget"],
825
923
  ]);
826
924
  const HIDDEN_COMMAND_NAMES = new Set(["webui-tree-navigate", "webui-helper"]);
@@ -855,6 +953,8 @@ let optionalFeaturePackageStatusError = "";
855
953
  const gitFooterPayloadRefreshInFlightByTab = new Set();
856
954
  const gitFooterSyncPushInFlightByTab = new Set();
857
955
  const gitFooterPiCalibrationInFlightByTab = new Set();
956
+ let gitFooterVisibilityApplyInFlight = false;
957
+ let gitFooterVisibilityDirty = false;
858
958
 
859
959
  function createGitWorkflowActionsDone(patch = {}) {
860
960
  return {
@@ -5389,6 +5489,67 @@ function fileEntryIcon(entry = {}) {
5389
5489
  return "·";
5390
5490
  }
5391
5491
 
5492
+ function normalizeFileTreeGitStatus(status = {}) {
5493
+ if (!status || status.changed !== true) return null;
5494
+ const kind = ["changed", "modified", "staged", "untracked", "conflicted"].includes(String(status.kind || "")) ? String(status.kind) : "changed";
5495
+ return {
5496
+ changed: true,
5497
+ kind,
5498
+ status: String(status.status || "").slice(0, 4),
5499
+ direct: status.direct === true,
5500
+ changedDescendants: Math.max(0, Number(status.changedDescendants || 0) || 0),
5501
+ };
5502
+ }
5503
+
5504
+ function fileTreeGitStatusForEntry(entry = {}) {
5505
+ const own = normalizeFileTreeGitStatus(entry.gitStatus);
5506
+ if (own) return own;
5507
+ return fileTreeState.gitStatusByPath.get(normalizeFileTreePath(entry.path || "")) || null;
5508
+ }
5509
+
5510
+ function fileTreeGitStatusClasses(status) {
5511
+ const normalized = normalizeFileTreeGitStatus(status);
5512
+ if (!normalized) return "";
5513
+ return `git-changed git-${normalized.kind} ${normalized.direct ? "git-direct" : "git-descendants"}`;
5514
+ }
5515
+
5516
+ function fileTreeGitStatusTitle(status) {
5517
+ const normalized = normalizeFileTreeGitStatus(status);
5518
+ if (!normalized) return "";
5519
+ if (normalized.direct) {
5520
+ const state = normalized.status ? ` (${normalized.status})` : "";
5521
+ return `Git ${normalized.kind}${state}`;
5522
+ }
5523
+ const count = normalized.changedDescendants || 0;
5524
+ return count > 0 ? `Git changes in ${count} descendant${count === 1 ? "" : "s"}` : "Git changes in this folder";
5525
+ }
5526
+
5527
+ function fileTreeGitStatusBadge(status) {
5528
+ const normalized = normalizeFileTreeGitStatus(status);
5529
+ if (!normalized) return null;
5530
+ const label = normalized.direct ? (normalized.status || "●") : (normalized.changedDescendants > 1 ? `Δ${normalized.changedDescendants}` : "Δ");
5531
+ const badge = make("span", `file-tree-git-badge ${normalized.kind} ${normalized.direct ? "direct" : "descendants"}`, label);
5532
+ badge.title = fileTreeGitStatusTitle(normalized);
5533
+ badge.setAttribute("aria-label", badge.title);
5534
+ return badge;
5535
+ }
5536
+
5537
+ function updateFileTreeGitStatus(gitStatus, entries = []) {
5538
+ const next = new Map();
5539
+ for (const status of Array.isArray(gitStatus?.entries) ? gitStatus.entries : []) {
5540
+ const path = normalizeFileTreePath(status.path || "");
5541
+ const normalized = normalizeFileTreeGitStatus(status);
5542
+ if (path && normalized) next.set(path, normalized);
5543
+ }
5544
+ for (const entry of entries) {
5545
+ const path = normalizeFileTreePath(entry?.path || "");
5546
+ const normalized = normalizeFileTreeGitStatus(entry?.gitStatus);
5547
+ if (path && normalized) next.set(path, normalized);
5548
+ }
5549
+ fileTreeState.gitStatusRoot = String(gitStatus?.root || "");
5550
+ fileTreeState.gitStatusByPath = next;
5551
+ }
5552
+
5392
5553
  function setFileTreeStatus(message = "", level = "muted") {
5393
5554
  if (!elements.fileTreeStatus) return;
5394
5555
  elements.fileTreeStatus.textContent = message;
@@ -5402,7 +5563,7 @@ function setFileViewerStatus(message = "", level = "muted") {
5402
5563
  }
5403
5564
 
5404
5565
  function emptyFileTreeState(requestSerial = 0) {
5405
- return { root: "", entriesByPath: new Map(), expanded: new Set(), loading: new Set(), selectedPath: "", requestSerial, searchQuery: "", searchEntries: [], searchLoading: false, searchTruncated: false, searchTotal: 0 };
5566
+ return { root: "", entriesByPath: new Map(), expanded: new Set(), loading: new Set(), selectedPath: "", requestSerial, searchQuery: "", searchEntries: [], searchLoading: false, searchTruncated: false, searchTotal: 0, gitStatusRoot: "", gitStatusByPath: new Map() };
5406
5567
  }
5407
5568
 
5408
5569
  function fileTreeSearchQueryText() {
@@ -5489,7 +5650,9 @@ function renderFileTree() {
5489
5650
  function appendFileSearchEntry(parent, entry) {
5490
5651
  const path = normalizeFileTreePath(entry.path);
5491
5652
  const isDirectory = entry.type === "directory" || entry.directory === true;
5492
- const item = make("li", `file-tree-node file-tree-search-node ${entry.type || "file"}${fileTreeState.selectedPath === path ? " selected" : ""}`);
5653
+ const gitStatus = fileTreeGitStatusForEntry(entry);
5654
+ const gitStatusClasses = fileTreeGitStatusClasses(gitStatus);
5655
+ const item = make("li", `file-tree-node file-tree-search-node ${entry.type || "file"}${gitStatusClasses ? ` ${gitStatusClasses}` : ""}${fileTreeState.selectedPath === path ? " selected" : ""}`);
5493
5656
  item.setAttribute("role", "none");
5494
5657
  const button = make("button", "file-tree-item file-tree-search-item");
5495
5658
  button.type = "button";
@@ -5497,7 +5660,7 @@ function appendFileSearchEntry(parent, entry) {
5497
5660
  button.dataset.type = entry.type || "file";
5498
5661
  button.style.setProperty("--file-tree-depth", "0");
5499
5662
  button.setAttribute("role", "treeitem");
5500
- button.title = [path || ".", entry.error || ""].filter(Boolean).join("\n");
5663
+ button.title = [path || ".", fileTreeGitStatusTitle(gitStatus), entry.error || ""].filter(Boolean).join("\n");
5501
5664
  const label = make("span", "file-tree-search-label");
5502
5665
  label.append(
5503
5666
  make("span", "file-tree-name", entry.name || fileDisplayName(path)),
@@ -5507,6 +5670,8 @@ function appendFileSearchEntry(parent, entry) {
5507
5670
  make("span", "file-tree-icon", fileEntryIcon(entry)),
5508
5671
  label,
5509
5672
  );
5673
+ const gitBadge = fileTreeGitStatusBadge(gitStatus);
5674
+ if (gitBadge) button.append(gitBadge);
5510
5675
  if (entry.type === "file") button.append(make("span", "file-tree-kind", entry.extension || "file"));
5511
5676
  else if (entry.type && entry.type !== "directory") button.append(make("span", "file-tree-kind", entry.type));
5512
5677
  if (entry.error) button.append(make("span", "file-tree-error", entry.error));
@@ -5520,6 +5685,7 @@ function appendFileSearchEntry(parent, entry) {
5520
5685
  else if (entry.type === "file") openFileInViewer(path);
5521
5686
  });
5522
5687
  button.addEventListener("contextmenu", (event) => showFileContextMenu(event, entry));
5688
+ bindFileTreeDragAndDrop(button, item, entry);
5523
5689
  item.append(button);
5524
5690
  parent.append(item);
5525
5691
  }
@@ -5552,7 +5718,9 @@ function appendFileTreeEntry(parent, entry, depth = 0) {
5552
5718
  const isDirectory = entry.type === "directory" || entry.directory === true;
5553
5719
  const expanded = isDirectory && fileTreeState.expanded.has(path);
5554
5720
  const loading = isDirectory && fileTreeState.loading.has(path);
5555
- const item = make("li", `file-tree-node ${entry.type || "file"}${expanded ? " expanded" : ""}${fileTreeState.selectedPath === path ? " selected" : ""}`);
5721
+ const gitStatus = fileTreeGitStatusForEntry(entry);
5722
+ const gitStatusClasses = fileTreeGitStatusClasses(gitStatus);
5723
+ const item = make("li", `file-tree-node ${entry.type || "file"}${gitStatusClasses ? ` ${gitStatusClasses}` : ""}${expanded ? " expanded" : ""}${fileTreeState.selectedPath === path ? " selected" : ""}`);
5556
5724
  item.setAttribute("role", "none");
5557
5725
  const button = make("button", "file-tree-item");
5558
5726
  button.type = "button";
@@ -5561,11 +5729,13 @@ function appendFileTreeEntry(parent, entry, depth = 0) {
5561
5729
  button.style.setProperty("--file-tree-depth", String(depth));
5562
5730
  button.setAttribute("role", "treeitem");
5563
5731
  if (isDirectory) button.setAttribute("aria-expanded", expanded ? "true" : "false");
5564
- button.title = [path || ".", entry.error || ""].filter(Boolean).join("\n");
5732
+ button.title = [path || ".", fileTreeGitStatusTitle(gitStatus), entry.error || ""].filter(Boolean).join("\n");
5565
5733
  button.append(
5566
5734
  make("span", `file-tree-icon ${isDirectory && expanded ? "expanded" : ""}`, loading ? "…" : fileEntryIcon(entry)),
5567
5735
  make("span", "file-tree-name", entry.name || fileDisplayName(path)),
5568
5736
  );
5737
+ const gitBadge = fileTreeGitStatusBadge(gitStatus);
5738
+ if (gitBadge) button.append(gitBadge);
5569
5739
  if (entry.type === "file") button.append(make("span", "file-tree-kind", entry.extension || "file"));
5570
5740
  if (entry.error) button.append(make("span", "file-tree-error", entry.error));
5571
5741
  button.addEventListener("click", () => {
@@ -5579,6 +5749,7 @@ function appendFileTreeEntry(parent, entry, depth = 0) {
5579
5749
  else openFileInViewer(path);
5580
5750
  });
5581
5751
  button.addEventListener("contextmenu", (event) => showFileContextMenu(event, entry));
5752
+ bindFileTreeDragAndDrop(button, item, entry);
5582
5753
  item.append(button);
5583
5754
  if (isDirectory && expanded) {
5584
5755
  const children = fileTreeState.entriesByPath.get(path) || [];
@@ -5611,6 +5782,7 @@ async function loadFileTreeDirectory(path = FILE_TREE_ROOT_PATH, { force = false
5611
5782
  fileTreeState.expanded.clear();
5612
5783
  }
5613
5784
  const entries = Array.isArray(data.entries) ? data.entries : [];
5785
+ updateFileTreeGitStatus(data.gitStatus, entries);
5614
5786
  fileTreeState.entriesByPath.set(normalized, entries);
5615
5787
  setFileTreeStatus(fileTreeEntriesStatus(entries, { truncated: data.truncated, total: data.total || entries.length }));
5616
5788
  return entries;
@@ -5668,6 +5840,7 @@ async function runFileTreeSearch() {
5668
5840
  const data = response.data || {};
5669
5841
  const entries = Array.isArray(data.entries) ? data.entries : [];
5670
5842
  if (data.root) fileTreeState.root = data.root;
5843
+ updateFileTreeGitStatus(data.gitStatus, entries);
5671
5844
  fileTreeState.searchQuery = data.query || query;
5672
5845
  fileTreeState.searchEntries = entries;
5673
5846
  fileTreeState.searchLoading = false;
@@ -5768,6 +5941,352 @@ async function openPathInDefaultEditor(path = currentFileViewerPath()) {
5768
5941
  }
5769
5942
  }
5770
5943
 
5944
+ function filePathWithinOrEqual(filePath = "", parentPath = "") {
5945
+ const path = normalizeFileTreePath(filePath);
5946
+ const parent = normalizeFileTreePath(parentPath);
5947
+ if (!parent) return path === parent;
5948
+ return path === parent || path.startsWith(`${parent}/`);
5949
+ }
5950
+
5951
+ function remapFileTreePathAfterMove(filePath = "", sourcePath = "", destinationPath = "") {
5952
+ const path = normalizeFileTreePath(filePath);
5953
+ const source = normalizeFileTreePath(sourcePath);
5954
+ const destination = normalizeFileTreePath(destinationPath);
5955
+ if (!path || !source || !destination) return path;
5956
+ if (path === source) return destination;
5957
+ return path.startsWith(`${source}/`) ? `${destination}/${path.slice(source.length + 1)}` : path;
5958
+ }
5959
+
5960
+ function fileExtensionForPath(filePath = "") {
5961
+ const name = fileDisplayName(filePath);
5962
+ const dot = name.lastIndexOf(".");
5963
+ return dot > 0 ? name.slice(dot).toLowerCase() : "";
5964
+ }
5965
+
5966
+ function fileLanguageForPath(filePath = "") {
5967
+ const extension = fileExtensionForPath(filePath);
5968
+ return extension === ".md" || extension === ".markdown" ? "markdown" : "text";
5969
+ }
5970
+
5971
+ function fileOperationTypeLabel(entry = {}) {
5972
+ if (entry.type === "directory" || entry.directory === true) return "directory";
5973
+ if (entry.type === "file" || entry.file === true) return "file";
5974
+ return "entry";
5975
+ }
5976
+
5977
+ function fileTreeEntryIsMovable(entry = {}) {
5978
+ const path = normalizeFileTreePath(entry.path || "");
5979
+ return !!path && (entry.type === "file" || entry.file === true || entry.type === "directory" || entry.directory === true);
5980
+ }
5981
+
5982
+ function fileTreeEntryIsDirectory(entry = {}) {
5983
+ return entry.type === "directory" || entry.directory === true;
5984
+ }
5985
+
5986
+ function fileTreeDragSourceFromEvent(event) {
5987
+ const statePath = normalizeFileTreePath(fileTreeDragState?.sourcePath || "");
5988
+ return statePath ? { path: statePath, type: fileTreeDragState?.sourceType || "entry", entry: fileTreeDragState?.entry || null } : null;
5989
+ }
5990
+
5991
+ function fileTreeEntryFromElement(element) {
5992
+ const path = normalizeFileTreePath(element?.dataset?.path || "");
5993
+ const type = element?.dataset?.type || "";
5994
+ return path || type ? { path, type, directory: type === "directory", file: type === "file" } : null;
5995
+ }
5996
+
5997
+ function fileTreeDropTargetFromEvent(event) {
5998
+ const button = event?.target?.closest?.(".file-tree-item");
5999
+ if (!button || !elements.fileTreeRoot?.contains?.(button)) return null;
6000
+ const entry = fileTreeEntryFromElement(button);
6001
+ if (!entry || !fileTreeEntryIsDirectory(entry)) return null;
6002
+ return { entry, item: button.closest(".file-tree-node"), button };
6003
+ }
6004
+
6005
+ function fileTreeCanDropOnDirectory(sourcePath = "", targetDirectoryPath = "", sourceEntry = fileTreeDragState?.entry) {
6006
+ const source = normalizeFileTreePath(sourcePath);
6007
+ const target = normalizeFileTreePath(targetDirectoryPath);
6008
+ if (!source) return false;
6009
+ if (fileParentPath(source) === target) return false;
6010
+ if (fileTreeEntryIsDirectory(sourceEntry || {}) && (target === source || target.startsWith(`${source}/`))) return false;
6011
+ return true;
6012
+ }
6013
+
6014
+ function clearFileTreeDragVisuals() {
6015
+ for (const node of document.querySelectorAll(".file-tree-node.dragging, .file-tree-node.drop-target, .file-tree-node.drop-blocked")) {
6016
+ node.classList.remove("dragging", "drop-target", "drop-blocked");
6017
+ }
6018
+ elements.fileTreeRoot?.classList.remove("drag-root-drop", "drop-blocked");
6019
+ }
6020
+
6021
+ function finishFileTreeDrag() {
6022
+ clearFileTreeDragVisuals();
6023
+ fileTreeDragState = null;
6024
+ }
6025
+
6026
+ function beginFileTreeDrag(event, entry = {}, item) {
6027
+ if (!fileTreeEntryIsMovable(entry)) {
6028
+ event.preventDefault();
6029
+ return;
6030
+ }
6031
+ const sourcePath = normalizeFileTreePath(entry.path || "");
6032
+ closeFileContextMenu();
6033
+ fileTreeDragState = { sourcePath, sourceType: fileOperationTypeLabel(entry), entry: { ...entry, path: sourcePath } };
6034
+ event.dataTransfer.effectAllowed = "move";
6035
+ event.dataTransfer.setData(FILE_TREE_DRAG_MIME, sourcePath);
6036
+ event.dataTransfer.setData("text/plain", sourcePath);
6037
+ item?.classList.add("dragging");
6038
+ setFileTreeStatus(`Drag ${sourcePath} onto a folder or empty file-tree space to move it.`);
6039
+ }
6040
+
6041
+ function updateFileTreeDropTarget(event, entry = {}, item) {
6042
+ const source = fileTreeDragSourceFromEvent(event);
6043
+ if (!source || !fileTreeEntryIsDirectory(entry)) return false;
6044
+ const targetPath = normalizeFileTreePath(entry.path || "");
6045
+ const allowed = fileTreeCanDropOnDirectory(source.path, targetPath, source.entry);
6046
+ for (const node of document.querySelectorAll(".file-tree-node.drop-target, .file-tree-node.drop-blocked")) node.classList.remove("drop-target", "drop-blocked");
6047
+ elements.fileTreeRoot?.classList.remove("drag-root-drop", "drop-blocked");
6048
+ if (!allowed) {
6049
+ item?.classList.add("drop-blocked");
6050
+ event.dataTransfer.dropEffect = "none";
6051
+ return false;
6052
+ }
6053
+ event.preventDefault();
6054
+ event.stopPropagation();
6055
+ event.dataTransfer.dropEffect = "move";
6056
+ item?.classList.add("drop-target");
6057
+ if (fileTreeDragState) fileTreeDragState.targetPath = targetPath;
6058
+ return true;
6059
+ }
6060
+
6061
+ function clearFileTreeDropTarget(event, item) {
6062
+ if (!item?.contains?.(event.relatedTarget)) item?.classList.remove("drop-target", "drop-blocked");
6063
+ }
6064
+
6065
+ async function dropFileTreeEntry(event, entry = {}) {
6066
+ const source = fileTreeDragSourceFromEvent(event);
6067
+ if (!source || !fileTreeEntryIsDirectory(entry)) return;
6068
+ const targetPath = normalizeFileTreePath(entry.path || "");
6069
+ if (!fileTreeCanDropOnDirectory(source.path, targetPath, source.entry)) return;
6070
+ event.preventDefault();
6071
+ event.stopPropagation();
6072
+ finishFileTreeDrag();
6073
+ await moveFileTreeEntryToDestination(source.entry || { path: source.path, type: source.type }, targetPath, { viaDragDrop: true });
6074
+ }
6075
+
6076
+ function bindFileTreeDragAndDrop(button, item, entry = {}) {
6077
+ if (!button || !item) return;
6078
+ const movable = fileTreeEntryIsMovable(entry);
6079
+ button.draggable = movable;
6080
+ button.classList.toggle("file-tree-draggable", movable);
6081
+ if (movable) {
6082
+ button.addEventListener("dragstart", (event) => beginFileTreeDrag(event, entry, item));
6083
+ button.addEventListener("dragend", finishFileTreeDrag);
6084
+ }
6085
+ if (fileTreeEntryIsDirectory(entry)) {
6086
+ for (const target of [button, item]) {
6087
+ target.addEventListener("dragenter", (event) => updateFileTreeDropTarget(event, entry, item));
6088
+ target.addEventListener("dragover", (event) => updateFileTreeDropTarget(event, entry, item));
6089
+ target.addEventListener("dragleave", (event) => clearFileTreeDropTarget(event, item));
6090
+ target.addEventListener("drop", (event) => dropFileTreeEntry(event, entry).catch((error) => addEvent(error.message || String(error), "error")));
6091
+ }
6092
+ }
6093
+ }
6094
+
6095
+ function handleFileTreeRootDragOver(event) {
6096
+ const delegatedTarget = fileTreeDropTargetFromEvent(event);
6097
+ if (delegatedTarget) {
6098
+ updateFileTreeDropTarget(event, delegatedTarget.entry, delegatedTarget.item);
6099
+ return;
6100
+ }
6101
+ const source = fileTreeDragSourceFromEvent(event);
6102
+ if (!source) return;
6103
+ const allowed = fileTreeCanDropOnDirectory(source.path, FILE_TREE_ROOT_PATH, source.entry);
6104
+ elements.fileTreeRoot?.classList.toggle("drop-blocked", !allowed);
6105
+ if (!allowed) {
6106
+ event.dataTransfer.dropEffect = "none";
6107
+ return;
6108
+ }
6109
+ event.preventDefault();
6110
+ event.dataTransfer.dropEffect = "move";
6111
+ elements.fileTreeRoot?.classList.add("drag-root-drop");
6112
+ }
6113
+
6114
+ function handleFileTreeRootDragLeave(event) {
6115
+ if (elements.fileTreeRoot?.contains?.(event.relatedTarget)) return;
6116
+ elements.fileTreeRoot?.classList.remove("drag-root-drop", "drop-blocked");
6117
+ }
6118
+
6119
+ async function handleFileTreeRootDrop(event) {
6120
+ const delegatedTarget = fileTreeDropTargetFromEvent(event);
6121
+ if (delegatedTarget) {
6122
+ await dropFileTreeEntry(event, delegatedTarget.entry);
6123
+ return;
6124
+ }
6125
+ const source = fileTreeDragSourceFromEvent(event);
6126
+ if (!source || !fileTreeCanDropOnDirectory(source.path, FILE_TREE_ROOT_PATH, source.entry)) return;
6127
+ event.preventDefault();
6128
+ finishFileTreeDrag();
6129
+ await moveFileTreeEntryToDestination(source.entry || { path: source.path, type: source.type }, FILE_TREE_ROOT_PATH, { viaDragDrop: true });
6130
+ }
6131
+
6132
+ function clearFileTreeEntryCache(filePath = "") {
6133
+ const normalized = normalizeFileTreePath(filePath);
6134
+ if (!normalized) {
6135
+ fileTreeState.entriesByPath.clear();
6136
+ fileTreeState.expanded.clear();
6137
+ fileTreeState.loading.clear();
6138
+ return;
6139
+ }
6140
+ for (const key of [...fileTreeState.entriesByPath.keys()]) {
6141
+ if (key === normalized || key.startsWith(`${normalized}/`)) fileTreeState.entriesByPath.delete(key);
6142
+ }
6143
+ for (const key of [...fileTreeState.expanded]) {
6144
+ if (key === normalized || key.startsWith(`${normalized}/`)) fileTreeState.expanded.delete(key);
6145
+ }
6146
+ for (const key of [...fileTreeState.loading]) {
6147
+ if (key === normalized || key.startsWith(`${normalized}/`)) fileTreeState.loading.delete(key);
6148
+ }
6149
+ }
6150
+
6151
+ async function refreshFileTreeAfterOperation(paths = []) {
6152
+ if (fileTreeSearchQueryText()) {
6153
+ await runFileTreeSearch();
6154
+ return;
6155
+ }
6156
+ const uniquePaths = [...new Set(paths.map((item) => normalizeFileTreePath(item)))];
6157
+ if (!uniquePaths.length) {
6158
+ renderFileTree();
6159
+ return;
6160
+ }
6161
+ for (const path of uniquePaths) await loadFileTreeDirectory(path, { force: true });
6162
+ renderFileTree();
6163
+ }
6164
+
6165
+ function updateActiveFileViewerAfterMove(sourcePath = "", destinationPath = "") {
6166
+ if (!activeFileViewer) return;
6167
+ const currentPath = normalizeFileTreePath(activeFileViewer.path || "");
6168
+ const nextPath = remapFileTreePathAfterMove(currentPath, sourcePath, destinationPath);
6169
+ if (!nextPath || nextPath === currentPath) return;
6170
+ const language = fileLanguageForPath(nextPath);
6171
+ activeFileViewer = {
6172
+ ...activeFileViewer,
6173
+ path: nextPath,
6174
+ name: fileDisplayName(nextPath),
6175
+ extension: fileExtensionForPath(nextPath),
6176
+ language,
6177
+ mode: activeFileViewer.mode === "preview" && language === "markdown" ? "preview" : "source",
6178
+ };
6179
+ if (fileViewerSelection) fileViewerSelection = { ...fileViewerSelection, path: nextPath, fileName: activeFileViewer.name };
6180
+ updateFileViewerUi();
6181
+ }
6182
+
6183
+ function closeActiveFileViewerIfDeleted(deletedPath = "") {
6184
+ if (!activeFileViewer || !filePathWithinOrEqual(activeFileViewer.path, deletedPath)) return false;
6185
+ closeFileViewer();
6186
+ return true;
6187
+ }
6188
+
6189
+ async function deleteFileTreeEntry(entry = fileContextMenuState?.entry) {
6190
+ if (!entry) return;
6191
+ const sourcePath = normalizeFileTreePath(entry.path || "");
6192
+ if (!sourcePath) {
6193
+ addEvent("Workspace root cannot be deleted from the Files panel.", "warn");
6194
+ return;
6195
+ }
6196
+ const typeLabel = fileOperationTypeLabel(entry);
6197
+ const dirtyWarning = activeFileViewer?.dirty && filePathWithinOrEqual(activeFileViewer.path, sourcePath)
6198
+ ? "\n\nThe currently open file has unsaved edits that will be discarded from the viewer."
6199
+ : "";
6200
+ const recursiveWarning = typeLabel === "directory" ? "\n\nThis permanently deletes the directory and all of its contents." : "";
6201
+ if (!window.confirm(`Delete ${typeLabel} ${sourcePath}?${recursiveWarning}${dirtyWarning}\n\nThis cannot be undone.`)) return;
6202
+ const tabContext = activeTabContext();
6203
+ setFileTreeStatus(`Deleting ${sourcePath}…`);
6204
+ try {
6205
+ const response = await api("/api/files", { method: "DELETE", body: { path: sourcePath, confirmed: true }, tabId: tabContext.tabId });
6206
+ if (!isCurrentTabContext(tabContext)) return;
6207
+ const data = response.data || {};
6208
+ closeActiveFileViewerIfDeleted(sourcePath);
6209
+ clearFileTreeEntryCache(sourcePath);
6210
+ fileTreeState.selectedPath = "";
6211
+ await refreshFileTreeAfterOperation([data.parentPath ?? fileParentPath(sourcePath)]);
6212
+ setFileTreeStatus(`Deleted ${data.path || sourcePath}.`, "success");
6213
+ addEvent(`deleted ${data.path || sourcePath}`, "warn");
6214
+ } catch (error) {
6215
+ if (isCurrentTabContext(tabContext)) {
6216
+ setFileTreeStatus(error.message || String(error), "error");
6217
+ addEvent(`file delete failed: ${error.message || String(error)}`, "error");
6218
+ }
6219
+ }
6220
+ }
6221
+
6222
+ async function moveFileTreeEntryToDestination(entry = {}, destinationPath = "", { viaDragDrop = false, confirmMove = false } = {}) {
6223
+ const sourcePath = normalizeFileTreePath(entry.path || "");
6224
+ const normalizedDestination = normalizeFileTreePath(destinationPath);
6225
+ if (!sourcePath) {
6226
+ addEvent("Workspace root cannot be moved from the Files panel.", "warn");
6227
+ return;
6228
+ }
6229
+ if (!normalizedDestination && normalizedDestination !== FILE_TREE_ROOT_PATH) {
6230
+ addEvent("Destination path is required.", "warn");
6231
+ return;
6232
+ }
6233
+ const typeLabel = fileOperationTypeLabel(entry);
6234
+ if (confirmMove && !window.confirm(`Move ${typeLabel}?\n\nFrom: ${sourcePath}\nTo: ${normalizedDestination || "."}\n\nExisting destination paths are refused.`)) return;
6235
+ const tabContext = activeTabContext();
6236
+ const isDirectory = fileTreeEntryIsDirectory(entry);
6237
+ const restoreSourceExpanded = isDirectory && fileTreeState.expanded.has(sourcePath) && !fileTreeSearchQueryText();
6238
+ const expandDestinationDirectory = viaDragDrop && !fileTreeSearchQueryText();
6239
+ setFileTreeStatus(`Moving ${sourcePath}…`);
6240
+ try {
6241
+ const response = await api("/api/files/move", { method: "POST", body: { path: sourcePath, toPath: normalizedDestination || ".", confirmed: true }, tabId: tabContext.tabId });
6242
+ if (!isCurrentTabContext(tabContext)) return;
6243
+ const data = response.data || {};
6244
+ const nextPath = normalizeFileTreePath(data.destination || normalizedDestination);
6245
+ const sourceParent = data.parentPath ?? fileParentPath(sourcePath);
6246
+ const destinationParent = data.destinationParentPath ?? fileParentPath(nextPath);
6247
+ clearFileTreeEntryCache(sourcePath);
6248
+ clearFileTreeEntryCache(nextPath);
6249
+ if (restoreSourceExpanded && nextPath) fileTreeState.expanded.add(nextPath);
6250
+ if (expandDestinationDirectory) fileTreeState.expanded.add(normalizedDestination);
6251
+ fileTreeState.selectedPath = nextPath;
6252
+ updateActiveFileViewerAfterMove(sourcePath, nextPath);
6253
+ await refreshFileTreeAfterOperation([sourceParent, destinationParent]);
6254
+ if (restoreSourceExpanded && nextPath) await loadFileTreeDirectory(nextPath, { force: true });
6255
+ if (expandDestinationDirectory) await loadFileTreeDirectory(normalizedDestination, { force: true });
6256
+ renderFileTree();
6257
+ setFileTreeStatus(`Moved ${sourcePath} to ${nextPath}.`, "success");
6258
+ addEvent(`${viaDragDrop ? "drag-moved" : "moved"} ${sourcePath} to ${nextPath}`, "info");
6259
+ } catch (error) {
6260
+ if (isCurrentTabContext(tabContext)) {
6261
+ setFileTreeStatus(error.message || String(error), "error");
6262
+ addEvent(`file move failed: ${error.message || String(error)}`, "error");
6263
+ }
6264
+ }
6265
+ }
6266
+
6267
+ async function moveFileTreeEntry(entry = fileContextMenuState?.entry) {
6268
+ if (!entry) return;
6269
+ const sourcePath = normalizeFileTreePath(entry.path || "");
6270
+ if (!sourcePath) {
6271
+ addEvent("Workspace root cannot be moved from the Files panel.", "warn");
6272
+ return;
6273
+ }
6274
+ const typeLabel = fileOperationTypeLabel(entry);
6275
+ const destinationInput = window.prompt([
6276
+ `Move/rename ${typeLabel} ${sourcePath}`,
6277
+ "",
6278
+ "Enter a destination path inside the current workspace.",
6279
+ `Existing directories receive the ${typeLabel} as a child.`,
6280
+ ].join("\n"), sourcePath);
6281
+ if (destinationInput === null) return;
6282
+ const destinationPath = String(destinationInput || "").trim();
6283
+ if (!destinationPath) {
6284
+ addEvent("Destination path is required.", "warn");
6285
+ return;
6286
+ }
6287
+ await moveFileTreeEntryToDestination(entry, destinationPath, { confirmMove: true });
6288
+ }
6289
+
5771
6290
  function readStoredFileViewerWidth() {
5772
6291
  try {
5773
6292
  const width = Number.parseFloat(localStorage.getItem(FILE_VIEWER_WIDTH_STORAGE_KEY) || "");
@@ -6482,7 +7001,7 @@ function restoreActiveDraft() {
6482
7001
 
6483
7002
  function focusPromptInput({ defer = false } = {}) {
6484
7003
  const focus = () => {
6485
- if (!elements.promptInput || elements.dialog.open || elements.pathPickerDialog.open || elements.gitChangesDialog?.open || elements.commandPaletteDialog?.open || elements.editRetryDialog?.open || elements.nativeCommandDialog.open || elements.remoteQrDialog?.open || elements.appRunnerInfoDialog?.open || elements.promptListDialog?.open || elements.attachmentTextDialog?.open || elements.skillEditorDialog?.open || document.visibilityState === "hidden") return;
7004
+ if (!elements.promptInput || elements.dialog.open || elements.pathPickerDialog.open || elements.gitChangesDialog?.open || elements.commandPaletteDialog?.open || elements.editRetryDialog?.open || elements.nativeCommandDialog.open || elements.remoteQrDialog?.open || elements.appRunnerInfoDialog?.open || elements.gitFooterVisibilityDialog?.open || elements.promptListDialog?.open || elements.attachmentTextDialog?.open || elements.skillEditorDialog?.open || document.visibilityState === "hidden") return;
6486
7005
  try {
6487
7006
  elements.promptInput.focus({ preventScroll: true });
6488
7007
  } catch {
@@ -6647,6 +7166,7 @@ function resetActiveTabUi() {
6647
7166
  hideCommandSuggestions();
6648
7167
  cancelPendingDialogs();
6649
7168
  if (elements.nativeCommandDialog.open) closeNativeCommandDialog();
7169
+ if (elements.gitFooterVisibilityDialog?.open) closeGitFooterVisibilityDialog();
6650
7170
  if (pathPickerState) closePathPicker(null);
6651
7171
  bindGitWorkflowToActiveTab();
6652
7172
  resetChatOutput();
@@ -8329,6 +8849,297 @@ const GIT_FOOTER_TOOLTIP_COPY = {
8329
8849
  thinking: "Reasoning/thinking effort for this tab.",
8330
8850
  };
8331
8851
 
8852
+ const GIT_FOOTER_VISIBILITY_GROUPS = Object.freeze([
8853
+ {
8854
+ label: "Cards & chips",
8855
+ description: "Main footer cards and extra status chips rendered in the browser footer.",
8856
+ keys: ["tokens", "cache", "pi", "speed", "cost", "context", "cwd", "git", "git-state", "sync", "changes", "git-extra", "worktree", "model", "thinking", "context-meta"],
8857
+ },
8858
+ {
8859
+ label: "Git subitems",
8860
+ description: "Fine-grained pieces inside the Git branch, sync, changes, and git+ chips.",
8861
+ keys: ["git-branch-indicator", "git-detached", "git-operation", "git-ahead", "git-behind", "git-upstream", "git-staged", "git-unstaged", "git-untracked", "git-conflicted", "git-clean", "git-stash", "git-submodules", "git-worktrees", "git-tag", "git-last-commit-age", "git-signing-mismatch", "webui-fetch-state"],
8862
+ },
8863
+ {
8864
+ label: "WebUI actions & modals",
8865
+ description: "Buttons, pickers, popovers, and modal affordances attached to footer chips.",
8866
+ keys: ["webui-refresh-button", "webui-details-button", "webui-cwd-picker", "webui-pi-calibration", "webui-context-auto-compaction", "webui-branch-picker", "webui-git-init", "webui-sync-push", "webui-changes-modal", "webui-git-tools-modal", "webui-model-picker", "webui-thinking-picker", "webui-changed-files-popover"],
8867
+ },
8868
+ {
8869
+ label: "Native parity keys",
8870
+ description: "Keys shared with the native footer command set; these are kept for parity even when they have little browser-visible effect.",
8871
+ keys: ["cwd-branch", "git-status", "extension-statuses"],
8872
+ },
8873
+ ]);
8874
+ const GIT_FOOTER_VISIBILITY_GROUPED_KEYS = new Set(GIT_FOOTER_VISIBILITY_GROUPS.flatMap((group) => group.keys));
8875
+ const GIT_FOOTER_VISIBILITY_DIALOG_KEYS = Object.freeze([
8876
+ ...GIT_FOOTER_VISIBILITY_GROUPS.flatMap((group) => group.keys),
8877
+ ...Object.keys(GIT_FOOTER_WEBUI_VISIBILITY_DEFAULTS).filter((key) => !GIT_FOOTER_VISIBILITY_GROUPED_KEYS.has(key)),
8878
+ ]);
8879
+ const GIT_FOOTER_VISIBILITY_LABELS = Object.freeze({
8880
+ tokens: "Tokens card",
8881
+ cache: "Cache card",
8882
+ pi: "PI estimate card",
8883
+ speed: "Speed card",
8884
+ cost: "Cost card",
8885
+ context: "Context card",
8886
+ cwd: "Working directory chip",
8887
+ git: "Git branch chip",
8888
+ "git-state": "Git state chip",
8889
+ sync: "Sync chip",
8890
+ changes: "Changes chip",
8891
+ "git-extra": "Git+ chip",
8892
+ worktree: "Worktree chip",
8893
+ model: "Model chip",
8894
+ thinking: "Thinking chip",
8895
+ "context-meta": "Context meta chip",
8896
+ "git-branch-indicator": "Branch indicator",
8897
+ "git-detached": "Detached marker",
8898
+ "git-operation": "Operation marker",
8899
+ "git-ahead": "Ahead count",
8900
+ "git-behind": "Behind count",
8901
+ "git-upstream": "Upstream name",
8902
+ "git-staged": "Staged count",
8903
+ "git-unstaged": "Unstaged count",
8904
+ "git-untracked": "Untracked count",
8905
+ "git-conflicted": "Conflicted count",
8906
+ "git-clean": "Clean marker",
8907
+ "git-stash": "Stash count",
8908
+ "git-submodules": "Submodule state",
8909
+ "git-worktrees": "Worktree count",
8910
+ "git-tag": "HEAD tag",
8911
+ "git-last-commit-age": "Last commit age",
8912
+ "git-signing-mismatch": "Signing mismatch",
8913
+ "webui-fetch-state": "Fetch state",
8914
+ "webui-refresh-button": "Refresh button",
8915
+ "webui-details-button": "Details button",
8916
+ "webui-cwd-picker": "CWD picker",
8917
+ "webui-pi-calibration": "PI calibration action",
8918
+ "webui-context-auto-compaction": "Auto-compaction action",
8919
+ "webui-branch-picker": "Branch/worktree picker",
8920
+ "webui-git-init": "Git init affordance",
8921
+ "webui-sync-push": "Sync push action",
8922
+ "webui-changes-modal": "Changes modal",
8923
+ "webui-git-tools-modal": "Git tools modal",
8924
+ "webui-model-picker": "Model picker",
8925
+ "webui-thinking-picker": "Thinking picker",
8926
+ "webui-changed-files-popover": "Changed-files popover",
8927
+ "cwd-branch": "CWD branch suffix",
8928
+ "git-status": "Native git status line",
8929
+ "extension-statuses": "Extension status line",
8930
+ });
8931
+ const GIT_FOOTER_VISIBILITY_HINTS = Object.freeze({
8932
+ "context-meta": "Secondary context chip shown in the footer details row.",
8933
+ "git-branch-indicator": "Optional branch glyph/name inside the generated git state section; off by default in WebUI.",
8934
+ "git-detached": "Detached-HEAD warning inside the git state chip.",
8935
+ "git-operation": "Merge/rebase/cherry-pick/revert/bisect operation text inside the git state chip.",
8936
+ "git-ahead": "Outgoing commit count inside the sync chip.",
8937
+ "git-behind": "Incoming commit count inside the sync/changes chips.",
8938
+ "git-upstream": "Tracked upstream branch name inside the sync chip.",
8939
+ "git-staged": "Staged-file count inside the changes chip.",
8940
+ "git-unstaged": "Modified-but-unstaged count inside the changes chip.",
8941
+ "git-untracked": "Untracked-file count inside the changes chip.",
8942
+ "git-conflicted": "Conflict count inside the changes chip.",
8943
+ "git-clean": "Clean working-tree checkmark inside the changes chip.",
8944
+ "git-stash": "Stash count inside the git+ chip.",
8945
+ "git-submodules": "Dirty submodule count inside the git+ chip.",
8946
+ "git-worktrees": "Repository worktree count inside the git+ chip.",
8947
+ "git-tag": "Tag at HEAD inside the git+ chip.",
8948
+ "git-last-commit-age": "Last-commit age inside the git+ chip.",
8949
+ "git-signing-mismatch": "Signing-key mismatch marker inside the git+ chip.",
8950
+ "webui-fetch-state": "Fetch progress/success/error marker in the changes chip.",
8951
+ "webui-refresh-button": "Floating footer refresh button.",
8952
+ "webui-details-button": "Mobile/details-row expander button.",
8953
+ "webui-cwd-picker": "Click action on the working-directory chip.",
8954
+ "webui-pi-calibration": "Click action on the PI card for calibration/probe commands.",
8955
+ "webui-context-auto-compaction": "Click action on context chips for auto-compaction.",
8956
+ "webui-branch-picker": "Click action on the git branch/worktree chips.",
8957
+ "webui-git-init": "Git initialization affordance when a tab has no repository.",
8958
+ "webui-sync-push": "Click-to-push action on outgoing sync chips.",
8959
+ "webui-changes-modal": "Click action opening the changes/conflicts modal.",
8960
+ "webui-git-tools-modal": "Click action opening extra git tools.",
8961
+ "webui-model-picker": "Click action opening the footer model picker.",
8962
+ "webui-thinking-picker": "Click action opening the thinking-effort picker.",
8963
+ "webui-changed-files-popover": "Hover/focus popover listing changed files from the changes chip.",
8964
+ "cwd-branch": "Native footer branch suffix for the cwd text; included here for command parity.",
8965
+ "git-status": "Native footer git status status-entry gate; included here for command parity.",
8966
+ "extension-statuses": "Native footer extension-status gate; included here for command parity.",
8967
+ });
8968
+
8969
+ function gitFooterVisibilityLabel(key) {
8970
+ return GIT_FOOTER_VISIBILITY_LABELS[key] || String(key).split("-").map((part) => part ? `${part[0].toUpperCase()}${part.slice(1)}` : part).join(" ");
8971
+ }
8972
+
8973
+ function gitFooterVisibilityHint(key) {
8974
+ return GIT_FOOTER_VISIBILITY_HINTS[key] || GIT_FOOTER_TOOLTIP_COPY[key] || `Controls the ${key} footer visibility key for the Web UI.`;
8975
+ }
8976
+
8977
+ function gitFooterVisibilityCommandName() {
8978
+ return resolveAvailableCommandName("git-footer-visibility", { rpcOnly: true });
8979
+ }
8980
+
8981
+ function gitFooterVisibilityCommandAvailable() {
8982
+ return !!gitFooterVisibilityCommandName();
8983
+ }
8984
+
8985
+ function currentGitFooterVisibilityState() {
8986
+ return normalizeGitFooterWebuiVisibility(parseGitFooterWebuiPayload()?.visibility);
8987
+ }
8988
+
8989
+ function setGitFooterVisibilityStatus(message = "", level = "muted") {
8990
+ if (!elements.gitFooterVisibilityStatus) return;
8991
+ elements.gitFooterVisibilityStatus.textContent = message;
8992
+ elements.gitFooterVisibilityStatus.className = `git-footer-visibility-status ${level || "muted"}`;
8993
+ elements.gitFooterVisibilityStatus.hidden = !message;
8994
+ }
8995
+
8996
+ function setGitFooterVisibilityBusy(busy) {
8997
+ gitFooterVisibilityApplyInFlight = !!busy;
8998
+ const commandAvailable = gitFooterVisibilityCommandAvailable();
8999
+ for (const button of [elements.gitFooterVisibilityApplyButton, elements.gitFooterVisibilityResetButton]) {
9000
+ if (button) button.disabled = gitFooterVisibilityApplyInFlight || !commandAvailable;
9001
+ }
9002
+ const inputs = elements.gitFooterVisibilityBody?.querySelectorAll("input[data-git-footer-visibility-key]") || [];
9003
+ for (const input of inputs) input.disabled = gitFooterVisibilityApplyInFlight || !commandAvailable;
9004
+ for (const button of [elements.gitFooterVisibilitySelectAllButton, elements.gitFooterVisibilitySelectNoneButton]) {
9005
+ if (button) button.disabled = gitFooterVisibilityApplyInFlight || !commandAvailable;
9006
+ }
9007
+ if (elements.gitFooterVisibilityCloseButton) elements.gitFooterVisibilityCloseButton.disabled = gitFooterVisibilityApplyInFlight;
9008
+ }
9009
+
9010
+ function renderGitFooterVisibilityToggle(key, visibility) {
9011
+ const label = make("label", "toggle-control git-footer-visibility-toggle");
9012
+ const input = make("input");
9013
+ input.type = "checkbox";
9014
+ input.checked = visibility[key] ?? true;
9015
+ input.dataset.gitFooterVisibilityKey = key;
9016
+ input.addEventListener("change", () => {
9017
+ gitFooterVisibilityDirty = true;
9018
+ setGitFooterVisibilityStatus("Unsaved WebUI footer visibility changes.", "warn");
9019
+ });
9020
+ const text = make("span", "git-footer-visibility-toggle-text");
9021
+ text.append(
9022
+ make("span", "toggle-control-label", gitFooterVisibilityLabel(key)),
9023
+ make("span", "toggle-control-hint", gitFooterVisibilityHint(key)),
9024
+ make("code", "git-footer-visibility-key", key),
9025
+ );
9026
+ label.append(input, text);
9027
+ return label;
9028
+ }
9029
+
9030
+ function renderGitFooterVisibilityDialog() {
9031
+ if (!elements.gitFooterVisibilityBody) return;
9032
+ const visibility = currentGitFooterVisibilityState();
9033
+ elements.gitFooterVisibilityBody.replaceChildren();
9034
+ for (const group of GIT_FOOTER_VISIBILITY_GROUPS) {
9035
+ const section = make("section", "git-footer-visibility-group");
9036
+ const header = make("div", "git-footer-visibility-group-header");
9037
+ header.append(make("h3", "", group.label), make("p", "muted", group.description));
9038
+ const grid = make("div", "git-footer-visibility-grid");
9039
+ for (const key of group.keys) grid.append(renderGitFooterVisibilityToggle(key, visibility));
9040
+ section.append(header, grid);
9041
+ elements.gitFooterVisibilityBody.append(section);
9042
+ }
9043
+ setGitFooterVisibilityBusy(gitFooterVisibilityApplyInFlight);
9044
+ if (!gitFooterVisibilityDirty) {
9045
+ setGitFooterVisibilityStatus(
9046
+ gitFooterVisibilityCommandAvailable()
9047
+ ? "Runtime changes last until Pi/package restart. Use PI_GIT_FOOTER_WEBUI_HIDE or per-key env vars for persistence."
9048
+ : commandUnavailableMessage("git-footer-visibility"),
9049
+ gitFooterVisibilityCommandAvailable() ? "muted" : "warn",
9050
+ );
9051
+ }
9052
+ }
9053
+
9054
+ function readGitFooterVisibilitySelection() {
9055
+ const next = currentGitFooterVisibilityState();
9056
+ const inputs = elements.gitFooterVisibilityBody?.querySelectorAll("input[data-git-footer-visibility-key]") || [];
9057
+ for (const input of inputs) {
9058
+ const key = input.dataset.gitFooterVisibilityKey;
9059
+ if (key && key in next) next[key] = input.checked;
9060
+ }
9061
+ return next;
9062
+ }
9063
+
9064
+ async function runGitFooterVisibilityCommand(action, keys = []) {
9065
+ const commandName = gitFooterVisibilityCommandName();
9066
+ if (!commandName) throw new Error(commandUnavailableMessage("git-footer-visibility"));
9067
+ const suffix = keys.length > 0 ? ` ${keys.join(" ")}` : "";
9068
+ await sendPrompt("prompt", `/${commandName} ${action} webui${suffix}`, { targetTabId: activeTabId, throwOnError: true });
9069
+ }
9070
+
9071
+ async function applyGitFooterVisibilityDialog() {
9072
+ if (gitFooterVisibilityApplyInFlight) return;
9073
+ const current = currentGitFooterVisibilityState();
9074
+ const next = readGitFooterVisibilitySelection();
9075
+ const show = [];
9076
+ const hide = [];
9077
+ for (const key of GIT_FOOTER_VISIBILITY_DIALOG_KEYS) {
9078
+ if (next[key] === current[key]) continue;
9079
+ if (next[key]) show.push(key);
9080
+ else hide.push(key);
9081
+ }
9082
+ if (show.length === 0 && hide.length === 0) {
9083
+ gitFooterVisibilityDirty = false;
9084
+ setGitFooterVisibilityStatus("No footer visibility changes to apply.", "muted");
9085
+ return;
9086
+ }
9087
+
9088
+ setGitFooterVisibilityBusy(true);
9089
+ setGitFooterVisibilityStatus("Applying WebUI footer visibility…", "muted");
9090
+ try {
9091
+ if (hide.length) await runGitFooterVisibilityCommand("hide", hide);
9092
+ if (show.length) await runGitFooterVisibilityCommand("show", show);
9093
+ gitFooterVisibilityDirty = false;
9094
+ setGitFooterVisibilityStatus(`Applied ${hide.length + show.length} WebUI footer visibility change${hide.length + show.length === 1 ? "" : "s"}.`, "success");
9095
+ requestGitFooterWebuiPayload(activeTabContext(), { force: true, allowDuringRun: true });
9096
+ renderFooter();
9097
+ } catch (error) {
9098
+ setGitFooterVisibilityStatus(error.message || String(error), "error");
9099
+ } finally {
9100
+ setGitFooterVisibilityBusy(false);
9101
+ }
9102
+ }
9103
+
9104
+ async function resetGitFooterVisibilityDialog() {
9105
+ if (gitFooterVisibilityApplyInFlight) return;
9106
+ setGitFooterVisibilityBusy(true);
9107
+ setGitFooterVisibilityStatus("Resetting WebUI footer visibility…", "muted");
9108
+ try {
9109
+ await runGitFooterVisibilityCommand("reset");
9110
+ gitFooterVisibilityDirty = false;
9111
+ setGitFooterVisibilityStatus("Reset WebUI footer visibility overrides.", "success");
9112
+ requestGitFooterWebuiPayload(activeTabContext(), { force: true, allowDuringRun: true });
9113
+ } catch (error) {
9114
+ setGitFooterVisibilityStatus(error.message || String(error), "error");
9115
+ } finally {
9116
+ setGitFooterVisibilityBusy(false);
9117
+ }
9118
+ }
9119
+
9120
+ function setGitFooterVisibilitySelection(checked) {
9121
+ const inputs = elements.gitFooterVisibilityBody?.querySelectorAll("input[data-git-footer-visibility-key]") || [];
9122
+ for (const input of inputs) input.checked = !!checked;
9123
+ gitFooterVisibilityDirty = true;
9124
+ setGitFooterVisibilityStatus(checked ? "Selected all WebUI footer options." : "Deselected all WebUI footer options.", "warn");
9125
+ }
9126
+
9127
+ function openGitFooterVisibilityDialog() {
9128
+ if (!elements.gitFooterVisibilityDialog) return;
9129
+ setOptionsMenuOpen(false);
9130
+ hideFooterTooltip();
9131
+ gitFooterVisibilityDirty = false;
9132
+ renderGitFooterVisibilityDialog();
9133
+ if (!elements.gitFooterVisibilityDialog.open) elements.gitFooterVisibilityDialog.showModal();
9134
+ queueMicrotask(() => elements.gitFooterVisibilityBody?.querySelector("input")?.focus());
9135
+ }
9136
+
9137
+ function closeGitFooterVisibilityDialog() {
9138
+ gitFooterVisibilityDirty = false;
9139
+ gitFooterVisibilityApplyInFlight = false;
9140
+ if (elements.gitFooterVisibilityDialog?.open) elements.gitFooterVisibilityDialog.close();
9141
+ }
9142
+
8332
9143
  function cleanFooterPayloadText(value, fallback = "", maxLength = 240) {
8333
9144
  const text = cleanStatusText(value).slice(0, maxLength);
8334
9145
  return text || fallback;
@@ -8349,6 +9160,30 @@ function normalizeFooterPayloadChangedFile(value) {
8349
9160
  return file;
8350
9161
  }
8351
9162
 
9163
+ function normalizeGitFooterWebuiVisibility(value) {
9164
+ const visibility = { ...GIT_FOOTER_WEBUI_VISIBILITY_DEFAULTS };
9165
+ if (!value || typeof value !== "object") return visibility;
9166
+ for (const key of Object.keys(visibility)) {
9167
+ if (typeof value[key] === "boolean") visibility[key] = value[key];
9168
+ }
9169
+ return visibility;
9170
+ }
9171
+
9172
+ function gitFooterPayloadVisible(payload, key) {
9173
+ if (!key) return true;
9174
+ if (typeof payload?.visibility?.[key] === "boolean") return payload.visibility[key];
9175
+ return GIT_FOOTER_WEBUI_VISIBILITY_DEFAULTS[key] ?? true;
9176
+ }
9177
+
9178
+ function currentGitFooterPayloadVisible(key) {
9179
+ return gitFooterPayloadVisible(parseGitFooterWebuiPayload(), key);
9180
+ }
9181
+
9182
+ function gitFooterPayloadVisibilityKey(payload) {
9183
+ const visibility = normalizeGitFooterWebuiVisibility(payload?.visibility);
9184
+ return Object.keys(visibility).sort().map((key) => `${key}:${visibility[key] ? 1 : 0}`).join("|");
9185
+ }
9186
+
8352
9187
  function normalizeFooterPayloadChip(value, index) {
8353
9188
  if (!value || typeof value !== "object") return null;
8354
9189
  const key = cleanFooterPayloadText(value.key, `item-${index}`).replace(/[^a-z0-9_.:-]/gi, "-").slice(0, 64) || `item-${index}`;
@@ -8364,7 +9199,14 @@ function normalizeFooterPayloadChip(value, index) {
8364
9199
  if (FOOTER_PAYLOAD_ACTIONS.has(value.action)) chip.action = value.action;
8365
9200
  if (Array.isArray(value.files)) {
8366
9201
  const files = value.files.map(normalizeFooterPayloadChangedFile).filter(Boolean).slice(0, 80);
8367
- if (files.length) chip.files = files;
9202
+ if (files.length) {
9203
+ chip.files = files;
9204
+ const filesTotal = Number(value.filesTotal);
9205
+ if (value.filesTruncated === true && Number.isFinite(filesTotal) && filesTotal > files.length) {
9206
+ chip.filesTotal = filesTotal;
9207
+ chip.filesTruncated = true;
9208
+ }
9209
+ }
8368
9210
  }
8369
9211
  if (value.contextUsage && typeof value.contextUsage === "object") {
8370
9212
  const percent = typeof value.contextUsage.percent === "number" ? value.contextUsage.percent : Number.NaN;
@@ -8389,8 +9231,9 @@ function parseGitFooterWebuiPayloadRaw(raw) {
8389
9231
  if (!parsed || parsed.type !== GIT_FOOTER_WEBUI_PAYLOAD_TYPE || parsed.version !== GIT_FOOTER_WEBUI_PAYLOAD_VERSION) return null;
8390
9232
  const main = Array.isArray(parsed.main) ? parsed.main.map(normalizeFooterPayloadChip).filter(Boolean).slice(0, 8) : [];
8391
9233
  const meta = Array.isArray(parsed.meta) ? parsed.meta.map(normalizeFooterPayloadChip).filter(Boolean).slice(0, 10) : [];
8392
- if (!main.length && !meta.length) return null;
8393
- return { main, meta };
9234
+ const visibility = normalizeGitFooterWebuiVisibility(parsed.visibility);
9235
+ if (!main.length && !meta.length && !parsed.visibility) return null;
9236
+ return { main, meta, visibility };
8394
9237
  } catch {
8395
9238
  return null;
8396
9239
  }
@@ -8493,14 +9336,23 @@ function parseGitFooterWebuiPayload() {
8493
9336
  return parseGitFooterWebuiPayloadRaw(readCachedGitFooterWebuiPayloadRaw());
8494
9337
  }
8495
9338
 
9339
+ function footerPayloadChipVisible(payload, chip, area = "main") {
9340
+ if (!chip?.key) return true;
9341
+ if (area === "meta" && chip.key === "context") return gitFooterPayloadVisible(payload, "context-meta");
9342
+ return gitFooterPayloadVisible(payload, chip.key);
9343
+ }
9344
+
8496
9345
  function footerPayloadWithLiveModel(payload) {
8497
9346
  if (!payload) return payload;
9347
+ const visible = (key) => gitFooterPayloadVisible(payload, key);
9348
+ const mainSource = payload.main.filter((chip) => footerPayloadChipVisible(payload, chip, "main"));
9349
+ const metaSource = payload.meta.filter((chip) => footerPayloadChipVisible(payload, chip, "meta"));
8498
9350
  const model = currentState?.model ? shortModelLabel(currentState.model) : "";
8499
9351
  const effort = footerThinkingDisplay();
8500
9352
  const workspace = normalizeGitWorkspaceInfo(activeTab()?.gitWorkspace);
8501
9353
  const worktreeLabel = gitWorkspaceBadgeLabel(workspace);
8502
- const hasThinkingChip = [...payload.main, ...payload.meta].some((chip) => chip?.key === "thinking");
8503
- const hasWorktreeChip = [...payload.main, ...payload.meta].some((chip) => chip?.key === "worktree");
9354
+ const hasThinkingChip = [...mainSource, ...metaSource].some((chip) => chip?.key === "thinking");
9355
+ const hasWorktreeChip = [...mainSource, ...metaSource].some((chip) => chip?.key === "worktree");
8504
9356
  const contextChip = (chip) => {
8505
9357
  const usageUnknown = contextUsageUnknownAfterCompaction();
8506
9358
  const value = usageUnknown ? footerContextDisplayWithAuto(unknownFooterContextText(chip?.contextUsage)) : footerContextDisplayWithAuto(chip?.value);
@@ -8511,16 +9363,17 @@ function footerPayloadWithLiveModel(payload) {
8511
9363
  const worktreeChip = () => ({ key: "worktree", label: "worktree", value: worktreeLabel, icon: "🌳", tone: workspace?.isMainWorktree ? "teal" : "green", title: workspace?.worktreePath || "Git worktree" });
8512
9364
  const splitChip = (chip) => {
8513
9365
  if (chip?.key === "context") return [contextChip(chip)];
8514
- if (chip?.key === "thinking") return [effortChip(chip)];
9366
+ if (chip?.key === "thinking") return visible("thinking") ? [effortChip(chip)] : [];
8515
9367
  if (chip?.key !== "model" || !model) return [chip];
8516
9368
  const modelChip = { ...chip, value: model, title: `model: ${model}` };
8517
- return hasThinkingChip ? [modelChip] : [modelChip, effortChip(chip)];
9369
+ return hasThinkingChip || !visible("thinking") ? [modelChip] : [modelChip, effortChip(chip)];
8518
9370
  };
8519
- const meta = payload.meta.flatMap(splitChip);
8520
- if (worktreeLabel && !hasWorktreeChip) meta.splice(Math.min(meta.length, 2), 0, worktreeChip());
9371
+ const meta = metaSource.flatMap(splitChip);
9372
+ if (visible("worktree") && worktreeLabel && !hasWorktreeChip) meta.splice(Math.min(meta.length, 2), 0, worktreeChip());
8521
9373
  return {
8522
- main: payload.main.flatMap(splitChip),
9374
+ main: mainSource.flatMap(splitChip),
8523
9375
  meta,
9376
+ visibility: payload.visibility,
8524
9377
  };
8525
9378
  }
8526
9379
 
@@ -8637,26 +9490,29 @@ function renderChangedFilesGroup(kind, files) {
8637
9490
  return group;
8638
9491
  }
8639
9492
 
8640
- function applyFooterChangedFilesDropdown(node, chip) {
8641
- if (chip?.key !== "changes" || !Array.isArray(chip.files) || chip.files.length === 0) return node;
9493
+ function applyFooterChangedFilesDropdown(node, chip, payload) {
9494
+ if (!gitFooterPayloadVisible(payload, "webui-changed-files-popover") || chip?.key !== "changes" || !Array.isArray(chip.files) || chip.files.length === 0) return node;
8642
9495
  node.classList.add("footer-changes-with-files");
8643
9496
  node.tabIndex = 0;
8644
9497
  node.removeAttribute("data-tooltip");
8645
9498
  node.setAttribute("aria-label", `changes: ${chip.value}. Hover or focus to choose changed files. Click a file to add it as an @ reference.`);
8646
9499
 
8647
9500
  const popover = make("span", "footer-changed-files-popover");
8648
- popover.append(make("span", "footer-changed-files-title", "Changed files"));
9501
+ popover.append(make("span", "footer-changed-files-title", chip.filesTruncated ? `Changed files (showing ${chip.files.length} of ${chip.filesTotal})` : "Changed files"));
8649
9502
  for (const kind of FOOTER_CHANGED_FILE_KIND_ORDER) {
8650
9503
  const group = renderChangedFilesGroup(kind, chip.files.filter((file) => file.kind === kind));
8651
9504
  if (group) popover.append(group);
8652
9505
  }
9506
+ if (chip.filesTruncated) popover.append(make("span", "footer-changed-files-truncated", `${chip.filesTotal - chip.files.length} more files not shown; open the Git Changes dialog for the full list.`));
8653
9507
  node.append(popover);
8654
9508
  return node;
8655
9509
  }
8656
9510
 
8657
- function renderGitFooterPayloadMetric(chip) {
9511
+ function renderGitFooterPayloadMetric(chip, payload) {
8658
9512
  const options = { tooltipAlign: gitFooterTooltipAlign(chip) };
8659
- const action = applyGitFooterPiCalibrationOptions(chip, options) || applyGitFooterContextToggleOptions(chip, options);
9513
+ const piAction = gitFooterPayloadVisible(payload, "webui-pi-calibration") ? applyGitFooterPiCalibrationOptions(chip, options) : "";
9514
+ const contextAction = gitFooterPayloadVisible(payload, "webui-context-auto-compaction") ? applyGitFooterContextToggleOptions(chip, options) : "";
9515
+ const action = piAction || contextAction;
8660
9516
  options.title = gitFooterPayloadTooltip(chip, { action });
8661
9517
  const node = footerMetric(chip.icon || "•", chip.label, chip.value, chip.tone ? `tone-${chip.tone}` : "", options);
8662
9518
  return chip.contextUsage ? applyFooterContextUsage(node, chip.contextUsage) : node;
@@ -8671,6 +9527,12 @@ function gitFooterSyncChipHasOutgoing(chip) {
8671
9527
  return chip?.key === "sync" && gitFooterSyncOutgoingCount(chip.value) > 0;
8672
9528
  }
8673
9529
 
9530
+ function gitFooterCurrentBranch() {
9531
+ const gitChip = parseGitFooterWebuiPayload()?.meta?.find((chip) => chip.key === "git");
9532
+ const value = cleanFooterPayloadText(gitChip?.value, "").toLowerCase();
9533
+ return value && value !== "no repo" ? cleanFooterPayloadText(gitChip.value, "") : "";
9534
+ }
9535
+
8674
9536
  async function pushGitFooterSync(tabId = activeTabId, syncValue = "") {
8675
9537
  if (!tabId || gitFooterSyncPushInFlightByTab.has(tabId)) return;
8676
9538
  const outgoing = gitFooterSyncOutgoingCount(syncValue);
@@ -8679,14 +9541,47 @@ async function pushGitFooterSync(tabId = activeTabId, syncValue = "") {
8679
9541
  const tab = tabs.find((item) => item.id === tabId);
8680
9542
  const target = tab?.title || tab?.cwd || "this tab";
8681
9543
  hideFooterTooltip();
8682
- if (!window.confirm(`Run git push for ${outgoing} outgoing commit${outgoing === 1 ? "" : "s"} in ${target}?`)) return;
9544
+ const branch = gitFooterCurrentBranch();
9545
+ const protectedWarning = ["main", "master"].includes(branch)
9546
+ ? `\n\nWarning: ${branch} is usually a protected/shared branch. Consider pushing a feature branch and opening a PR instead.`
9547
+ : "";
9548
+ if (!window.confirm(`Run git push for ${outgoing} outgoing commit${outgoing === 1 ? "" : "s"} in ${target}?${protectedWarning}`)) return;
8683
9549
 
8684
9550
  gitFooterSyncPushInFlightByTab.add(tabId);
8685
9551
  if (isCurrentTabContext(tabContext)) renderFooter();
8686
9552
  try {
8687
9553
  const response = await api("/api/git-workflow/push", { method: "POST", body: {}, tabId });
8688
9554
  if (!response.ok) {
8689
- const detail = [response.error, formatGitCommandResult(response.data)].filter(Boolean).join("\n\n").trim();
9555
+ if (response.code === "NO_UPSTREAM") {
9556
+ const publish = window.confirm(`${response.error}\n\n${response.hint || ""}\n\nRun git push -u to publish ${branch || "the current branch"} and set its upstream?`);
9557
+ if (publish) {
9558
+ const upstreamResponse = await api("/api/git-workflow/push", { method: "POST", body: { setUpstream: true }, tabId });
9559
+ if (!upstreamResponse.ok) throw new Error([upstreamResponse.error, upstreamResponse.hint].filter(Boolean).join("\n"));
9560
+ addEvent(`Published ${upstreamResponse.data?.branch || "branch"} to ${upstreamResponse.data?.remote || "the remote"} and set its upstream.`, "success");
9561
+ requestGitFooterWebuiPayload(tabContext, { force: true });
9562
+ return;
9563
+ }
9564
+ throw new Error([response.error, response.hint].filter(Boolean).join("\n"));
9565
+ }
9566
+ if (response.code === "NON_FAST_FORWARD") {
9567
+ const forcePush = window.confirm([
9568
+ response.error,
9569
+ "",
9570
+ response.hint || "",
9571
+ "",
9572
+ "Recommended: open the Git Changes dialog, fetch, and review the incoming diff first.",
9573
+ `DANGER: force-push ${branch || "the current branch"} with --force-with-lease instead? This rewrites the remote branch (but still refuses if the remote moved past what you fetched).`,
9574
+ ].join("\n"));
9575
+ if (forcePush) {
9576
+ const forceResponse = await api("/api/git-workflow/push", { method: "POST", body: { forceWithLease: true, confirmed: true }, tabId });
9577
+ if (!forceResponse.ok) throw new Error([forceResponse.error, forceResponse.hint].filter(Boolean).join("\n"));
9578
+ addEvent("Force-pushed with --force-with-lease.", "success");
9579
+ requestGitFooterWebuiPayload(tabContext, { force: true });
9580
+ return;
9581
+ }
9582
+ throw new Error([response.error, response.hint].filter(Boolean).join("\n"));
9583
+ }
9584
+ const detail = [response.error, response.hint, formatGitCommandResult(response.data)].filter(Boolean).join("\n\n").trim();
8690
9585
  throw new Error(detail || "git push failed");
8691
9586
  }
8692
9587
  addEvent(`Pushed ${outgoing} outgoing commit${outgoing === 1 ? "" : "s"}.`, "success");
@@ -8699,43 +9594,51 @@ async function pushGitFooterSync(tabId = activeTabId, syncValue = "") {
8699
9594
  }
8700
9595
  }
8701
9596
 
8702
- function renderGitFooterPayloadMeta(chip, tab) {
9597
+ function renderGitFooterPayloadMeta(chip, tab, payload) {
8703
9598
  const options = {};
9599
+ const visible = (key) => gitFooterPayloadVisible(payload, key);
8704
9600
  let action = "";
8705
- if (chip.key === "cwd" && tab) {
9601
+ if (chip.key === "cwd" && tab && visible("webui-cwd-picker")) {
8706
9602
  options.onClick = changeActiveTabCwd;
8707
9603
  action = `Click to change the working directory for ${tab.title}.`;
8708
- } else if (chip.key === "git" && cleanFooterPayloadText(chip.value, "").toLowerCase() === "no repo") {
9604
+ } else if (chip.key === "git" && cleanFooterPayloadText(chip.value, "").toLowerCase() === "no repo" && visible("webui-git-init")) {
8709
9605
  options.onClick = () => startGitInitWorkflow();
8710
9606
  action = "No Git repository detected. Click to initialize a repo, create README.md, add origin, and push main.";
8711
- } else if (chip.key === "git") {
9607
+ } else if (chip.key === "git" && visible("webui-branch-picker")) {
8712
9608
  options.onClick = () => setFooterBranchPickerOpen(!footerBranchPickerOpen);
8713
9609
  action = "Click to open, create, or switch branches. Worktree actions are the safe default for parallel work.";
8714
- } else if (chip.key === "worktree") {
9610
+ } else if (chip.key === "worktree" && visible("webui-branch-picker")) {
8715
9611
  options.onClick = () => setFooterBranchPickerOpen(!footerBranchPickerOpen);
8716
9612
  action = "Click to manage branch worktrees for this repository.";
8717
- } else if (chip.key === "sync" && gitFooterSyncChipHasOutgoing(chip)) {
9613
+ } else if (chip.key === "sync" && visible("webui-sync-push") && gitFooterSyncChipHasOutgoing(chip)) {
8718
9614
  const tabId = tab?.id || activeTabId;
8719
9615
  const inFlight = tabId ? gitFooterSyncPushInFlightByTab.has(tabId) : false;
8720
9616
  options.onClick = () => pushGitFooterSync(tabId, chip.value);
8721
9617
  options.ariaBusy = inFlight;
8722
9618
  options.disabled = inFlight;
8723
9619
  action = inFlight ? "Pushing local commits to the configured remote." : "Click to push local commits to the configured remote.";
8724
- } else if (chip.key === "changes") {
9620
+ } else if (chip.key === "changes" && visible("webui-changes-modal")) {
8725
9621
  options.onClick = openGitChangesDialog;
8726
9622
  action = "Click to view the current git diff.";
8727
- } else if (chip.key === "model") {
9623
+ } else if (chip.key === "git-state" && visible("webui-changes-modal")) {
9624
+ options.onClick = openGitChangesDialog;
9625
+ action = "Click to open the conflicts and operation panel with continue/abort actions.";
9626
+ } else if (chip.key === "git-extra" && visible("webui-git-tools-modal")) {
9627
+ const toolsSection = gitToolsSectionForExtraChip(chip.value);
9628
+ options.onClick = () => openGitToolsFromFooter(toolsSection);
9629
+ action = `Click to open git tools (${toolsSection} first): stash, worktrees, undo, submodules, tags, signing.`;
9630
+ } else if (chip.key === "model" && visible("webui-model-picker")) {
8728
9631
  options.onClick = () => setFooterModelPickerOpen(!footerModelPickerOpen);
8729
9632
  action = "Click to choose another model.";
8730
- } else if (chip.key === "thinking") {
9633
+ } else if (chip.key === "thinking" && visible("webui-thinking-picker")) {
8731
9634
  options.onClick = () => setFooterThinkingPickerOpen(!footerThinkingPickerOpen);
8732
9635
  action = "Click to change thinking effort.";
8733
9636
  }
8734
- action = applyGitFooterContextToggleOptions(chip, options) || action;
9637
+ action = (visible("webui-context-auto-compaction") ? applyGitFooterContextToggleOptions(chip, options) : "") || action;
8735
9638
  options.title = gitFooterPayloadTooltip(chip, { action });
8736
9639
  options.tooltipAlign = gitFooterTooltipAlign(chip);
8737
9640
  const node = footerMeta(chip.label, chip.value, footerMetaClassForPayload(chip), options);
8738
- applyFooterChangedFilesDropdown(node, chip);
9641
+ applyFooterChangedFilesDropdown(node, chip, payload);
8739
9642
  if (["git", "worktree"].includes(chip.key) && options.onClick && cleanFooterPayloadText(chip.value, "").toLowerCase() !== "no repo") {
8740
9643
  node.setAttribute("aria-haspopup", "listbox");
8741
9644
  node.setAttribute("aria-expanded", footerBranchPickerOpen ? "true" : "false");
@@ -8759,12 +9662,12 @@ function gitFooterChipShapeKey(chip) {
8759
9662
  return JSON.stringify(shape);
8760
9663
  }
8761
9664
 
8762
- function gitFooterPickerStateKey() {
9665
+ function gitFooterPickerStateKey(payload) {
8763
9666
  const tabContext = activeTabContext();
8764
9667
  const refreshInFlight = tabContext.tabId ? gitFooterPayloadRefreshInFlightByTab.has(tabContext.tabId) : false;
8765
9668
  const syncPushInFlight = tabContext.tabId ? gitFooterSyncPushInFlightByTab.has(tabContext.tabId) : false;
8766
9669
  const refreshAvailable = hasLoadedRpcCommand("git-footer-refresh");
8767
- return `${footerModelPickerOpen ? 1 : 0}|${footerThinkingPickerOpen ? 1 : 0}|${footerBranchPickerOpen ? 1 : 0}|${mobileFooterExpanded ? 1 : 0}|${refreshInFlight ? 1 : 0}|${syncPushInFlight ? 1 : 0}|${refreshAvailable ? 1 : 0}`;
9670
+ return `${footerModelPickerOpen ? 1 : 0}|${footerThinkingPickerOpen ? 1 : 0}|${footerBranchPickerOpen ? 1 : 0}|${mobileFooterExpanded ? 1 : 0}|${refreshInFlight ? 1 : 0}|${syncPushInFlight ? 1 : 0}|${refreshAvailable ? 1 : 0}|${gitFooterPayloadVisibilityKey(payload)}`;
8768
9671
  }
8769
9672
 
8770
9673
  function updateGitFooterChipNodeValue(node, chip, valueSelector) {
@@ -8816,7 +9719,11 @@ function renderGitFooterRefreshButton() {
8816
9719
 
8817
9720
  function renderGitFooterPayload(payload) {
8818
9721
  const tab = activeTab();
8819
- const pickerKey = gitFooterPickerStateKey();
9722
+ if (!gitFooterPayloadVisible(payload, "webui-details-button")) mobileFooterExpanded = false;
9723
+ if (!gitFooterPayloadVisible(payload, "webui-model-picker")) footerModelPickerOpen = false;
9724
+ if (!gitFooterPayloadVisible(payload, "webui-thinking-picker")) footerThinkingPickerOpen = false;
9725
+ if (!gitFooterPayloadVisible(payload, "webui-branch-picker")) footerBranchPickerOpen = false;
9726
+ const pickerKey = gitFooterPickerStateKey(payload);
8820
9727
  const mainKeys = payload.main.map(gitFooterChipShapeKey);
8821
9728
  const metaKeys = payload.meta.map(gitFooterChipShapeKey);
8822
9729
 
@@ -8847,23 +9754,28 @@ function renderGitFooterPayload(payload) {
8847
9754
  elements.statusBar.classList.add("statusbar-git-footer");
8848
9755
  document.body.classList.toggle("footer-model-picker-open", isFooterPickerOpen());
8849
9756
 
8850
- const mainNodes = payload.main.map(renderGitFooterPayloadMetric);
9757
+ const mainNodes = payload.main.map((chip) => renderGitFooterPayloadMetric(chip, payload));
8851
9758
  const row1 = make("div", "footer-line footer-line-main");
8852
9759
  row1.append(...mainNodes);
8853
9760
 
8854
- const footerToggle = make("button", "footer-details-toggle", mobileFooterExpanded ? "Less" : "Details");
8855
- footerToggle.type = "button";
8856
- footerToggle.setAttribute("aria-expanded", mobileFooterExpanded ? "true" : "false");
8857
- footerToggle.addEventListener("click", () => setMobileFooterExpanded(!mobileFooterExpanded));
8858
-
8859
- const metaNodes = payload.meta.map((chip) => renderGitFooterPayloadMeta(chip, tab));
9761
+ const metaNodes = payload.meta.map((chip) => renderGitFooterPayloadMeta(chip, tab, payload));
8860
9762
  const row2 = make("div", "footer-line footer-line-meta");
8861
- row2.append(...metaNodes, footerToggle);
8862
-
8863
- elements.statusBar.append(row1, row2, renderGitFooterRefreshButton());
8864
- if (footerModelPickerOpen) elements.statusBar.append(renderFooterModelPicker());
8865
- if (footerThinkingPickerOpen) elements.statusBar.append(renderFooterThinkingPicker());
8866
- if (footerBranchPickerOpen) elements.statusBar.append(renderFooterBranchPicker());
9763
+ const row2Children = [...metaNodes];
9764
+ if (gitFooterPayloadVisible(payload, "webui-details-button")) {
9765
+ const footerToggle = make("button", "footer-details-toggle", mobileFooterExpanded ? "Less" : "Details");
9766
+ footerToggle.type = "button";
9767
+ footerToggle.setAttribute("aria-expanded", mobileFooterExpanded ? "true" : "false");
9768
+ footerToggle.addEventListener("click", () => setMobileFooterExpanded(!mobileFooterExpanded));
9769
+ row2Children.push(footerToggle);
9770
+ }
9771
+ row2.append(...row2Children);
9772
+
9773
+ const statusChildren = [row1, row2];
9774
+ if (gitFooterPayloadVisible(payload, "webui-refresh-button")) statusChildren.push(renderGitFooterRefreshButton());
9775
+ elements.statusBar.append(...statusChildren);
9776
+ if (footerModelPickerOpen && gitFooterPayloadVisible(payload, "webui-model-picker")) elements.statusBar.append(renderFooterModelPicker());
9777
+ if (footerThinkingPickerOpen && gitFooterPayloadVisible(payload, "webui-thinking-picker")) elements.statusBar.append(renderFooterThinkingPicker());
9778
+ if (footerBranchPickerOpen && gitFooterPayloadVisible(payload, "webui-branch-picker")) elements.statusBar.append(renderFooterBranchPicker());
8867
9779
  gitFooterRenderCache = { pickerKey, mainKeys, metaKeys, mainNodes, metaNodes };
8868
9780
  setMobileFooterExpanded(mobileFooterExpanded);
8869
9781
  updateFooterModelPickerPosition();
@@ -9049,15 +9961,89 @@ function renderGitDiffGrid(file) {
9049
9961
  grid.append(renderGitDiffRow(row));
9050
9962
  renderedRows += 1;
9051
9963
  }
9052
- if (truncated) break;
9964
+ if (truncated) break;
9965
+ }
9966
+ if (truncated) {
9967
+ grid.append(renderGitDiffRow({ type: "meta", oldNumber: "", newNumber: "", left: `Diff preview truncated after ${rowLimit} rows.`, right: "Use git diff in the terminal for the full output." }));
9968
+ }
9969
+ return grid;
9970
+ }
9971
+
9972
+ function gitFileActionButtons(actions) {
9973
+ if (!actions?.length) return null;
9974
+ const wrap = make("span", "git-file-actions");
9975
+ for (const action of actions) {
9976
+ const button = make("button", `git-file-action ${action.className || ""}`.trim(), action.label);
9977
+ button.type = "button";
9978
+ button.title = action.title || action.label;
9979
+ button.addEventListener("click", (event) => {
9980
+ event.preventDefault();
9981
+ event.stopPropagation();
9982
+ action.onClick();
9983
+ });
9984
+ wrap.append(button);
9985
+ }
9986
+ return wrap;
9987
+ }
9988
+
9989
+ function copyGitTextToClipboard(text, label = "text") {
9990
+ navigator.clipboard?.writeText(text)
9991
+ .then(() => addEvent(`Copied ${label}: ${text}`, "info"))
9992
+ .catch(() => addEvent(`Clipboard unavailable; copy the ${label} manually.`, "error"));
9993
+ }
9994
+
9995
+ function copyGitPathToClipboard(path) {
9996
+ copyGitTextToClipboard(path, "path");
9997
+ }
9998
+
9999
+ // Git paths are repo-root-relative; the file viewer resolves against the tab
10000
+ // cwd. Translate when the tab sits at (or above within) the repo root.
10001
+ async function openGitFileFromChanges(repoRelPath) {
10002
+ const tabId = gitChangesState.tabId || activeTabId;
10003
+ const root = gitChangesState.data?.root || "";
10004
+ const tab = tabs.find((item) => item.id === tabId);
10005
+ let viewerPath = repoRelPath;
10006
+ if (root && tab?.cwd) {
10007
+ const absolute = `${root.replace(/\/+$/, "")}/${repoRelPath}`;
10008
+ const cwd = tab.cwd.replace(/\/+$/, "");
10009
+ if (absolute.startsWith(`${cwd}/`)) viewerPath = absolute.slice(cwd.length + 1);
10010
+ else if (root !== cwd) {
10011
+ addEvent(`Cannot open ${repoRelPath}: it is outside this tab's working directory.`, "error");
10012
+ return;
10013
+ }
9053
10014
  }
9054
- if (truncated) {
9055
- grid.append(renderGitDiffRow({ type: "meta", oldNumber: "", newNumber: "", left: `Diff preview truncated after ${rowLimit} rows.`, right: "Use git diff in the terminal for the full output." }));
10015
+ closeGitChangesDialog();
10016
+ setSidePanelCollapsed(false);
10017
+ await openFileInViewer(viewerPath);
10018
+ }
10019
+
10020
+ function gitChangesCommonFileActions(path) {
10021
+ return [
10022
+ { label: "Open", title: "Open this file in the WebUI file viewer", onClick: () => openGitFileFromChanges(path) },
10023
+ { label: "Copy path", title: "Copy the repo-relative path", onClick: () => copyGitPathToClipboard(path) },
10024
+ ];
10025
+ }
10026
+
10027
+ function gitChangesFileActionsFor(sectionKey, path) {
10028
+ if (!path || gitChangesState.loading || gitChangesState.pulling || gitChangesState.fetching) return [];
10029
+ if (sectionKey === "unstaged") {
10030
+ return [
10031
+ { label: "Stage", title: `git add -- ${path}`, onClick: () => runGitFileAction("stage", path) },
10032
+ ...gitChangesCommonFileActions(path),
10033
+ { label: "Discard", className: "danger", title: `git restore -- ${path} (destructive)`, onClick: () => runGitFileAction("discard", path) },
10034
+ ];
9056
10035
  }
9057
- return grid;
10036
+ if (sectionKey === "staged") {
10037
+ return [
10038
+ { label: "Unstage", title: `git restore --staged -- ${path}`, onClick: () => runGitFileAction("unstage", path) },
10039
+ ...gitChangesCommonFileActions(path),
10040
+ ];
10041
+ }
10042
+ if (sectionKey === "incoming") return [{ label: "Copy path", title: "Copy the repo-relative path", onClick: () => copyGitPathToClipboard(path) }];
10043
+ return [];
9058
10044
  }
9059
10045
 
9060
- function renderGitDiffFile(file) {
10046
+ function renderGitDiffFile(file, actions = []) {
9061
10047
  const details = make("details", `git-diff-file ${file.className || ""}`.trim());
9062
10048
  details.open = true;
9063
10049
  details.dataset.gitDiffFile = file.path || "diff";
@@ -9066,6 +10052,8 @@ function renderGitDiffFile(file) {
9066
10052
  make("span", "git-diff-file-name", file.path || "diff"),
9067
10053
  make("span", "git-diff-file-stats", file.statsText || `+${file.additions || 0} −${file.deletions || 0}`),
9068
10054
  );
10055
+ const actionButtons = gitFileActionButtons(actions);
10056
+ if (actionButtons) summary.append(actionButtons);
9069
10057
  details.append(summary);
9070
10058
  if (file.hunks?.length) {
9071
10059
  details.append(renderGitDiffGrid(file));
@@ -9083,7 +10071,20 @@ function renderGitDiffSection(section, files) {
9083
10071
  make("div", "git-diff-section-title", section?.label || "Git diff"),
9084
10072
  make("div", "git-diff-section-meta", `${files.length} file${files.length === 1 ? "" : "s"} · ${section?.command || "git diff"}`),
9085
10073
  );
9086
- wrapper.append(header, ...files.map(renderGitDiffFile));
10074
+ wrapper.append(header);
10075
+ if (section?.truncated) {
10076
+ const notice = make("div", "git-diff-truncated-notice");
10077
+ const fullCommand = String(section?.command || "git diff").replace(/\s--unified=0\b/, "");
10078
+ notice.append(make("span", undefined, `Diff truncated at ${formatBytes(section.capBytes || 0)} — showing the tail. Use the per-file Open buttons for full contents, or run the full command in a terminal:`));
10079
+ notice.append(make("code", "git-tools-command", fullCommand));
10080
+ const copy = make("button", "git-file-action", "Copy command");
10081
+ copy.type = "button";
10082
+ copy.title = "Copy the full diff command";
10083
+ copy.addEventListener("click", () => copyGitTextToClipboard(fullCommand, "command"));
10084
+ notice.append(copy);
10085
+ wrapper.append(notice);
10086
+ }
10087
+ wrapper.append(...files.map((file) => renderGitDiffFile(file, gitChangesFileActionsFor(section?.key, file.path))));
9087
10088
  return wrapper;
9088
10089
  }
9089
10090
 
@@ -9157,9 +10158,21 @@ function renderGitUntrackedLoadingFile(entry) {
9157
10158
  }
9158
10159
 
9159
10160
  function renderGitUntrackedFile(entry) {
9160
- if (entry.contentMissing) return renderGitUntrackedLoadingFile(entry);
9161
- if (entry.error || entry.binary) return renderGitUntrackedRawFile(entry);
9162
- return renderGitDiffFile(gitUntrackedEntryToDiffFile(entry));
10161
+ const node = entry.contentMissing
10162
+ ? renderGitUntrackedLoadingFile(entry)
10163
+ : entry.error || entry.binary
10164
+ ? renderGitUntrackedRawFile(entry)
10165
+ : renderGitDiffFile(gitUntrackedEntryToDiffFile(entry));
10166
+ if (!gitChangesState.loading && !gitChangesState.pulling && !gitChangesState.fetching) {
10167
+ const summary = node.querySelector("summary");
10168
+ const actions = gitFileActionButtons([
10169
+ { label: "Stage", title: `git add -- ${entry.path}`, onClick: () => runGitFileAction("stage", entry.path) },
10170
+ ...gitChangesCommonFileActions(entry.path),
10171
+ { label: "Delete", className: "danger", title: "Delete this untracked file from disk (destructive)", onClick: () => runGitFileAction("delete-untracked", entry.path) },
10172
+ ]);
10173
+ if (summary && actions) summary.append(actions);
10174
+ }
10175
+ return node;
9163
10176
  }
9164
10177
 
9165
10178
  function replaceGitUntrackedEntry(entry, tabId = gitChangesState.tabId) {
@@ -9410,9 +10423,12 @@ function renderGitPullResultPanel(result) {
9410
10423
 
9411
10424
  function renderGitChangesDialog() {
9412
10425
  if (!elements.gitChangesDialog || !elements.gitChangesBody) return;
9413
- const { loading, pulling, error, message, pullResult, data } = gitChangesState;
10426
+ const { loading, pulling, fetching, error, message, pullResult, data, operation } = gitChangesState;
10427
+ const busyAction = pulling || fetching;
9414
10428
  const behind = Number(data?.remote?.behind ?? data?.summary?.behind ?? 0) || 0;
9415
- const canPull = behind > 0 && data?.remote?.canPull !== false;
10429
+ const diverged = data?.remote?.diverged === true;
10430
+ const canPull = behind > 0 && data?.remote?.canPull !== false && !diverged;
10431
+ const hasOperation = Boolean(operation?.operation);
9416
10432
  const remoteNotice = !error && data?.remote?.error ? `Incoming diff unavailable: ${data.remote.error}` : "";
9417
10433
  if (elements.gitChangesTitle) elements.gitChangesTitle.textContent = "Git Changes";
9418
10434
  if (elements.gitChangesSubtitle) {
@@ -9420,16 +10436,25 @@ function renderGitChangesDialog() {
9420
10436
  elements.gitChangesSubtitle.textContent = data?.remote?.upstream ? `${base} · upstream ${data.remote.upstream}` : base;
9421
10437
  }
9422
10438
  if (elements.gitChangesRefreshButton) {
9423
- elements.gitChangesRefreshButton.disabled = loading || pulling;
10439
+ elements.gitChangesRefreshButton.disabled = loading || busyAction;
9424
10440
  elements.gitChangesRefreshButton.textContent = loading ? "Refreshing…" : "Refresh";
9425
10441
  }
10442
+ if (elements.gitChangesFetchButton) {
10443
+ elements.gitChangesFetchButton.disabled = loading || busyAction || !data?.root;
10444
+ elements.gitChangesFetchButton.textContent = fetching ? "Fetching…" : "Fetch";
10445
+ elements.gitChangesFetchButton.title = "Run git fetch --prune to refresh remote tracking state";
10446
+ }
9426
10447
  if (elements.gitChangesPullButton) {
9427
- elements.gitChangesPullButton.disabled = loading || pulling || !canPull;
10448
+ elements.gitChangesPullButton.disabled = loading || busyAction || !canPull;
9428
10449
  elements.gitChangesPullButton.textContent = pulling ? "Pulling…" : behind > 0 ? `Pull ↓${behind}` : "Pull";
9429
- elements.gitChangesPullButton.title = canPull ? "Run git pull --ff-only for the current repository" : "No remote commits to pull";
10450
+ elements.gitChangesPullButton.title = canPull
10451
+ ? "Run git pull --ff-only for the current repository"
10452
+ : diverged
10453
+ ? "Local and remote branches have diverged; use the integrate actions below instead of one-click pull."
10454
+ : "No remote commits to pull";
9430
10455
  }
9431
10456
  if (elements.gitChangesStatus) {
9432
- const statusText = error || (pulling ? "Pulling changes…" : loading ? "Loading git diff…" : message || remoteNotice || (data ? gitChangesGeneratedLabel(data) : ""));
10457
+ const statusText = error || (pulling ? "Pulling changes…" : fetching ? "Fetching from remote…" : loading ? "Loading git diff…" : message || remoteNotice || (data ? gitChangesGeneratedLabel(data) : ""));
9433
10458
  elements.gitChangesStatus.className = `git-changes-status ${error || remoteNotice ? "error" : message ? "success" : "muted"}`;
9434
10459
  elements.gitChangesStatus.textContent = statusText;
9435
10460
  elements.gitChangesStatus.hidden = !elements.gitChangesStatus.textContent;
@@ -9451,7 +10476,18 @@ function renderGitChangesDialog() {
9451
10476
  }
9452
10477
 
9453
10478
  if (pullResult) body.append(renderGitPullResultPanel(pullResult));
10479
+ if (hasOperation) {
10480
+ const panel = renderGitOperationPanel(operation);
10481
+ if (panel) body.append(panel);
10482
+ }
9454
10483
  body.append(renderGitChangesOverview(data));
10484
+ const fetchStateLines = gitChangesFetchStateLines();
10485
+ if (fetchStateLines.length) {
10486
+ const fetchNote = make("div", "git-tools-note git-fetch-state-note");
10487
+ for (const line of fetchStateLines) fetchNote.append(make("div", undefined, line));
10488
+ body.append(fetchNote);
10489
+ }
10490
+ if (diverged && !hasOperation) body.append(renderGitDivergedBar(data));
9455
10491
  const parsedSections = (Array.isArray(data.sections) ? data.sections : [])
9456
10492
  .map((section) => ({ section, files: parseGitUnifiedDiff(section.diff || "") }))
9457
10493
  .filter((entry) => entry.files.length > 0);
@@ -9464,23 +10500,40 @@ function renderGitChangesDialog() {
9464
10500
  }
9465
10501
  for (const entry of parsedSections) body.append(renderGitDiffSection(entry.section, entry.files));
9466
10502
  if (untracked.length) body.append(renderGitUntrackedSection(untracked));
9467
- if (!hasVisibleFiles) {
10503
+ if (!hasVisibleFiles && !hasOperation) {
9468
10504
  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.";
9469
10505
  body.append(make("div", "git-changes-empty success", emptyMessage));
9470
10506
  }
10507
+ body.append(renderGitToolsSection());
9471
10508
  if (hasVisibleFiles) requestAnimationFrame(updateGitChangesCurrentFileHeader);
9472
10509
  }
9473
10510
 
9474
10511
  async function loadGitChangesDialog(tabContext = activeTabContext()) {
9475
10512
  const requestSerial = ++gitChangesRequestSerial;
9476
10513
  gitChangesUntrackedContentRequests.clear();
9477
- gitChangesState = { ...gitChangesState, loading: true, error: "", message: "", pullResult: null, tabId: tabContext.tabId || activeTabId };
10514
+ gitChangesState = { ...gitChangesState, loading: true, error: "", errorCode: "", errorHint: "", message: "", pullResult: null, tabId: tabContext.tabId || activeTabId };
9478
10515
  renderGitChangesDialog();
9479
10516
  try {
9480
- const response = await api("/api/git-changes", { tabId: tabContext.tabId });
10517
+ const [response, operationResponse] = await Promise.all([
10518
+ api("/api/git-changes", { tabId: tabContext.tabId }),
10519
+ api("/api/git-operation", { tabId: tabContext.tabId }).catch(() => null),
10520
+ ]);
9481
10521
  if (requestSerial !== gitChangesRequestSerial) return;
9482
10522
  if (!response.ok) throw new Error(response.error || "Failed to load git changes");
9483
- gitChangesState = { loading: false, pulling: false, error: "", message: "", pullResult: null, data: response.data || null, tabId: tabContext.tabId || activeTabId };
10523
+ gitChangesState = {
10524
+ ...gitChangesState,
10525
+ loading: false,
10526
+ pulling: false,
10527
+ fetching: false,
10528
+ error: "",
10529
+ errorCode: "",
10530
+ errorHint: "",
10531
+ message: "",
10532
+ pullResult: null,
10533
+ data: response.data || null,
10534
+ operation: operationResponse?.ok ? operationResponse.data : null,
10535
+ tabId: tabContext.tabId || activeTabId,
10536
+ };
9484
10537
  } catch (error) {
9485
10538
  if (requestSerial !== gitChangesRequestSerial) return;
9486
10539
  gitChangesState = { ...gitChangesState, loading: false, error: error.message || String(error) };
@@ -9493,7 +10546,22 @@ function openGitChangesDialog() {
9493
10546
  hideFooterTooltip();
9494
10547
  const tabContext = activeTabContext();
9495
10548
  const tabId = tabContext.tabId || activeTabId;
9496
- gitChangesState = { loading: true, pulling: false, error: "", message: "", pullResult: null, data: gitChangesState.tabId === tabId ? gitChangesState.data : null, tabId };
10549
+ if (gitToolsState.tabId !== tabId) resetGitToolsState(tabId);
10550
+ gitChangesState = {
10551
+ ...gitChangesState,
10552
+ loading: true,
10553
+ pulling: false,
10554
+ fetching: false,
10555
+ error: "",
10556
+ errorCode: "",
10557
+ errorHint: "",
10558
+ message: "",
10559
+ pullResult: null,
10560
+ data: gitChangesState.tabId === tabId ? gitChangesState.data : null,
10561
+ operation: gitChangesState.tabId === tabId ? gitChangesState.operation : null,
10562
+ lastFetch: gitChangesState.tabId === tabId ? gitChangesState.lastFetch : null,
10563
+ tabId,
10564
+ };
9497
10565
  renderGitChangesDialog();
9498
10566
  if (!elements.gitChangesDialog.open) elements.gitChangesDialog.showModal();
9499
10567
  loadGitChangesDialog(tabContext).catch((error) => addEvent(error.message || String(error), "error"));
@@ -9507,25 +10575,30 @@ function refreshGitChangesDialog() {
9507
10575
  async function pullGitChangesDialog() {
9508
10576
  const tabContext = { tabId: gitChangesState.tabId || activeTabId };
9509
10577
  const behind = Number(gitChangesState.data?.remote?.behind ?? gitChangesState.data?.summary?.behind ?? 0) || 0;
9510
- if (behind <= 0 || gitChangesState.pulling || gitChangesState.loading) return;
10578
+ if (behind <= 0 || gitChangesState.pulling || gitChangesState.loading || gitChangesState.fetching) return;
10579
+ if (gitChangesState.data?.remote?.diverged === true) return;
9511
10580
  const root = gitChangesState.data?.root || "the current repository";
9512
10581
  if (!window.confirm(`Run git pull --ff-only in ${root}?`)) return;
9513
10582
 
9514
10583
  const requestSerial = ++gitChangesRequestSerial;
9515
- gitChangesState = { ...gitChangesState, pulling: true, loading: false, error: "", message: "", pullResult: null, tabId: tabContext.tabId };
10584
+ gitChangesState = { ...gitChangesState, pulling: true, loading: false, error: "", errorCode: "", errorHint: "", message: "", pullResult: null, tabId: tabContext.tabId };
9516
10585
  renderGitChangesDialog();
9517
10586
  try {
9518
10587
  const response = await api("/api/git-changes/pull", { method: "POST", body: {}, tabId: tabContext.tabId });
9519
10588
  if (requestSerial !== gitChangesRequestSerial) return;
9520
10589
  if (!response.ok) {
9521
- const detail = [response.error, response.data?.stderr || response.data?.stdout].filter(Boolean).join("\n").trim();
10590
+ gitChangesState = { ...gitChangesState, errorCode: response.code || "" };
10591
+ const detail = [response.error, response.hint].filter(Boolean).join("\n").trim();
9522
10592
  throw new Error(detail || "Failed to pull git changes");
9523
10593
  }
9524
10594
  const pullResult = normalizeGitPullResult(response.data || {});
9525
10595
  gitChangesState = {
10596
+ ...gitChangesState,
9526
10597
  loading: false,
9527
10598
  pulling: false,
9528
10599
  error: "",
10600
+ errorCode: "",
10601
+ errorHint: "",
9529
10602
  message: gitPullResultStatus(pullResult),
9530
10603
  pullResult,
9531
10604
  data: response.data?.changes || gitChangesState.data,
@@ -9544,10 +10617,742 @@ async function pullGitChangesDialog() {
9544
10617
  function closeGitChangesDialog() {
9545
10618
  gitChangesRequestSerial += 1;
9546
10619
  gitChangesUntrackedContentRequests.clear();
9547
- gitChangesState = { ...gitChangesState, loading: false, pulling: false };
10620
+ gitChangesState = { ...gitChangesState, loading: false, pulling: false, fetching: false };
9548
10621
  if (elements.gitChangesDialog?.open) elements.gitChangesDialog.close();
9549
10622
  }
9550
10623
 
10624
+ async function fetchGitChangesDialog() {
10625
+ const tabId = gitChangesState.tabId || activeTabId;
10626
+ if (gitChangesState.fetching || gitChangesState.loading || gitChangesState.pulling) return;
10627
+ const requestSerial = ++gitChangesRequestSerial;
10628
+ gitChangesState = { ...gitChangesState, fetching: true, error: "", errorCode: "", errorHint: "", message: "", pullResult: null };
10629
+ renderGitChangesDialog();
10630
+ try {
10631
+ const response = await api("/api/git-fetch", { method: "POST", body: {}, tabId });
10632
+ if (requestSerial !== gitChangesRequestSerial) return;
10633
+ if (!response.ok) {
10634
+ gitChangesState = { ...gitChangesState, errorCode: response.code || "" };
10635
+ throw new Error([response.error, response.hint].filter(Boolean).join("\n") || "git fetch failed");
10636
+ }
10637
+ const summaryLine = String(response.data?.summary || "").split(/\r?\n/).map((line) => line.trim()).filter(Boolean).slice(-1)[0] || "";
10638
+ gitChangesState = {
10639
+ ...gitChangesState,
10640
+ fetching: false,
10641
+ data: response.data?.changes || gitChangesState.data,
10642
+ lastFetch: { at: Date.now(), summary: summaryLine, error: "" },
10643
+ message: summaryLine && !/^fetching/i.test(summaryLine) ? `Fetched (--prune). ${summaryLine}` : "Fetched remote state (git fetch --prune).",
10644
+ };
10645
+ addEvent("Fetched remote state (git fetch --prune).", "success");
10646
+ requestGitFooterWebuiPayload(activeTabContext(tabId), { force: true });
10647
+ } catch (error) {
10648
+ if (requestSerial !== gitChangesRequestSerial) return;
10649
+ gitChangesState = { ...gitChangesState, fetching: false, error: error.message || String(error), lastFetch: { at: Date.now(), summary: "", error: error.message || String(error) } };
10650
+ }
10651
+ renderGitChangesDialog();
10652
+ }
10653
+
10654
+ // Fetch state lines shown inside the dialog: the extension's startup/tab fetch
10655
+ // state (from the changes-chip tooltip payload) plus this dialog's last fetch.
10656
+ function gitChangesFetchStateLines() {
10657
+ const lines = [];
10658
+ const chip = parseGitFooterWebuiPayload()?.meta?.find((item) => item.key === "changes");
10659
+ const extensionLine = String(chip?.title || "").split("\n").find((line) => /git fetch/i.test(line));
10660
+ if (extensionLine) lines.push(`Tab fetch state: ${extensionLine.trim()}`);
10661
+ const lastFetch = gitChangesState.lastFetch;
10662
+ if (lastFetch?.at) {
10663
+ const time = new Date(lastFetch.at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
10664
+ lines.push(lastFetch.error ? `Last fetch from this dialog at ${time} failed: ${lastFetch.error}` : `Last fetch from this dialog at ${time}${lastFetch.summary ? ` — ${lastFetch.summary}` : " completed."}`);
10665
+ }
10666
+ return lines;
10667
+ }
10668
+
10669
+ async function integrateGitChangesDialog(mode) {
10670
+ const tabId = gitChangesState.tabId || activeTabId;
10671
+ const data = gitChangesState.data;
10672
+ const upstream = data?.remote?.upstream || "@{upstream}";
10673
+ const command = mode === "merge" ? `git merge --no-edit ${upstream}` : `git rebase ${upstream}`;
10674
+ if (!window.confirm([
10675
+ `${mode === "merge" ? "Merge" : "Rebase onto"} ${upstream} in ${data?.root || "the current repository"}?`,
10676
+ "",
10677
+ `Command: ${command}`,
10678
+ mode === "rebase" ? "Rebase rewrites local commits. Conflicts open the conflicts panel." : "Conflicts open the conflicts panel.",
10679
+ "For risky integration, prefer a separate worktree instead.",
10680
+ ].join("\n"))) return;
10681
+ gitChangesState = { ...gitChangesState, pulling: true, error: "", errorCode: "", errorHint: "", message: "", pullResult: null };
10682
+ renderGitChangesDialog();
10683
+ try {
10684
+ const response = await api("/api/git-changes/integrate", { method: "POST", body: { mode, confirmed: true }, tabId });
10685
+ if (!response.ok) {
10686
+ const errText = [response.error, response.hint].filter(Boolean).join("\n") || `git ${mode} failed`;
10687
+ gitChangesState = { ...gitChangesState, pulling: false };
10688
+ await loadGitChangesDialog({ tabId });
10689
+ gitChangesState = { ...gitChangesState, error: errText, errorCode: response.code || "" };
10690
+ renderGitChangesDialog();
10691
+ return;
10692
+ }
10693
+ gitChangesState = { ...gitChangesState, pulling: false, message: `Integrated ${upstream} via ${mode}.`, data: response.data?.changes || gitChangesState.data };
10694
+ addEvent(`Integrated ${upstream} via ${mode}.`, "success");
10695
+ renderGitChangesDialog();
10696
+ requestGitFooterWebuiPayload(activeTabContext(tabId), { force: true });
10697
+ } catch (error) {
10698
+ gitChangesState = { ...gitChangesState, pulling: false, error: error.message || String(error) };
10699
+ renderGitChangesDialog();
10700
+ }
10701
+ }
10702
+
10703
+ async function runGitFileAction(action, path) {
10704
+ const tabId = gitChangesState.tabId || activeTabId;
10705
+ const root = gitChangesState.data?.root || "the repository";
10706
+ const config = {
10707
+ stage: { url: "/api/git-changes/stage-file", body: { path }, label: `Staged ${path}.` },
10708
+ unstage: { url: "/api/git-changes/unstage-file", body: { path }, label: `Unstaged ${path}.` },
10709
+ discard: {
10710
+ url: "/api/git-changes/discard-file",
10711
+ body: { path, confirmed: true },
10712
+ label: `Discarded changes in ${path}.`,
10713
+ confirm: `Discard working tree changes in ${path}?\n\nRepository: ${root}\nCommand: git restore -- ${path}\n\nThis permanently reverts unstaged edits to this file.`,
10714
+ },
10715
+ "delete-untracked": {
10716
+ url: "/api/git-changes/delete-untracked",
10717
+ body: { path, confirmed: true },
10718
+ label: `Deleted untracked file ${path}.`,
10719
+ confirm: `Delete untracked file ${path}?\n\nRepository: ${root}\n\nThis permanently removes the file from disk.`,
10720
+ },
10721
+ }[action];
10722
+ if (!config) return;
10723
+ if (config.confirm && !window.confirm(config.confirm)) return;
10724
+ try {
10725
+ const response = await api(config.url, { method: "POST", body: config.body, tabId });
10726
+ if (!response.ok) throw new Error([response.error, response.hint].filter(Boolean).join("\n") || `git ${action} failed`);
10727
+ gitChangesState = { ...gitChangesState, data: response.data?.changes || gitChangesState.data, message: config.label, error: "", errorCode: "", errorHint: "" };
10728
+ addEvent(config.label, "success");
10729
+ renderGitChangesDialog();
10730
+ requestGitFooterWebuiPayload(activeTabContext(tabId), { force: true });
10731
+ } catch (error) {
10732
+ gitChangesState = { ...gitChangesState, error: error.message || String(error) };
10733
+ renderGitChangesDialog();
10734
+ addEvent(error.message || String(error), "error");
10735
+ }
10736
+ }
10737
+
10738
+ const GIT_OPERATION_TITLES = {
10739
+ merge: "Merge in progress",
10740
+ rebase: "Rebase in progress",
10741
+ "cherry-pick": "Cherry-pick in progress",
10742
+ revert: "Revert in progress",
10743
+ bisect: "Bisect in progress",
10744
+ };
10745
+
10746
+ function renderGitConflictPreview(preview) {
10747
+ if (!preview) return null;
10748
+ if (preview.kind === "binary") return make("pre", "git-conflict-preview muted", `Binary file (${formatBytes(preview.size || 0)}); resolve it with an external tool, then mark it resolved.`);
10749
+ if (preview.kind === "large") return make("pre", "git-conflict-preview muted", `File too large to preview (${formatBytes(preview.size || 0)}).`);
10750
+ if (preview.kind === "missing") return make("pre", "git-conflict-preview muted", "File is missing in the working tree (deleted on one side).");
10751
+ if (preview.kind === "error") return make("pre", "git-conflict-preview muted", preview.error || "Preview unavailable.");
10752
+ if (preview.kind !== "text") return null;
10753
+ if (!preview.hunks?.length) {
10754
+ return make("pre", "git-conflict-preview muted", preview.hasMarkers ? "Conflict markers present." : "No conflict markers found; the file may already be resolved — mark it resolved to stage it.");
10755
+ }
10756
+ const text = preview.hunks.map((hunk) => hunk.lines.join("\n") + (hunk.truncated ? "\n…" : "")).join("\n⋯\n");
10757
+ return make("pre", "git-conflict-preview", text);
10758
+ }
10759
+
10760
+ async function runGitOperationRequest(url, body, successLabel) {
10761
+ const tabId = gitChangesState.tabId || activeTabId;
10762
+ gitToolsState.busy.add("operation");
10763
+ renderGitChangesDialog();
10764
+ try {
10765
+ const response = await api(url, { method: "POST", body, tabId });
10766
+ if (!response.ok) throw new Error([response.error, response.hint].filter(Boolean).join("\n") || "git operation failed");
10767
+ gitToolsState.busy.delete("operation");
10768
+ addEvent(`${successLabel}.`, "success");
10769
+ await loadGitChangesDialog({ tabId });
10770
+ gitChangesState = { ...gitChangesState, message: `${successLabel}.` };
10771
+ renderGitChangesDialog();
10772
+ requestGitFooterWebuiPayload(activeTabContext(tabId), { force: true });
10773
+ } catch (error) {
10774
+ gitToolsState.busy.delete("operation");
10775
+ gitChangesState = { ...gitChangesState, error: error.message || String(error) };
10776
+ renderGitChangesDialog();
10777
+ }
10778
+ }
10779
+
10780
+ function renderGitOperationPanel(operation) {
10781
+ const kind = operation?.operation;
10782
+ if (!kind) return null;
10783
+ const busy = gitToolsState.busy.has("operation") || gitChangesState.loading || gitChangesState.pulling || gitChangesState.fetching;
10784
+ const conflicts = operation.conflicts || [];
10785
+ const panel = make("section", "git-operation-panel");
10786
+ const header = make("div", "git-operation-header");
10787
+ header.append(
10788
+ make("strong", "git-operation-title", GIT_OPERATION_TITLES[kind] || `${kind} in progress`),
10789
+ make("span", "git-operation-meta", `${conflicts.length} conflicted file${conflicts.length === 1 ? "" : "s"} · ${operation.root || ""}`),
10790
+ );
10791
+ panel.append(header);
10792
+
10793
+ if (kind === "bisect") {
10794
+ if (operation.bisect?.log) panel.append(make("pre", "git-conflict-preview", operation.bisect.log));
10795
+ const row = make("div", "git-operation-actions");
10796
+ for (const verdict of ["good", "bad", "skip"]) {
10797
+ const button = make("button", "git-operation-button", `bisect ${verdict}`);
10798
+ button.type = "button";
10799
+ button.disabled = busy;
10800
+ button.title = `git bisect ${verdict}`;
10801
+ button.addEventListener("click", () => runGitOperationRequest("/api/git-operation/bisect", { verdict }, `Marked the current revision as ${verdict}`));
10802
+ row.append(button);
10803
+ }
10804
+ const reset = make("button", "git-operation-button danger", "Reset bisect");
10805
+ reset.type = "button";
10806
+ reset.disabled = busy;
10807
+ reset.title = "git bisect reset";
10808
+ reset.addEventListener("click", () => {
10809
+ if (!window.confirm(`Reset the bisect session in ${operation.root}?\n\nCommand: git bisect reset\nThis returns to the pre-bisect checkout.`)) return;
10810
+ runGitOperationRequest("/api/git-operation/bisect", { verdict: "reset", confirmed: true }, "Reset the bisect session");
10811
+ });
10812
+ row.append(reset);
10813
+ panel.append(row);
10814
+ return panel;
10815
+ }
10816
+
10817
+ if (conflicts.length) {
10818
+ const list = make("div", "git-conflict-list");
10819
+ for (const conflict of conflicts) {
10820
+ const item = make("details", "git-conflict-file");
10821
+ item.open = conflicts.length <= 3;
10822
+ const summary = make("summary", "git-conflict-summary");
10823
+ summary.append(
10824
+ make("span", "git-conflict-status", conflict.status || "UU"),
10825
+ make("span", "git-conflict-path", conflict.path),
10826
+ );
10827
+ const actions = gitFileActionButtons([
10828
+ {
10829
+ label: "Mark resolved",
10830
+ title: `git add -- ${conflict.path}`,
10831
+ onClick: () => runGitOperationRequest("/api/git-operation/stage-file", { path: conflict.path }, `Marked ${conflict.path} as resolved`),
10832
+ },
10833
+ ]);
10834
+ if (actions) summary.append(actions);
10835
+ item.append(summary);
10836
+ const preview = renderGitConflictPreview(conflict.preview);
10837
+ if (preview) item.append(preview);
10838
+ list.append(item);
10839
+ }
10840
+ panel.append(list);
10841
+ } else {
10842
+ panel.append(make("div", "git-changes-empty success", "No unmerged paths remain. Continue to finish the operation."));
10843
+ }
10844
+
10845
+ const row = make("div", "git-operation-actions");
10846
+ const refresh = make("button", "git-operation-button", "Refresh conflicts");
10847
+ refresh.type = "button";
10848
+ refresh.disabled = busy;
10849
+ refresh.addEventListener("click", refreshGitChangesDialog);
10850
+ row.append(refresh);
10851
+
10852
+ const cont = make("button", "git-operation-button primary", kind === "merge" ? "Continue (commit merge)" : "Continue");
10853
+ cont.type = "button";
10854
+ cont.disabled = busy || operation.canContinue !== true;
10855
+ cont.title = operation.canContinue ? operation.commands?.continue || "" : "Resolve and stage every conflicted file first.";
10856
+ cont.addEventListener("click", () => runGitOperationRequest("/api/git-operation/continue", {}, `Continued the ${kind}`));
10857
+ row.append(cont);
10858
+
10859
+ if (operation.canSkip) {
10860
+ const skip = make("button", "git-operation-button", "Skip");
10861
+ skip.type = "button";
10862
+ skip.disabled = busy;
10863
+ skip.title = operation.commands?.skip || "";
10864
+ skip.addEventListener("click", () => {
10865
+ if (!window.confirm(`Skip the current ${kind} step?\n\nCommand: ${operation.commands?.skip || `git ${kind} --skip`}\nThe skipped commit is left out of the result.`)) return;
10866
+ runGitOperationRequest("/api/git-operation/skip", {}, `Skipped the current ${kind} step`);
10867
+ });
10868
+ row.append(skip);
10869
+ }
10870
+
10871
+ const abort = make("button", "git-operation-button danger", "Abort");
10872
+ abort.type = "button";
10873
+ abort.disabled = busy;
10874
+ abort.title = operation.commands?.abort || "";
10875
+ abort.addEventListener("click", () => {
10876
+ const summary = operation.summary || {};
10877
+ if (!window.confirm([
10878
+ `Abort the ${kind} in ${operation.root}?`,
10879
+ "",
10880
+ `Command: ${operation.commands?.abort || `git ${kind} --abort`}`,
10881
+ `Working tree: ${summary.staged || 0} staged · ${summary.unstaged || 0} unstaged · ${conflicts.length} conflicted`,
10882
+ "",
10883
+ "This discards the in-progress operation state and returns to the pre-operation HEAD.",
10884
+ ].join("\n"))) return;
10885
+ runGitOperationRequest("/api/git-operation/abort", { confirmed: true }, `Aborted the ${kind}`);
10886
+ });
10887
+ row.append(abort);
10888
+ panel.append(row);
10889
+ return panel;
10890
+ }
10891
+
10892
+ function renderGitDivergedBar(data) {
10893
+ const remote = data?.remote || {};
10894
+ const bar = make("section", "git-diverged-bar");
10895
+ bar.append(make("strong", "git-diverged-title", `Diverged from ${remote.upstream || "upstream"}: ↑${remote.ahead || 0} local · ↓${remote.behind || 0} remote.`));
10896
+ bar.append(make("div", "git-tools-note", "One-click pull is disabled. Review the incoming diff below, then integrate explicitly — a separate worktree is the safest place for risky integration."));
10897
+ const row = make("div", "git-operation-actions");
10898
+ const busy = gitChangesState.loading || gitChangesState.pulling || gitChangesState.fetching;
10899
+ const addButton = (label, className, title, handler) => {
10900
+ const button = make("button", `git-operation-button ${className}`.trim(), label);
10901
+ button.type = "button";
10902
+ button.disabled = busy;
10903
+ button.title = title;
10904
+ button.addEventListener("click", handler);
10905
+ row.append(button);
10906
+ };
10907
+ addButton("Merge upstream…", "", `git merge --no-edit ${remote.upstream || "@{upstream}"}`, () => integrateGitChangesDialog("merge"));
10908
+ addButton("Rebase onto upstream…", "", `git rebase ${remote.upstream || "@{upstream}"}`, () => integrateGitChangesDialog("rebase"));
10909
+ addButton("Create integration worktree", "", "Open the branch picker to integrate in a separate worktree tab", () => {
10910
+ closeGitChangesDialog();
10911
+ openBranchWorktreePicker();
10912
+ });
10913
+ bar.append(row);
10914
+ return bar;
10915
+ }
10916
+
10917
+ // ---- Git tools (stash, undo, worktrees, submodules, tags, signing) ----
10918
+
10919
+ const GIT_TOOLS_SECTIONS = [
10920
+ { key: "stash", title: "Stash", detail: "List, apply, pop, drop, or create stashes." },
10921
+ { key: "undo", title: "Undo & recovery", detail: "Undo the last unpushed commit, amend its message, review recent HEAD history." },
10922
+ { key: "worktrees", title: "Worktrees", detail: "Health, removal, and pruning of git worktrees." },
10923
+ { key: "submodules", title: "Submodules", detail: "Status and recursive update." },
10924
+ { key: "tags", title: "Tags", detail: "Recent tags and annotated tag creation." },
10925
+ { key: "signing", title: "Signing", detail: "Commit signing configuration and diagnostics." },
10926
+ ];
10927
+
10928
+ const GIT_TOOLS_ENDPOINTS = {
10929
+ stash: "/api/git-stash",
10930
+ undo: "/api/git-undo",
10931
+ worktrees: "/api/git-worktrees",
10932
+ submodules: "/api/git-submodules",
10933
+ tags: "/api/git-tags",
10934
+ signing: "/api/git-signing",
10935
+ };
10936
+
10937
+ function resetGitToolsState(tabId) {
10938
+ gitToolsState = { tabId, openSections: new Set(), cache: {}, busy: new Set(), notice: {} };
10939
+ }
10940
+
10941
+ async function loadGitToolsSection(key, { force = false } = {}) {
10942
+ const tabId = gitChangesState.tabId || activeTabId;
10943
+ if (!force && gitToolsState.cache[key]) return;
10944
+ if (gitToolsState.busy.has(`load:${key}`)) return;
10945
+ gitToolsState.busy.add(`load:${key}`);
10946
+ try {
10947
+ const response = await api(GIT_TOOLS_ENDPOINTS[key], { tabId });
10948
+ if (!response.ok) throw new Error(response.error || `Failed to load ${key}`);
10949
+ gitToolsState.cache[key] = response.data;
10950
+ if (key === "undo") {
10951
+ const reflog = await api("/api/git-reflog", { tabId }).catch(() => null);
10952
+ gitToolsState.cache.reflog = reflog?.ok ? reflog.data : null;
10953
+ }
10954
+ gitToolsState.notice[key] = "";
10955
+ } catch (error) {
10956
+ gitToolsState.notice[key] = error.message || String(error);
10957
+ } finally {
10958
+ gitToolsState.busy.delete(`load:${key}`);
10959
+ renderGitChangesDialog();
10960
+ }
10961
+ }
10962
+
10963
+ async function runGitToolAction(sectionKey, { url, method = "POST", body, confirm, success, successMessage, refreshChanges = false }) {
10964
+ const tabId = gitChangesState.tabId || activeTabId;
10965
+ if (confirm && !window.confirm(confirm)) return;
10966
+ gitToolsState.busy.add(sectionKey);
10967
+ renderGitChangesDialog();
10968
+ try {
10969
+ const response = await api(url, { method, body, tabId });
10970
+ if (!response.ok) throw new Error([response.error, response.hint].filter(Boolean).join("\n") || "git action failed");
10971
+ const finalMessage = (typeof successMessage === "function" ? successMessage(response) : "") || success;
10972
+ gitToolsState.notice[sectionKey] = "";
10973
+ gitToolsState.busy.delete(sectionKey);
10974
+ addEvent(finalMessage, "success");
10975
+ await loadGitToolsSection(sectionKey, { force: true });
10976
+ if (refreshChanges) await loadGitChangesDialog({ tabId });
10977
+ gitChangesState = { ...gitChangesState, message: finalMessage };
10978
+ renderGitChangesDialog();
10979
+ requestGitFooterWebuiPayload(activeTabContext(tabId), { force: true });
10980
+ } catch (error) {
10981
+ gitToolsState.busy.delete(sectionKey);
10982
+ gitToolsState.notice[sectionKey] = error.message || String(error);
10983
+ renderGitChangesDialog();
10984
+ }
10985
+ }
10986
+
10987
+ function gitToolsButton(label, { className = "", disabled = false, title = "" } = {}, handler) {
10988
+ const button = make("button", `git-operation-button ${className}`.trim(), label);
10989
+ button.type = "button";
10990
+ button.disabled = disabled;
10991
+ if (title) button.title = title;
10992
+ button.addEventListener("click", handler);
10993
+ return button;
10994
+ }
10995
+
10996
+ // Apply/pop/drop always show the stash's --stat preview in the confirmation,
10997
+ // so no stash is modified sight-unseen.
10998
+ async function confirmGitStashActionWithPreview(stash, question) {
10999
+ const tabId = gitChangesState.tabId || activeTabId;
11000
+ let statText = "";
11001
+ try {
11002
+ const preview = await api(`/api/git-stash/show?ref=${encodeURIComponent(stash.ref)}`, { tabId });
11003
+ statText = preview?.ok ? String(preview.data?.stat || "").trim() : "";
11004
+ } catch {
11005
+ // Preview is best-effort; the confirmation still shows the stash subject.
11006
+ }
11007
+ return window.confirm([
11008
+ question,
11009
+ "",
11010
+ stash.subject || stash.ref,
11011
+ "",
11012
+ statText ? `Preview (git stash show --stat):\n${statText.slice(0, 2000)}` : "Preview unavailable.",
11013
+ ].join("\n"));
11014
+ }
11015
+
11016
+ function renderGitStashTools(body, data, busy) {
11017
+ const row = make("div", "git-operation-actions");
11018
+ row.append(
11019
+ gitToolsButton("Stash tracked changes", { disabled: busy, title: "git stash push" }, () =>
11020
+ runGitToolAction("stash", { url: "/api/git-stash/save", body: {}, success: "Stashed tracked changes.", refreshChanges: true })),
11021
+ gitToolsButton("Stash incl. untracked", { disabled: busy, title: "git stash push --include-untracked" }, () =>
11022
+ runGitToolAction("stash", { url: "/api/git-stash/save", body: { includeUntracked: true }, success: "Stashed tracked and untracked changes.", refreshChanges: true })),
11023
+ );
11024
+ body.append(row);
11025
+ const stashes = data.stashes || [];
11026
+ if (!stashes.length) {
11027
+ body.append(make("div", "git-changes-empty", "No stashes."));
11028
+ return body;
11029
+ }
11030
+ for (const stash of stashes) {
11031
+ const item = make("details", "git-tools-item");
11032
+ const summary = make("summary", "git-tools-item-summary");
11033
+ summary.append(make("span", "git-tools-item-ref", stash.ref), make("span", "git-tools-item-subject", stash.subject || ""));
11034
+ const actions = gitFileActionButtons([
11035
+ {
11036
+ label: "Apply",
11037
+ title: `git stash apply ${stash.ref}`,
11038
+ onClick: () => confirmGitStashActionWithPreview(stash, `Apply ${stash.ref} to the working tree?`).then((confirmed) => {
11039
+ if (confirmed) runGitToolAction("stash", { url: "/api/git-stash/apply", body: { ref: stash.ref }, success: `Applied ${stash.ref}.`, refreshChanges: true });
11040
+ }),
11041
+ },
11042
+ {
11043
+ label: "Pop",
11044
+ title: `git stash pop ${stash.ref}`,
11045
+ onClick: () => confirmGitStashActionWithPreview(stash, `Pop ${stash.ref}? This applies the stash and removes the entry on success.`).then((confirmed) => {
11046
+ if (confirmed) runGitToolAction("stash", { url: "/api/git-stash/pop", body: { ref: stash.ref }, success: `Popped ${stash.ref}.`, refreshChanges: true });
11047
+ }),
11048
+ },
11049
+ {
11050
+ label: "Drop",
11051
+ className: "danger",
11052
+ title: `git stash drop ${stash.ref}`,
11053
+ onClick: () => confirmGitStashActionWithPreview(stash, `Drop ${stash.ref}? This permanently deletes the stash entry.`).then((confirmed) => {
11054
+ if (confirmed) runGitToolAction("stash", { url: "/api/git-stash/drop", body: { ref: stash.ref, confirmed: true }, success: `Dropped ${stash.ref}.` });
11055
+ }),
11056
+ },
11057
+ ]);
11058
+ if (actions) summary.append(actions);
11059
+ item.append(summary);
11060
+ item.addEventListener("toggle", async () => {
11061
+ if (!item.open || item.dataset.previewLoaded) return;
11062
+ item.dataset.previewLoaded = "1";
11063
+ const placeholder = make("pre", "git-conflict-preview muted", "Loading stash preview…");
11064
+ item.append(placeholder);
11065
+ const preview = await api(`/api/git-stash/show?ref=${encodeURIComponent(stash.ref)}`, { tabId: gitChangesState.tabId || activeTabId }).catch(() => null);
11066
+ const text = preview?.ok ? [preview.data?.stat, preview.data?.patch].filter(Boolean).join("\n\n") : "Preview unavailable.";
11067
+ placeholder.textContent = text || "Empty stash preview.";
11068
+ placeholder.classList.toggle("muted", !preview?.ok);
11069
+ });
11070
+ body.append(item);
11071
+ }
11072
+ return body;
11073
+ }
11074
+
11075
+ function renderGitUndoTools(body, data, busy) {
11076
+ const last = data.lastCommit;
11077
+ body.append(make("div", "git-tools-note", last ? `Last commit: ${last.hash} ${last.subject}` : "No commits yet."));
11078
+ const row = make("div", "git-operation-actions");
11079
+ row.append(gitToolsButton(
11080
+ "Undo last commit (keep changes)",
11081
+ { disabled: busy || !data.canUndoLastCommit, title: data.canUndoLastCommit ? "git reset --soft HEAD~1" : "Requires an unpushed commit with a parent and no operation in progress." },
11082
+ () => runGitToolAction("undo", {
11083
+ url: "/api/git-undo/last-commit",
11084
+ body: { confirmed: true },
11085
+ confirm: [
11086
+ `Undo the last commit in ${data.root}?`,
11087
+ "",
11088
+ `Commit: ${last?.hash || ""} ${last?.subject || ""}`,
11089
+ "Command: git reset --soft HEAD~1 (the commit's changes stay staged)",
11090
+ "Restore afterwards with: git reset --soft ORIG_HEAD",
11091
+ ].join("\n"),
11092
+ success: "Undid the last commit; its changes remain staged.",
11093
+ successMessage: (response) => {
11094
+ const undone = response.data?.undoneCommit;
11095
+ const restore = response.data?.restoreCommand || "git reset --soft ORIG_HEAD";
11096
+ return `Undid commit ${undone?.hash || ""} "${undone?.subject || ""}"; its changes remain staged. Restore with: ${restore}`;
11097
+ },
11098
+ refreshChanges: true,
11099
+ }),
11100
+ ));
11101
+ row.append(gitToolsButton(
11102
+ "Amend last commit message",
11103
+ { disabled: busy || !data.canAmendMessage, title: data.canAmendMessage ? "git commit --amend -m <message>" : "Requires an unpushed commit and an empty staging area." },
11104
+ () => {
11105
+ const message = window.prompt("New commit message:", last?.subject || "");
11106
+ if (!message || !message.trim()) return;
11107
+ runGitToolAction("undo", {
11108
+ url: "/api/git-undo/amend-message",
11109
+ body: { confirmed: true, message: message.trim() },
11110
+ confirm: `Rewrite the last commit message?\n\nOld: ${last?.subject || ""}\nNew: ${message.trim()}`,
11111
+ success: "Amended the last commit message.",
11112
+ successMessage: (response) => {
11113
+ const previous = response.data?.previousCommit;
11114
+ const restore = response.data?.restoreCommand || "git reset --soft ORIG_HEAD";
11115
+ return `Amended the last commit message${previous?.hash ? ` (was ${previous.hash} "${previous.subject}")` : ""}. Restore with: ${restore}`;
11116
+ },
11117
+ });
11118
+ },
11119
+ ));
11120
+ body.append(row);
11121
+ const reflog = gitToolsState.cache.reflog;
11122
+ if (reflog?.entries?.length) {
11123
+ const details = make("details", "git-tools-item");
11124
+ details.append(make("summary", "git-tools-item-summary", `Recent HEAD history (${reflog.entries.length})`));
11125
+ details.append(make("pre", "git-conflict-preview", reflog.entries.map((entry) => `${entry.selector}\t${entry.hash}\t${entry.subject}`).join("\n")));
11126
+ body.append(details);
11127
+ body.append(make("div", "git-tools-note", "Recovery from here is read-only: copy a hash and use git reset/cherry-pick in a terminal."));
11128
+ }
11129
+ return body;
11130
+ }
11131
+
11132
+ function renderGitWorktreeTools(body, data, busy) {
11133
+ const worktrees = data.worktrees || [];
11134
+ for (const worktree of worktrees) {
11135
+ const item = make("div", "git-tools-row");
11136
+ const health = [
11137
+ worktree.isMainWorktree ? "main" : "",
11138
+ worktree.current ? "current" : "",
11139
+ worktree.detached ? "detached" : "",
11140
+ worktree.locked ? `locked${worktree.lockedReason ? `: ${worktree.lockedReason}` : ""}` : "",
11141
+ worktree.prunable ? "prunable" : "",
11142
+ ].filter(Boolean).join(" · ");
11143
+ item.append(
11144
+ make("span", "git-tools-item-ref", worktree.branch || "detached"),
11145
+ make("span", "git-tools-item-subject", `${normalizeDisplayPath(worktree.path)}${health ? ` · ${health}` : ""}`),
11146
+ );
11147
+ if (!worktree.isMainWorktree && !worktree.current) {
11148
+ const actions = gitFileActionButtons([
11149
+ {
11150
+ label: "Remove",
11151
+ className: "danger",
11152
+ title: `git worktree remove ${worktree.path}`,
11153
+ onClick: () => runGitToolAction("worktrees", {
11154
+ method: "DELETE",
11155
+ url: "/api/git-worktrees",
11156
+ body: { path: worktree.path, confirmed: true },
11157
+ confirm: [
11158
+ `Remove worktree ${worktree.path}?`,
11159
+ "",
11160
+ `Branch: ${worktree.branch || "detached"}`,
11161
+ "This deletes the checkout directory. Dirty worktrees and worktrees with open tabs are refused.",
11162
+ ].join("\n"),
11163
+ success: `Removed worktree ${worktree.path}.`,
11164
+ }),
11165
+ },
11166
+ ]);
11167
+ if (actions) item.append(actions);
11168
+ }
11169
+ body.append(item);
11170
+ }
11171
+ const row = make("div", "git-operation-actions");
11172
+ row.append(gitToolsButton("Prune stale worktrees…", { disabled: busy, title: "git worktree prune (with dry-run preview)" }, async () => {
11173
+ const tabId = gitChangesState.tabId || activeTabId;
11174
+ try {
11175
+ const preview = await api("/api/git-worktrees/prune", { tabId });
11176
+ const previewData = preview?.data || preview || {};
11177
+ const output = String(previewData.output || "").trim();
11178
+ const prunable = previewData.prunable || [];
11179
+ if (!output && !prunable.length) {
11180
+ window.alert("No stale worktree records to prune.");
11181
+ return;
11182
+ }
11183
+ const lines = prunable.map((item) => `${item.path}${item.reason ? ` (${item.reason})` : ""}`).join("\n");
11184
+ runGitToolAction("worktrees", {
11185
+ url: "/api/git-worktrees/prune",
11186
+ body: { confirmed: true },
11187
+ confirm: `Prune stale worktree records?\n\nDry run:\n${output || lines || "(no output)"}\n\nThis removes administrative records for worktree directories that no longer exist.`,
11188
+ success: "Pruned stale worktree records.",
11189
+ });
11190
+ } catch (error) {
11191
+ gitToolsState.notice.worktrees = error.message || String(error);
11192
+ renderGitChangesDialog();
11193
+ }
11194
+ }));
11195
+ body.append(row);
11196
+ return body;
11197
+ }
11198
+
11199
+ function renderGitSubmoduleTools(body, data, busy) {
11200
+ if (!data.hasSubmodules) {
11201
+ body.append(make("div", "git-changes-empty", "This repository has no submodules."));
11202
+ return body;
11203
+ }
11204
+ for (const submodule of data.submodules || []) {
11205
+ const item = make("div", "git-tools-row");
11206
+ item.append(
11207
+ make("span", "git-tools-item-ref", submodule.state),
11208
+ make("span", "git-tools-item-subject", `${submodule.path} · ${String(submodule.sha || "").slice(0, 10)}${submodule.describe ? ` · ${submodule.describe}` : ""}`),
11209
+ );
11210
+ const actions = gitFileActionButtons([
11211
+ {
11212
+ label: "Open tab",
11213
+ title: "Open a Web UI tab rooted at this submodule",
11214
+ onClick: () => {
11215
+ const root = String(data.root || "").replace(/\/+$/, "");
11216
+ closeGitChangesDialog();
11217
+ createTerminalTab(`${root}/${submodule.path}`).catch((error) => addEvent(error.message || String(error), "error"));
11218
+ },
11219
+ },
11220
+ { label: "Copy path", title: "Copy the submodule path", onClick: () => copyGitPathToClipboard(submodule.path) },
11221
+ ]);
11222
+ if (actions) item.append(actions);
11223
+ body.append(item);
11224
+ }
11225
+ const row = make("div", "git-operation-actions");
11226
+ row.append(gitToolsButton("Update / init recursively…", { disabled: busy, title: "git submodule update --init --recursive" }, () =>
11227
+ runGitToolAction("submodules", {
11228
+ url: "/api/git-submodules/update",
11229
+ body: { confirmed: true },
11230
+ confirm: "Run git submodule update --init --recursive?\n\nThis can check out new commits in every submodule and may take a while.",
11231
+ success: "Updated submodules recursively.",
11232
+ refreshChanges: true,
11233
+ })));
11234
+ body.append(row);
11235
+ return body;
11236
+ }
11237
+
11238
+ function renderGitTagTools(body, data, busy) {
11239
+ const tags = data.tags || [];
11240
+ if (!tags.length) body.append(make("div", "git-changes-empty", "No tags."));
11241
+ for (const tag of tags.slice(0, 15)) {
11242
+ const item = make("div", "git-tools-row");
11243
+ item.append(
11244
+ make("span", "git-tools-item-ref", tag.name),
11245
+ make("span", "git-tools-item-subject", [tag.annotated ? "annotated" : "lightweight", tag.target ? `@ ${tag.target}` : "", tag.atHead ? "at HEAD" : "", tag.date || ""].filter(Boolean).join(" · ")),
11246
+ );
11247
+ body.append(item);
11248
+ }
11249
+ const row = make("div", "git-operation-actions");
11250
+ row.append(gitToolsButton("Create annotated tag…", { disabled: busy, title: "git tag -a <name> -m <message> (never pushed automatically)" }, () => {
11251
+ const name = window.prompt("Tag name (annotated tag at HEAD):", "");
11252
+ if (!name || !name.trim()) return;
11253
+ const message = window.prompt("Tag message:", name.trim());
11254
+ if (message === null) return;
11255
+ runGitToolAction("tags", {
11256
+ url: "/api/git-tags/create",
11257
+ body: { confirmed: true, name: name.trim(), message: (message || name).trim() },
11258
+ confirm: `Create annotated tag ${name.trim()} at HEAD?\n\nTags are not pushed automatically; push explicitly with: git push origin ${name.trim()}`,
11259
+ success: `Created tag ${name.trim()}.`,
11260
+ });
11261
+ }));
11262
+ body.append(row);
11263
+ return body;
11264
+ }
11265
+
11266
+ function renderGitSigningTools(body, data) {
11267
+ body.append(make("div", "git-tools-note", `commit.gpgsign: ${data.commitSignRequired ? "true" : "false"} · gpg.format: ${data.gpgFormat} · user.signingkey: ${data.signingKey}`));
11268
+ if (data.lastCommit) body.append(make("div", "git-tools-note", `Last commit ${data.lastCommit.hash}: signature state ${data.lastCommit.signState}${data.lastCommit.signer ? ` (${data.lastCommit.signer})` : ""}`));
11269
+ body.append(make("div", `git-tools-note${data.mismatch ? " error" : ""}`, data.mismatch ? "Signing mismatch: signing is required but the last commit is not validly signed." : "No signing mismatch detected."));
11270
+ for (const suggestion of data.suggestions || []) {
11271
+ const item = make("div", "git-tools-row");
11272
+ item.append(make("span", "git-tools-item-subject", suggestion.label), make("code", "git-tools-command", suggestion.command));
11273
+ const actions = gitFileActionButtons([
11274
+ { label: "Copy", title: "Copy this command", onClick: () => navigator.clipboard?.writeText(suggestion.command).catch(() => {}) },
11275
+ ]);
11276
+ if (actions) item.append(actions);
11277
+ body.append(item);
11278
+ }
11279
+ body.append(make("div", "git-tools-note", "Commands are copyable only; config is never rewritten automatically."));
11280
+ return body;
11281
+ }
11282
+
11283
+ function renderGitToolsSectionBody(key) {
11284
+ const body = make("div", "git-tools-body");
11285
+ const notice = gitToolsState.notice[key];
11286
+ if (notice) body.append(make("div", "git-changes-empty error", notice));
11287
+ const data = gitToolsState.cache[key];
11288
+ const busy = gitToolsState.busy.has(key) || gitToolsState.busy.has(`load:${key}`);
11289
+ if (!data) {
11290
+ if (!notice) body.append(make("div", "git-changes-empty", "Loading…"));
11291
+ return body;
11292
+ }
11293
+ switch (key) {
11294
+ case "stash":
11295
+ return renderGitStashTools(body, data, busy);
11296
+ case "undo":
11297
+ return renderGitUndoTools(body, data, busy);
11298
+ case "worktrees":
11299
+ return renderGitWorktreeTools(body, data, busy);
11300
+ case "submodules":
11301
+ return renderGitSubmoduleTools(body, data, busy);
11302
+ case "tags":
11303
+ return renderGitTagTools(body, data, busy);
11304
+ case "signing":
11305
+ return renderGitSigningTools(body, data);
11306
+ default:
11307
+ return body;
11308
+ }
11309
+ }
11310
+
11311
+ function renderGitToolsSection() {
11312
+ const wrapper = make("section", "git-tools");
11313
+ wrapper.append(make("div", "git-diff-section-heading git-tools-heading", "Git tools"));
11314
+ for (const section of GIT_TOOLS_SECTIONS) {
11315
+ const details = make("details", "git-tools-section");
11316
+ details.dataset.gitTools = section.key;
11317
+ details.open = gitToolsState.openSections.has(section.key);
11318
+ const summary = make("summary", "git-tools-summary");
11319
+ summary.append(make("span", "git-tools-title", section.title), make("span", "git-tools-detail", section.detail));
11320
+ details.append(summary);
11321
+ if (details.open) details.append(renderGitToolsSectionBody(section.key));
11322
+ details.addEventListener("toggle", () => {
11323
+ if (details.open) {
11324
+ if (gitToolsState.openSections.has(section.key)) return;
11325
+ gitToolsState.openSections.add(section.key);
11326
+ loadGitToolsSection(section.key);
11327
+ renderGitChangesDialog();
11328
+ } else {
11329
+ gitToolsState.openSections.delete(section.key);
11330
+ }
11331
+ });
11332
+ wrapper.append(details);
11333
+ }
11334
+ return wrapper;
11335
+ }
11336
+
11337
+ // Route the git+ chip to the tools section matching its leading indicator
11338
+ // (📦 stash, 🧩 submodules, 🔓 signing, 🏷 tag, 🌳 worktrees).
11339
+ function gitToolsSectionForExtraChip(value = "") {
11340
+ const text = String(value || "");
11341
+ if (text.includes("📦")) return "stash";
11342
+ if (text.includes("🧩")) return "submodules";
11343
+ if (text.includes("🔓")) return "signing";
11344
+ if (text.includes("🏷")) return "tags";
11345
+ if (text.includes("🌳")) return "worktrees";
11346
+ return "stash";
11347
+ }
11348
+
11349
+ function openGitToolsFromFooter(section = "stash") {
11350
+ openGitChangesDialog();
11351
+ gitToolsState.openSections.add(section);
11352
+ loadGitToolsSection(section);
11353
+ renderGitChangesDialog();
11354
+ }
11355
+
9551
11356
  function gitFooterFallbackMessage() {
9552
11357
  if (isOptionalFeatureDisabled("gitFooterStatus")) return "";
9553
11358
  const tabContext = activeTabContext();
@@ -10010,6 +11815,7 @@ function applyOptimisticGitFooterBranch(branch, tabContext = activeTabContext())
10010
11815
  generatedAt: Date.now(),
10011
11816
  main: payload.main,
10012
11817
  meta: payload.meta.map((chip) => chip.key === "git" ? { ...chip, value: nextBranch, title: `git branch: ${nextBranch}` } : chip),
11818
+ visibility: payload.visibility,
10013
11819
  };
10014
11820
  const nextRaw = JSON.stringify(nextPayload);
10015
11821
  statusEntries.set(GIT_FOOTER_WEBUI_STATUS_KEY, nextRaw);
@@ -10108,15 +11914,33 @@ function footerBranchAgentWarningLines(tabContext = activeTabContext()) {
10108
11914
  ];
10109
11915
  }
10110
11916
 
11917
+ function footerBranchDirtySummaryLines() {
11918
+ const changesChip = parseGitFooterWebuiPayload()?.meta?.find((chip) => chip.key === "changes");
11919
+ const files = Array.isArray(changesChip?.files) ? changesChip.files : [];
11920
+ if (!files.length) return [];
11921
+ const counts = {};
11922
+ for (const file of files) counts[file.kind] = (counts[file.kind] || 0) + 1;
11923
+ const parts = FOOTER_CHANGED_FILE_KIND_ORDER
11924
+ .filter((kind) => counts[kind])
11925
+ .map((kind) => `${counts[kind]} ${FOOTER_CHANGED_FILE_KIND_LABELS[kind]?.toLowerCase() || kind}`);
11926
+ const total = changesChip?.filesTruncated && changesChip?.filesTotal ? changesChip.filesTotal : files.length;
11927
+ return [
11928
+ `Dirty working tree: ${total} changed file${total === 1 ? "" : "s"} (${parts.join(", ")}).`,
11929
+ "Switching branches carries these changes along; consider a worktree instead.",
11930
+ ];
11931
+ }
11932
+
10111
11933
  function confirmFooterGitBranchAction(branch, { create = false, requireConfirm = false, tabContext = activeTabContext() } = {}) {
10112
11934
  const branchName = cleanStatusText(branch);
10113
11935
  const warningLines = footerBranchAgentWarningLines(tabContext);
10114
- if (!requireConfirm && warningLines.length === 0) return true;
11936
+ const dirtyLines = footerBranchDirtySummaryLines();
11937
+ if (!requireConfirm && warningLines.length === 0 && dirtyLines.length === 0) return true;
10115
11938
  const action = create ? "Create and switch to new git branch" : "Switch git branch";
10116
11939
  const message = [
10117
11940
  `${action}: ${branchName}?`,
10118
11941
  "",
10119
11942
  `Repository: ${footerBranchPickerState.root || currentGitFooterCacheCwd(tabContext.tabId) || "current tab"}`,
11943
+ ...dirtyLines,
10120
11944
  ...warningLines,
10121
11945
  "",
10122
11946
  "Continue?",
@@ -10503,23 +12327,91 @@ function renderFooterBranchOption(branch, state = footerBranchPickerState) {
10503
12327
  return row;
10504
12328
  }
10505
12329
 
12330
+ async function removeFooterGitWorktree(worktree, tabContext = activeTabContext()) {
12331
+ const tabId = tabContext.tabId || activeTabId;
12332
+ if (!window.confirm([
12333
+ `Remove worktree ${worktree.path}?`,
12334
+ "",
12335
+ `Branch: ${worktree.branch || "detached"}`,
12336
+ "Command: git worktree remove",
12337
+ "This deletes the checkout directory. Dirty worktrees and worktrees with open tabs are refused.",
12338
+ ].join("\n"))) return;
12339
+ footerBranchPickerState = { ...footerBranchPickerState, loading: true, error: "" };
12340
+ renderFooter();
12341
+ try {
12342
+ const response = await api("/api/git-worktrees", { method: "DELETE", body: { path: worktree.path, confirmed: true }, tabId });
12343
+ if (!response.ok) throw new Error(response.error || "Failed to remove the worktree");
12344
+ addEvent(`Removed worktree ${worktree.path}.`, "success");
12345
+ } catch (error) {
12346
+ addEvent(error.message || String(error), "error");
12347
+ }
12348
+ await loadFooterBranchPicker(tabContext).catch(() => {});
12349
+ }
12350
+
12351
+ async function pruneFooterGitWorktrees(tabContext = activeTabContext()) {
12352
+ const tabId = tabContext.tabId || activeTabId;
12353
+ try {
12354
+ const preview = await api("/api/git-worktrees/prune", { tabId });
12355
+ const previewData = preview?.data || {};
12356
+ const prunable = previewData.prunable || [];
12357
+ const output = String(previewData.output || "").trim();
12358
+ if (!prunable.length && !output) {
12359
+ addEvent("No stale worktree records to prune.", "info");
12360
+ return;
12361
+ }
12362
+ const lines = prunable.map((item) => `${item.path}${item.reason ? ` (${item.reason})` : ""}`).join("\n");
12363
+ if (!window.confirm(`Prune stale worktree records?\n\nDry run:\n${output || lines || "(no output)"}\n\nThis removes administrative records for worktree directories that no longer exist.`)) return;
12364
+ const response = await api("/api/git-worktrees/prune", { method: "POST", body: { confirmed: true }, tabId });
12365
+ if (!response.ok) throw new Error(response.error || "Failed to prune worktrees");
12366
+ addEvent("Pruned stale worktree records.", "success");
12367
+ } catch (error) {
12368
+ addEvent(error.message || String(error), "error");
12369
+ }
12370
+ await loadFooterBranchPicker(tabContext).catch(() => {});
12371
+ }
12372
+
10506
12373
  function renderFooterWorktreeList(state = footerBranchPickerState) {
10507
- const worktrees = (state.worktrees || []).filter((item) => item.path && !item.prunable);
10508
- if (worktrees.length <= 1) return null;
12374
+ const allWorktrees = (state.worktrees || []).filter((item) => item.path);
12375
+ const worktrees = allWorktrees.filter((item) => !item.prunable);
12376
+ const prunableCount = allWorktrees.length - worktrees.length;
12377
+ if (worktrees.length <= 1 && prunableCount === 0) return null;
12378
+ const busy = state.loading || !!state.switching;
10509
12379
  const section = make("div", "footer-branch-worktree-section");
10510
12380
  section.append(make("div", "footer-branch-section-title", `Open worktrees (${worktrees.length})`));
10511
12381
  for (const worktree of worktrees.slice(0, 8)) {
10512
12382
  const selected = worktree.current || worktree.path === state.currentWorktreePath;
12383
+ const row = make("div", "footer-branch-option-row");
10513
12384
  const button = make("button", `footer-model-option footer-worktree-option${selected ? " active" : ""}`);
10514
12385
  button.type = "button";
10515
- button.disabled = selected || state.loading || !!state.switching;
12386
+ button.disabled = selected || busy;
10516
12387
  button.title = selected ? `Current worktree: ${worktree.path}` : `Open worktree: ${worktree.path}`;
12388
+ const health = [
12389
+ worktree.detached ? "detached" : "",
12390
+ worktree.locked ? `locked${worktree.lockedReason ? `: ${worktree.lockedReason}` : ""}` : "",
12391
+ ].filter(Boolean).join(" · ");
10517
12392
  button.append(
10518
12393
  make("span", "footer-model-option-main", worktree.branch || "detached"),
10519
- make("span", "footer-model-option-name", `${selected ? "current" : "open"} · ${normalizeDisplayPath(worktree.path)}`),
12394
+ make("span", "footer-model-option-name", `${selected ? "current" : "open"}${health ? ` · ${health}` : ""} · ${normalizeDisplayPath(worktree.path)}`),
10520
12395
  );
10521
12396
  if (!button.disabled) button.addEventListener("click", () => openFooterGitWorktree(worktree.path, { branchName: worktree.branch || "", skipConfirm: true }));
10522
- section.append(button);
12397
+ row.append(button);
12398
+ if (!selected && !worktree.isMainWorktree) {
12399
+ const remove = make("button", "footer-branch-advanced-action footer-worktree-remove", "Remove");
12400
+ remove.type = "button";
12401
+ remove.disabled = busy || worktree.locked;
12402
+ remove.title = worktree.locked ? `Worktree is locked${worktree.lockedReason ? `: ${worktree.lockedReason}` : ""}` : `git worktree remove ${worktree.path}`;
12403
+ remove.addEventListener("click", () => removeFooterGitWorktree(worktree));
12404
+ row.append(remove);
12405
+ }
12406
+ section.append(row);
12407
+ }
12408
+ if (prunableCount > 0) {
12409
+ const prune = make("button", "footer-branch-advanced-action footer-worktree-prune", `Prune ${prunableCount} stale worktree record${prunableCount === 1 ? "" : "s"}…`);
12410
+ prune.type = "button";
12411
+ prune.disabled = busy;
12412
+ prune.title = "git worktree prune (with dry-run preview)";
12413
+ prune.addEventListener("click", () => pruneFooterGitWorktrees());
12414
+ section.append(prune);
10523
12415
  }
10524
12416
  return section;
10525
12417
  }
@@ -17092,13 +18984,33 @@ function assistantThinkingText(part) {
17092
18984
  return typeof part.content === "string" ? part.content : "";
17093
18985
  }
17094
18986
 
18987
+ function stripEmptyHtmlComments(text) {
18988
+ return String(text || "")
18989
+ .replace(/^[^\S\n]*<!--[\s\r\n]*-->[^\S\n]*(?:\n|$)/gm, "")
18990
+ .replace(/<!--[\s\r\n]*-->/g, "")
18991
+ .replace(/\n[^\S\n]*(?:\n[^\S\n]*){2,}/g, "\n\n");
18992
+ }
18993
+
17095
18994
  function visibleThinkingText(text) {
17096
- const value = String(text || "");
18995
+ const value = stripEmptyHtmlComments(text);
17097
18996
  const trimmed = value.trim();
17098
18997
  if (!trimmed || trimmed === UNEXPOSED_THINKING_TEXT) return "";
17099
18998
  return value;
17100
18999
  }
17101
19000
 
19001
+ function renderThinkingMarkdown(block, text) {
19002
+ if (!block) return;
19003
+ block._rawThinkingText = String(text || "");
19004
+ renderMarkdown(block, block._rawThinkingText);
19005
+ }
19006
+
19007
+ function appendThinkingMarkdown(parent, text) {
19008
+ const block = appendMarkdown(parent, text);
19009
+ block.classList.add("thinking-text");
19010
+ block._rawThinkingText = String(text || "");
19011
+ return block;
19012
+ }
19013
+
17102
19014
  function escapeRegExp(value) {
17103
19015
  return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
17104
19016
  }
@@ -18254,7 +20166,7 @@ function appendMessage(message, { streaming = false, messageIndex = -1, transien
18254
20166
  bubble._toolRenderSignature = toolExecutionRenderSignature(message);
18255
20167
  } else if (message.role === "thinking") {
18256
20168
  const thinkingText = visibleThinkingText(message.thinking || textFromContent(message.content));
18257
- if (thinkingOutputVisible && thinkingText) appendText(body, thinkingText, "thinking-text");
20169
+ if (thinkingOutputVisible && thinkingText) appendThinkingMarkdown(body, thinkingText);
18258
20170
  } else if (message.role === "toolCall") {
18259
20171
  renderToolCallMessageBody(body, message);
18260
20172
  } else if (message.role === "assistantEvent") {
@@ -19280,7 +21192,7 @@ function updateOptionalFeatureAvailability() {
19280
21192
  optionalFeatureAvailability.workflows = hasAvailableCommand("workflow") || hasAvailableCommand("workflow-clear") || optionalFeatureAvailability.workflows || widgets.has("workflow") || widgets.has("workflow:subprocess");
19281
21193
  optionalFeatureAvailability.safetyGuard = hasAvailableCommand("safety-guard") || optionalFeatureAvailability.safetyGuard || statusEntries.has("safety-guard");
19282
21194
  optionalFeatureAvailability.statsCommand = hasAvailableCommand("stats");
19283
- optionalFeatureAvailability.gitFooterStatus = hasAvailableCommand("git-footer-refresh") || optionalFeatureAvailability.gitFooterStatus || statusEntries.has("git-footer") || statusEntries.has(GIT_FOOTER_WEBUI_STATUS_KEY);
21195
+ optionalFeatureAvailability.gitFooterStatus = hasAvailableCommand("git-footer-refresh") || hasAvailableCommand("git-footer-visibility") || optionalFeatureAvailability.gitFooterStatus || statusEntries.has("git-footer") || statusEntries.has(GIT_FOOTER_WEBUI_STATUS_KEY);
19284
21196
  optionalFeatureAvailability.tuiSkillsCommand = hasLoadedRpcCommand("skills");
19285
21197
  optionalFeatureAvailability.todoProgressWidget = hasAvailableCommand("todo-progress-status") || optionalFeatureAvailability.todoProgressWidget || widgets.has("todo-progress");
19286
21198
  optionalFeatureAvailability.tuiToolsCommand = hasLoadedRpcCommand("tools");
@@ -19374,81 +21286,118 @@ function renderOptionalFeaturePanel() {
19374
21286
  elements.optionalFeaturesBox.append(notice);
19375
21287
  }
19376
21288
 
19377
- for (const feature of OPTIONAL_FEATURES) {
19378
- const detected = isOptionalFeatureDetected(feature.id);
19379
- const enabled = isOptionalFeatureEnabled(feature.id);
19380
- const installState = optionalFeatureInstallState(feature.id);
19381
- const installing = optionalFeatureInstallInProgress.has(feature.id) || optionalFeatureInstallIsActive(installState);
19382
- const failed = installState?.phase === "failed";
19383
- const packageStatus = optionalFeaturePackageStatus(feature.id);
19384
- const status = optionalFeatureStatus(feature.id);
19385
- const row = make("div", `optional-feature-row ${status.className}`);
19386
- const tooltip = optionalFeatureTooltip(feature, status);
19387
- row.dataset.tooltip = tooltip;
19388
- row.setAttribute("aria-label", tooltip.replace(/\s+/g, " "));
19389
- row.tabIndex = 0;
19390
-
19391
- const main = make("div", "optional-feature-main");
19392
- const title = make("div", "optional-feature-title");
19393
- title.append(make("strong", undefined, feature.label), make("span", `optional-feature-pill ${status.className}`, status.label));
19394
- main.append(title);
19395
- if (status.detail) {
19396
- const detail = make("div", `optional-feature-detail ${status.className === "failed" ? "error" : ""}`.trim(), status.detail);
19397
- detail.setAttribute("aria-live", installing ? "polite" : "off");
19398
- main.append(detail);
19399
- }
19400
- if (installing) {
19401
- const progress = make("div", "optional-feature-progress");
19402
- progress.setAttribute("aria-hidden", "true");
19403
- progress.append(make("span"));
19404
- main.append(progress);
19405
- }
19406
- if (status.hint) main.append(make("div", "optional-feature-hint", status.hint));
19407
- if (status.command) {
19408
- const command = make("div", "optional-feature-command");
19409
- command.append(make("code", undefined, status.command));
19410
- main.append(command);
19411
- }
19412
- if (failed && installState?.outputTail) main.append(make("pre", "optional-feature-error-output", installState.outputTail));
19413
-
19414
- const actions = make("div", "optional-feature-actions");
19415
- const action = make("button", "optional-feature-action");
19416
- action.type = "button";
19417
- action.disabled = installing;
19418
- if (installing) {
19419
- action.textContent = installState?.actionLabel === "Update" ? "Updating…" : "Installing…";
19420
- action.setAttribute("aria-busy", "true");
19421
- } else if (failed) {
19422
- const retryAsUpdate = installState?.actionLabel === "Update" || packageStatus?.updateAvailable;
19423
- action.textContent = "Retry…";
19424
- action.classList.add(retryAsUpdate ? "update" : "install");
19425
- action.addEventListener("click", () => installOptionalFeature(feature.id, { update: retryAsUpdate }));
19426
- } else if (packageStatus?.updateAvailable) {
19427
- action.textContent = "Update…";
19428
- action.classList.add("update");
19429
- action.addEventListener("click", () => installOptionalFeature(feature.id, { update: true }));
19430
- } else if (detected) {
19431
- action.textContent = enabled ? "Disable" : "Enable";
19432
- action.addEventListener("click", () => setOptionalFeatureDisabled(feature.id, enabled));
19433
- } else if (packageStatus?.installed) {
19434
- action.textContent = "Reload";
19435
- action.addEventListener("click", () => sendPrompt("prompt", "/reload"));
19436
- } else {
19437
- action.textContent = "Install…";
19438
- action.classList.add("install");
19439
- action.addEventListener("click", () => installOptionalFeature(feature.id));
19440
- }
19441
- actions.append(action);
19442
- if (status.command) {
19443
- const copyCommand = make("button", "optional-feature-action copy-command", "Copy cmd");
19444
- copyCommand.type = "button";
19445
- copyCommand.addEventListener("click", () => copyOptionalFeatureInstallCommand(feature.id));
19446
- actions.append(copyCommand);
19447
- }
21289
+ const renderedFeatureIds = new Set();
21290
+ for (const section of OPTIONAL_FEATURE_SECTIONS) {
21291
+ const sectionFeatures = section.featureIds
21292
+ .map((featureId) => OPTIONAL_FEATURE_BY_ID.get(featureId))
21293
+ .filter(Boolean);
21294
+ if (!sectionFeatures.length) continue;
21295
+ for (const feature of sectionFeatures) renderedFeatureIds.add(feature.id);
21296
+ renderOptionalFeatureSection(section, sectionFeatures);
21297
+ }
21298
+
21299
+ const uncategorizedFeatures = OPTIONAL_FEATURES.filter((feature) => !renderedFeatureIds.has(feature.id));
21300
+ if (uncategorizedFeatures.length) {
21301
+ renderOptionalFeatureSection({
21302
+ id: "other",
21303
+ label: "Other",
21304
+ description: "Optional companions that have not been assigned to a type section yet.",
21305
+ }, uncategorizedFeatures);
21306
+ }
21307
+ }
19448
21308
 
19449
- row.append(main, actions);
19450
- elements.optionalFeaturesBox.append(row);
21309
+ function renderOptionalFeatureSection(section, features) {
21310
+ const sectionNode = make("section", "optional-feature-section");
21311
+ sectionNode.dataset.optionalFeatureSection = section.id;
21312
+
21313
+ const header = make("div", "optional-feature-section-header");
21314
+ header.append(
21315
+ make("div", "optional-feature-section-title", section.label),
21316
+ make("span", "optional-feature-section-count", String(features.length)),
21317
+ );
21318
+ sectionNode.append(header);
21319
+ if (section.description) sectionNode.append(make("div", "optional-feature-section-description", section.description));
21320
+
21321
+ const list = make("div", "optional-feature-section-list");
21322
+ for (const feature of features) list.append(renderOptionalFeatureRow(feature));
21323
+ sectionNode.append(list);
21324
+ elements.optionalFeaturesBox.append(sectionNode);
21325
+ }
21326
+
21327
+ function renderOptionalFeatureRow(feature) {
21328
+ const detected = isOptionalFeatureDetected(feature.id);
21329
+ const enabled = isOptionalFeatureEnabled(feature.id);
21330
+ const installState = optionalFeatureInstallState(feature.id);
21331
+ const installing = optionalFeatureInstallInProgress.has(feature.id) || optionalFeatureInstallIsActive(installState);
21332
+ const failed = installState?.phase === "failed";
21333
+ const packageStatus = optionalFeaturePackageStatus(feature.id);
21334
+ const status = optionalFeatureStatus(feature.id);
21335
+ const row = make("div", `optional-feature-row ${status.className}`);
21336
+ const tooltip = optionalFeatureTooltip(feature, status);
21337
+ row.dataset.tooltip = tooltip;
21338
+ row.setAttribute("aria-label", tooltip.replace(/\s+/g, " "));
21339
+ row.tabIndex = 0;
21340
+
21341
+ const main = make("div", "optional-feature-main");
21342
+ const title = make("div", "optional-feature-title");
21343
+ title.append(make("strong", undefined, feature.label), make("span", `optional-feature-pill ${status.className}`, status.label));
21344
+ main.append(title);
21345
+ if (status.detail) {
21346
+ const detail = make("div", `optional-feature-detail ${status.className === "failed" ? "error" : ""}`.trim(), status.detail);
21347
+ detail.setAttribute("aria-live", installing ? "polite" : "off");
21348
+ main.append(detail);
21349
+ }
21350
+ if (installing) {
21351
+ const progress = make("div", "optional-feature-progress");
21352
+ progress.setAttribute("aria-hidden", "true");
21353
+ progress.append(make("span"));
21354
+ main.append(progress);
21355
+ }
21356
+ if (status.hint) main.append(make("div", "optional-feature-hint", status.hint));
21357
+ if (status.command) {
21358
+ const command = make("div", "optional-feature-command");
21359
+ command.append(make("code", undefined, status.command));
21360
+ main.append(command);
21361
+ }
21362
+ if (failed && installState?.outputTail) main.append(make("pre", "optional-feature-error-output", installState.outputTail));
21363
+
21364
+ const actions = make("div", "optional-feature-actions");
21365
+ const action = make("button", "optional-feature-action");
21366
+ action.type = "button";
21367
+ action.disabled = installing;
21368
+ if (installing) {
21369
+ action.textContent = installState?.actionLabel === "Update" ? "Updating…" : "Installing…";
21370
+ action.setAttribute("aria-busy", "true");
21371
+ } else if (failed) {
21372
+ const retryAsUpdate = installState?.actionLabel === "Update" || packageStatus?.updateAvailable;
21373
+ action.textContent = "Retry…";
21374
+ action.classList.add(retryAsUpdate ? "update" : "install");
21375
+ action.addEventListener("click", () => installOptionalFeature(feature.id, { update: retryAsUpdate }));
21376
+ } else if (packageStatus?.updateAvailable) {
21377
+ action.textContent = "Update…";
21378
+ action.classList.add("update");
21379
+ action.addEventListener("click", () => installOptionalFeature(feature.id, { update: true }));
21380
+ } else if (detected) {
21381
+ action.textContent = enabled ? "Disable" : "Enable";
21382
+ action.addEventListener("click", () => setOptionalFeatureDisabled(feature.id, enabled));
21383
+ } else if (packageStatus?.installed) {
21384
+ action.textContent = "Reload";
21385
+ action.addEventListener("click", () => sendPrompt("prompt", "/reload"));
21386
+ } else {
21387
+ action.textContent = "Install…";
21388
+ action.classList.add("install");
21389
+ action.addEventListener("click", () => installOptionalFeature(feature.id));
19451
21390
  }
21391
+ actions.append(action);
21392
+ if (status.command) {
21393
+ const copyCommand = make("button", "optional-feature-action copy-command", "Copy cmd");
21394
+ copyCommand.type = "button";
21395
+ copyCommand.addEventListener("click", () => copyOptionalFeatureInstallCommand(feature.id));
21396
+ actions.append(copyCommand);
21397
+ }
21398
+
21399
+ row.append(main, actions);
21400
+ return row;
19452
21401
  }
19453
21402
 
19454
21403
  function renderOptionalFeatureControls() {
@@ -19506,6 +21455,16 @@ function renderOptionalFeatureControls() {
19506
21455
  );
19507
21456
  }
19508
21457
 
21458
+ const hasGitFooterVisibility = isOptionalFeatureEnabled("gitFooterStatus") && gitFooterVisibilityCommandAvailable();
21459
+ if (elements.optionsFooterVisibilityButton) {
21460
+ elements.optionsFooterVisibilityButton.hidden = !hasGitFooterVisibility;
21461
+ setOptionalControlState(
21462
+ elements.optionsFooterVisibilityButton,
21463
+ hasGitFooterVisibility,
21464
+ commandUnavailableMessage("git-footer-visibility"),
21465
+ );
21466
+ }
21467
+
19509
21468
  const hasNaturalConversation = isOptionalFeatureEnabled("naturalConversation") || activeConversationMode().enabled;
19510
21469
  if (elements.optionsConversationModeButton) {
19511
21470
  elements.optionsConversationModeButton.hidden = !hasNaturalConversation;
@@ -20844,7 +22803,8 @@ function ensureStreamingThinkingBubble() {
20844
22803
  if (streamThinkingBubble?.parentElement === elements.chat) return true;
20845
22804
  const created = appendMessage({ role: "thinking", title: "thinking", timestamp: Date.now(), content: "" }, { streaming: true });
20846
22805
  streamThinkingBubble = created.bubble;
20847
- streamThinking = appendText(created.body, "", "thinking-text");
22806
+ streamThinking = make("div", "markdown-body thinking-text");
22807
+ created.body.append(streamThinking);
20848
22808
  renderRunIndicator({ scroll: false });
20849
22809
  scrollChatToBottom();
20850
22810
  return true;
@@ -20852,7 +22812,7 @@ function ensureStreamingThinkingBubble() {
20852
22812
 
20853
22813
  function showStreamingThinking(initialText = "") {
20854
22814
  if (!ensureStreamingThinkingBubble()) return;
20855
- if (initialText && !streamThinking.textContent) streamThinking.textContent = initialText;
22815
+ if (initialText && !streamThinking.textContent) renderThinkingMarkdown(streamThinking, initialText);
20856
22816
  }
20857
22817
 
20858
22818
  function resetStreamBubble() {
@@ -20882,7 +22842,7 @@ function liveStreamRenderActive() {
20882
22842
  * re-append the live thinking/text bubbles so no partial output is lost.
20883
22843
  */
20884
22844
  function restoreStreamRenderAfterChatRebuild() {
20885
- const thinkingText = streamThinking?.textContent || "";
22845
+ const thinkingText = streamThinking?._rawThinkingText || streamThinking?.textContent || "";
20886
22846
  const thinkingComplete = streamThinkingBubble?.classList.contains("complete") === true;
20887
22847
  const toolCallWasVisible = !!(streamToolCallBubble?.parentElement === elements.chat || streamToolCallRawArguments || streamToolCallName);
20888
22848
  streamBubble = null;
@@ -20999,7 +22959,7 @@ function setStreamingThinkingText(text) {
20999
22959
  const thinking = visibleThinkingText(text);
21000
22960
  if (!thinkingOutputVisible || !thinking) return false;
21001
22961
  showStreamingThinking("");
21002
- if (streamThinking) streamThinking.textContent = thinking;
22962
+ if (streamThinking) renderThinkingMarkdown(streamThinking, thinking);
21003
22963
  return true;
21004
22964
  }
21005
22965
 
@@ -21058,8 +23018,7 @@ function handleMessageUpdate(event) {
21058
23018
  const synced = syncStreamingThinkingFromUpdate(event, update);
21059
23019
  if (thinkingOutputVisible && delta && (!synced || !streamThinking?.textContent)) {
21060
23020
  showStreamingThinking("");
21061
- if (streamThinking?.textContent === "Thinking…") streamThinking.textContent = "";
21062
- if (streamThinking) streamThinking.textContent += delta;
23021
+ if (streamThinking) renderThinkingMarkdown(streamThinking, `${streamThinking._rawThinkingText || ""}${delta}`);
21063
23022
  }
21064
23023
  scheduleChatFollowScroll();
21065
23024
  } else if (update.type === "thinking_end") {
@@ -23648,6 +25607,17 @@ elements.optionsExportButton.addEventListener("click", () => runNativeCommandMen
23648
25607
  elements.optionsForkButton.addEventListener("click", () => runNativeCommandMenu("/fork"));
23649
25608
  elements.optionsTreeButton.addEventListener("click", () => runNativeCommandMenu("/tree"));
23650
25609
  elements.optionsStatsButton?.addEventListener("click", () => openStatsOverlay({ refresh: true }));
25610
+ elements.optionsFooterVisibilityButton?.addEventListener("click", openGitFooterVisibilityDialog);
25611
+ elements.gitFooterVisibilitySelectAllButton?.addEventListener("click", () => setGitFooterVisibilitySelection(true));
25612
+ elements.gitFooterVisibilitySelectNoneButton?.addEventListener("click", () => setGitFooterVisibilitySelection(false));
25613
+ elements.gitFooterVisibilityCloseButton?.addEventListener("click", closeGitFooterVisibilityDialog);
25614
+ elements.gitFooterVisibilityResetButton?.addEventListener("click", () => resetGitFooterVisibilityDialog());
25615
+ elements.gitFooterVisibilityApplyButton?.addEventListener("click", () => applyGitFooterVisibilityDialog());
25616
+ elements.gitFooterVisibilityDialog?.querySelector("form")?.addEventListener("submit", (event) => event.preventDefault());
25617
+ elements.gitFooterVisibilityDialog?.addEventListener("close", () => {
25618
+ gitFooterVisibilityDirty = false;
25619
+ gitFooterVisibilityApplyInFlight = false;
25620
+ });
23651
25621
  elements.statsOverlayRefreshButton?.addEventListener("click", () => requestStatsOverlayRefresh());
23652
25622
  elements.statsOverlayScope?.addEventListener("change", () => {
23653
25623
  const custom = elements.statsOverlayScope?.value === "custom";
@@ -24447,6 +26417,7 @@ window.addEventListener("blur", () => {
24447
26417
  });
24448
26418
 
24449
26419
  elements.gitChangesRefreshButton?.addEventListener("click", refreshGitChangesDialog);
26420
+ elements.gitChangesFetchButton?.addEventListener("click", () => fetchGitChangesDialog().catch((error) => addEvent(error.message || String(error), "error")));
24450
26421
  elements.gitChangesPullButton?.addEventListener("click", () => pullGitChangesDialog().catch((error) => addEvent(error.message || String(error), "error")));
24451
26422
  elements.gitChangesCloseButton?.addEventListener("click", closeGitChangesDialog);
24452
26423
  elements.gitChangesBody?.addEventListener("scroll", updateGitChangesCurrentFileHeader, { passive: true });
@@ -24485,6 +26456,9 @@ elements.refreshClaudeUsageButton?.addEventListener("click", () => {
24485
26456
  refreshClaudeUsage().finally(() => scheduleRefreshClaudeUsage());
24486
26457
  });
24487
26458
  elements.fileTreeRefreshButton?.addEventListener("click", () => refreshFileTreeRoot().catch((error) => addEvent(error.message || String(error), "error")));
26459
+ elements.fileTreeRoot?.addEventListener("dragover", handleFileTreeRootDragOver);
26460
+ elements.fileTreeRoot?.addEventListener("dragleave", handleFileTreeRootDragLeave);
26461
+ elements.fileTreeRoot?.addEventListener("drop", (event) => handleFileTreeRootDrop(event).catch((error) => addEvent(error.message || String(error), "error")));
24488
26462
  elements.fileTreeSearchInput?.addEventListener("input", () => scheduleFileTreeSearch());
24489
26463
  elements.fileTreeSearchInput?.addEventListener("keydown", (event) => {
24490
26464
  if (event.key === "Enter") {
@@ -24505,6 +26479,8 @@ elements.fileContextMenu?.addEventListener("click", (event) => {
24505
26479
  const action = button.dataset.fileMenuAction || "";
24506
26480
  if (action === "open-default") openPathInDefaultEditor(entry.path).catch((error) => addEvent(error.message || String(error), "error"));
24507
26481
  else if (action === "open-webui") openFileTreeEntryInWebui(entry).catch((error) => addEvent(error.message || String(error), "error"));
26482
+ else if (action === "move") moveFileTreeEntry(entry).catch((error) => addEvent(error.message || String(error), "error"));
26483
+ else if (action === "delete") deleteFileTreeEntry(entry).catch((error) => addEvent(error.message || String(error), "error"));
24508
26484
  });
24509
26485
  elements.fileViewerOpenDefaultButton?.addEventListener("click", () => openPathInDefaultEditor(currentFileViewerPath()));
24510
26486
  elements.fileViewerResizeHandle?.addEventListener("pointerdown", beginFileViewerResize);