@firstpick/pi-package-webui 0.6.4 → 0.6.6

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
@@ -108,10 +108,12 @@ const elements = {
108
108
  optionsNameButton: $("#optionsNameButton"),
109
109
  optionsCloneButton: $("#optionsCloneButton"),
110
110
  optionsSettingsButton: $("#optionsSettingsButton"),
111
+ optionsGitWorkflowSetupButton: $("#optionsGitWorkflowSetupButton"),
111
112
  optionsExportButton: $("#optionsExportButton"),
112
113
  optionsForkButton: $("#optionsForkButton"),
113
114
  optionsTreeButton: $("#optionsTreeButton"),
114
115
  optionsStatsButton: $("#optionsStatsButton"),
116
+ optionsFooterVisibilityButton: $("#optionsFooterVisibilityButton"),
115
117
  gitWorkflowPanel: $("#gitWorkflowPanel"),
116
118
  gitWorkflowKicker: $("#gitWorkflowKicker"),
117
119
  gitWorkflowTitle: $("#gitWorkflowTitle"),
@@ -132,6 +134,7 @@ const elements = {
132
134
  gitChangesStatus: $("#gitChangesStatus"),
133
135
  gitChangesBody: $("#gitChangesBody"),
134
136
  gitChangesRefreshButton: $("#gitChangesRefreshButton"),
137
+ gitChangesFetchButton: $("#gitChangesFetchButton"),
135
138
  gitChangesPullButton: $("#gitChangesPullButton"),
136
139
  gitChangesCloseButton: $("#gitChangesCloseButton"),
137
140
  modelControlLabel: $("#modelControlLabel"),
@@ -206,6 +209,9 @@ const elements = {
206
209
  sidePanelBackdrop: $("#sidePanelBackdrop"),
207
210
  sidePanel: $("#sidePanel"),
208
211
  stateDetails: $("#stateDetails"),
212
+ subagentsStatus: $("#subagentsStatus"),
213
+ subagentsBox: $("#subagentsBox"),
214
+ subagentCountBadge: $("#subagentCountBadge"),
209
215
  queueBox: $("#queueBox"),
210
216
  queueCountBadge: $("#queueCountBadge"),
211
217
  createPromptListButton: $("#createPromptListButton"),
@@ -278,6 +284,14 @@ const elements = {
278
284
  appRunnerInfoDialog: $("#appRunnerInfoDialog"),
279
285
  appRunnerInfoBody: $("#appRunnerInfoBody"),
280
286
  appRunnerInfoCloseButton: $("#appRunnerInfoCloseButton"),
287
+ gitFooterVisibilityDialog: $("#gitFooterVisibilityDialog"),
288
+ gitFooterVisibilityBody: $("#gitFooterVisibilityBody"),
289
+ gitFooterVisibilityStatus: $("#gitFooterVisibilityStatus"),
290
+ gitFooterVisibilitySelectAllButton: $("#gitFooterVisibilitySelectAllButton"),
291
+ gitFooterVisibilitySelectNoneButton: $("#gitFooterVisibilitySelectNoneButton"),
292
+ gitFooterVisibilityCloseButton: $("#gitFooterVisibilityCloseButton"),
293
+ gitFooterVisibilityResetButton: $("#gitFooterVisibilityResetButton"),
294
+ gitFooterVisibilityApplyButton: $("#gitFooterVisibilityApplyButton"),
281
295
  statsOverlayDialog: $("#statsOverlayDialog"),
282
296
  statsOverlaySubtitle: $("#statsOverlaySubtitle"),
283
297
  statsOverlayScope: $("#statsOverlayScope"),
@@ -297,10 +311,11 @@ let tabDrafts = new Map();
297
311
  let tabAttachments = new Map();
298
312
  let activeTextAttachmentEditor = null;
299
313
  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 };
314
+ 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
315
  let activeFileViewer = null;
302
316
  let fileViewerSelection = null;
303
317
  let fileContextMenuState = null;
318
+ let fileTreeDragState = null;
304
319
  let fileViewerResizeState = null;
305
320
  let fileTreeSearchTimer = null;
306
321
  let fileTreeSearchRequestSerial = 0;
@@ -346,7 +361,8 @@ let foregroundReconcileTimer = null;
346
361
  let eventSource = null;
347
362
  let activeDialog = null;
348
363
  let activeGitPrDialogResolve = null;
349
- let gitChangesState = { loading: false, pulling: false, error: "", message: "", pullResult: null, data: null, tabId: null };
364
+ let gitChangesState = { loading: false, pulling: false, fetching: false, error: "", errorCode: "", errorHint: "", message: "", pullResult: null, data: null, operation: null, lastFetch: null, tabId: null };
365
+ let gitToolsState = { tabId: null, openSections: new Set(), cache: {}, busy: new Set(), notice: {} };
350
366
  let gitChangesRequestSerial = 0;
351
367
  const gitChangesUntrackedContentRequests = new Set();
352
368
  let nativeCommandTabId = null;
@@ -414,6 +430,16 @@ let claudeUsageError = null;
414
430
  let claudeUsageLoading = false;
415
431
  let refreshClaudeUsageTimer = null;
416
432
  let claudeUsageRenderTimer = null;
433
+ let latestSubagents = null;
434
+ let subagentsError = null;
435
+ let subagentsLoading = false;
436
+ let refreshSubagentsTimer = null;
437
+ let subagentOverlaySelection = null;
438
+ let subagentOverlayData = null;
439
+ let subagentOverlayError = "";
440
+ let subagentOverlayLoading = false;
441
+ let subagentOverlayRefreshTimer = null;
442
+ let subagentOverlayRequestSerial = 0;
417
443
  let backendOffline = false;
418
444
  let serverRestartInProgress = false;
419
445
  let updateRequestInProgress = false;
@@ -541,6 +567,58 @@ const GIT_FOOTER_WEBUI_PAYLOAD_TYPE = "firstpick.git-footer-status.footer";
541
567
  const GIT_FOOTER_WEBUI_PAYLOAD_VERSION = 1;
542
568
  const GIT_FOOTER_WEBUI_PAYLOAD_CACHE_KEY = "pi-webui-git-footer-webui-payload-cache";
543
569
  const GIT_FOOTER_STATUS_SETUP_STORAGE_KEY = "pi-webui-git-footer-status-setup";
570
+ const GIT_FOOTER_WEBUI_VISIBILITY_DEFAULTS = Object.freeze({
571
+ tokens: true,
572
+ cache: true,
573
+ pi: true,
574
+ speed: true,
575
+ cost: true,
576
+ context: true,
577
+ model: true,
578
+ thinking: true,
579
+ cwd: true,
580
+ "cwd-branch": true,
581
+ "git-status": true,
582
+ "extension-statuses": true,
583
+ git: true,
584
+ "git-state": true,
585
+ sync: true,
586
+ changes: true,
587
+ "git-extra": true,
588
+ worktree: true,
589
+ "context-meta": true,
590
+ "git-branch-indicator": false,
591
+ "git-detached": true,
592
+ "git-operation": true,
593
+ "git-ahead": true,
594
+ "git-behind": true,
595
+ "git-upstream": true,
596
+ "git-staged": true,
597
+ "git-unstaged": true,
598
+ "git-untracked": true,
599
+ "git-conflicted": true,
600
+ "git-clean": true,
601
+ "git-stash": true,
602
+ "git-submodules": true,
603
+ "git-worktrees": true,
604
+ "git-tag": true,
605
+ "git-last-commit-age": true,
606
+ "git-signing-mismatch": true,
607
+ "webui-fetch-state": true,
608
+ "webui-refresh-button": true,
609
+ "webui-details-button": true,
610
+ "webui-cwd-picker": true,
611
+ "webui-pi-calibration": true,
612
+ "webui-context-auto-compaction": true,
613
+ "webui-branch-picker": true,
614
+ "webui-git-init": true,
615
+ "webui-sync-push": true,
616
+ "webui-changes-modal": true,
617
+ "webui-git-tools-modal": true,
618
+ "webui-model-picker": true,
619
+ "webui-thinking-picker": true,
620
+ "webui-changed-files-popover": true,
621
+ });
544
622
  const GIT_INIT_STACK_STORAGE_KEY = "pi-webui-git-init-stack";
545
623
  const STATS_WEBUI_STATUS_KEY = "stats-webui";
546
624
  const STATS_WEBUI_PAYLOAD_TYPE = "firstpick.pi-extension-stats.overlay";
@@ -569,6 +647,7 @@ const FILE_VIEWER_WIDTH_DEFAULT_PX = 520;
569
647
  const FILE_VIEWER_WIDTH_MIN_PX = 384;
570
648
  const FILE_VIEWER_CONTEXT_RADIUS_LINES = 6;
571
649
  const FILE_TREE_ROOT_PATH = "";
650
+ const FILE_TREE_DRAG_MIME = "application/x-pi-webui-file-path";
572
651
  const POINTER_ACTIVATION_SELECTOR = "button, a[href], input, select, textarea, summary, [role='button'], [tabindex]:not([tabindex='-1'])";
573
652
  const POINTER_ACTIVATION_RENDER_DEFER_MAX_MS = 1200;
574
653
  const PROMPT_HISTORY_LIMIT_PER_TAB = 50;
@@ -611,6 +690,10 @@ const CODEX_USAGE_REFRESH_MS = 5 * 60 * 1000;
611
690
  const CODEX_USAGE_RENDER_TICK_MS = 30 * 1000;
612
691
  const CLAUDE_USAGE_REFRESH_MS = 5 * 60 * 1000;
613
692
  const CLAUDE_USAGE_RENDER_TICK_MS = 30 * 1000;
693
+ const SUBAGENTS_ACTIVE_REFRESH_MS = 1500;
694
+ const SUBAGENTS_IDLE_REFRESH_MS = 4000;
695
+ const SUBAGENTS_HIDDEN_REFRESH_MS = 10_000;
696
+ const SUBAGENT_OVERLAY_REFRESH_MS = 1000;
614
697
  const UPDATE_STATUS_REFRESH_MS = 6 * 60 * 60 * 1000;
615
698
  const UPDATE_STATUS_INITIAL_DELAY_MS = 1800;
616
699
  const RUN_INDICATOR_TICK_MS = 1000;
@@ -798,6 +881,38 @@ const OPTIONAL_FEATURES = [
798
881
  },
799
882
  ];
800
883
  const OPTIONAL_FEATURE_BY_ID = new Map(OPTIONAL_FEATURES.map((feature) => [feature.id, feature]));
884
+ const OPTIONAL_FEATURE_SECTIONS = [
885
+ {
886
+ id: "composer-commands",
887
+ label: "Composer & commands",
888
+ description: "Input helpers and lightweight commands that change how prompts and shell actions are launched.",
889
+ featureIds: ["bangCommandAutocomplete", "fishUserBash", "btwCommand"],
890
+ },
891
+ {
892
+ id: "workflows-releases",
893
+ label: "Workflows & releases",
894
+ description: "Guided workflows, task runners, and publishing actions with visible execution state.",
895
+ featureIds: ["gitWorkflow", "workflows", "releaseNpm", "releaseAur"],
896
+ },
897
+ {
898
+ id: "safety-access",
899
+ label: "Safety & access",
900
+ description: "Guardrails and network-facing helpers that affect trust boundaries.",
901
+ featureIds: ["safetyGuard", "remoteWebui"],
902
+ },
903
+ {
904
+ id: "widgets-native-parity",
905
+ label: "UI widgets & native parity",
906
+ description: "Status widgets, dashboards, themes, and browser access to terminal-native controls.",
907
+ featureIds: ["tuiSkillsCommand", "todoProgressWidget", "tuiToolsCommand", "gitFooterStatus", "statsCommand", "themeBundle"],
908
+ },
909
+ {
910
+ id: "conversation",
911
+ label: "Conversation",
912
+ description: "Talk and voice-oriented interaction modes.",
913
+ featureIds: ["naturalConversation"],
914
+ },
915
+ ];
801
916
  const OPTIONAL_COMMAND_FEATURES = new Map([
802
917
  ["bang-refresh", "bangCommandAutocomplete"],
803
918
  ["bang-status", "bangCommandAutocomplete"],
@@ -821,14 +936,15 @@ const OPTIONAL_COMMAND_FEATURES = new Map([
821
936
  ["conversation", "naturalConversation"],
822
937
  ["stats", "statsCommand"],
823
938
  ["git-footer-refresh", "gitFooterStatus"],
939
+ ["git-footer-visibility", "gitFooterStatus"],
824
940
  ["todo-progress-status", "todoProgressWidget"],
825
941
  ]);
826
942
  const HIDDEN_COMMAND_NAMES = new Set(["webui-tree-navigate", "webui-helper"]);
827
943
  HIDDEN_COMMAND_NAMES.add("stats-webui");
828
944
  HIDDEN_COMMAND_NAMES.add("btw-status");
829
945
  HIDDEN_COMMAND_NAMES.add("btw-transfer");
830
- const NATIVE_SELECTOR_COMMANDS = new Set(["model", "settings", "theme", "fork", "clone", "name", "resume", "tree", "login", "logout", "scoped-models", "tools", "skills"]);
831
- const SETTINGS_THINKING_OPTIONS = ["off", "minimal", "low", "medium", "high", "xhigh"];
946
+ const NATIVE_SELECTOR_COMMANDS = new Set(["model", "settings", "git-workflow-setup", "theme", "fork", "clone", "name", "resume", "tree", "login", "logout", "scoped-models", "tools", "skills"]);
947
+ const SETTINGS_THINKING_OPTIONS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
832
948
  const SETTINGS_TRANSPORT_OPTIONS = ["sse", "websocket", "websocket-cached", "auto"];
833
949
  const SETTINGS_HTTP_IDLE_TIMEOUT_OPTIONS = [
834
950
  { value: "30000", label: "30 sec" },
@@ -855,6 +971,8 @@ let optionalFeaturePackageStatusError = "";
855
971
  const gitFooterPayloadRefreshInFlightByTab = new Set();
856
972
  const gitFooterSyncPushInFlightByTab = new Set();
857
973
  const gitFooterPiCalibrationInFlightByTab = new Set();
974
+ let gitFooterVisibilityApplyInFlight = false;
975
+ let gitFooterVisibilityDirty = false;
858
976
 
859
977
  function createGitWorkflowActionsDone(patch = {}) {
860
978
  return {
@@ -923,11 +1041,14 @@ function createGitWorkflowState() {
923
1041
  prBranch: "",
924
1042
  pr: null,
925
1043
  prRequestedAt: 0,
1044
+ preferences: null,
1045
+ verificationConfirmed: false,
926
1046
  };
927
1047
  }
928
1048
 
929
1049
  const gitWorkflowsByTab = new Map();
930
1050
  let gitWorkflow = createGitWorkflowState();
1051
+ let gitWorkflowPreferences = null;
931
1052
 
932
1053
  function gitWorkflowForTab(tabId = activeTabId, { create = true } = {}) {
933
1054
  if (!tabId) return null;
@@ -5389,6 +5510,67 @@ function fileEntryIcon(entry = {}) {
5389
5510
  return "·";
5390
5511
  }
5391
5512
 
5513
+ function normalizeFileTreeGitStatus(status = {}) {
5514
+ if (!status || status.changed !== true) return null;
5515
+ const kind = ["changed", "modified", "staged", "untracked", "conflicted"].includes(String(status.kind || "")) ? String(status.kind) : "changed";
5516
+ return {
5517
+ changed: true,
5518
+ kind,
5519
+ status: String(status.status || "").slice(0, 4),
5520
+ direct: status.direct === true,
5521
+ changedDescendants: Math.max(0, Number(status.changedDescendants || 0) || 0),
5522
+ };
5523
+ }
5524
+
5525
+ function fileTreeGitStatusForEntry(entry = {}) {
5526
+ const own = normalizeFileTreeGitStatus(entry.gitStatus);
5527
+ if (own) return own;
5528
+ return fileTreeState.gitStatusByPath.get(normalizeFileTreePath(entry.path || "")) || null;
5529
+ }
5530
+
5531
+ function fileTreeGitStatusClasses(status) {
5532
+ const normalized = normalizeFileTreeGitStatus(status);
5533
+ if (!normalized) return "";
5534
+ return `git-changed git-${normalized.kind} ${normalized.direct ? "git-direct" : "git-descendants"}`;
5535
+ }
5536
+
5537
+ function fileTreeGitStatusTitle(status) {
5538
+ const normalized = normalizeFileTreeGitStatus(status);
5539
+ if (!normalized) return "";
5540
+ if (normalized.direct) {
5541
+ const state = normalized.status ? ` (${normalized.status})` : "";
5542
+ return `Git ${normalized.kind}${state}`;
5543
+ }
5544
+ const count = normalized.changedDescendants || 0;
5545
+ return count > 0 ? `Git changes in ${count} descendant${count === 1 ? "" : "s"}` : "Git changes in this folder";
5546
+ }
5547
+
5548
+ function fileTreeGitStatusBadge(status) {
5549
+ const normalized = normalizeFileTreeGitStatus(status);
5550
+ if (!normalized) return null;
5551
+ const label = normalized.direct ? (normalized.status || "●") : (normalized.changedDescendants > 1 ? `Δ${normalized.changedDescendants}` : "Δ");
5552
+ const badge = make("span", `file-tree-git-badge ${normalized.kind} ${normalized.direct ? "direct" : "descendants"}`, label);
5553
+ badge.title = fileTreeGitStatusTitle(normalized);
5554
+ badge.setAttribute("aria-label", badge.title);
5555
+ return badge;
5556
+ }
5557
+
5558
+ function updateFileTreeGitStatus(gitStatus, entries = []) {
5559
+ const next = new Map();
5560
+ for (const status of Array.isArray(gitStatus?.entries) ? gitStatus.entries : []) {
5561
+ const path = normalizeFileTreePath(status.path || "");
5562
+ const normalized = normalizeFileTreeGitStatus(status);
5563
+ if (path && normalized) next.set(path, normalized);
5564
+ }
5565
+ for (const entry of entries) {
5566
+ const path = normalizeFileTreePath(entry?.path || "");
5567
+ const normalized = normalizeFileTreeGitStatus(entry?.gitStatus);
5568
+ if (path && normalized) next.set(path, normalized);
5569
+ }
5570
+ fileTreeState.gitStatusRoot = String(gitStatus?.root || "");
5571
+ fileTreeState.gitStatusByPath = next;
5572
+ }
5573
+
5392
5574
  function setFileTreeStatus(message = "", level = "muted") {
5393
5575
  if (!elements.fileTreeStatus) return;
5394
5576
  elements.fileTreeStatus.textContent = message;
@@ -5402,7 +5584,7 @@ function setFileViewerStatus(message = "", level = "muted") {
5402
5584
  }
5403
5585
 
5404
5586
  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 };
5587
+ 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
5588
  }
5407
5589
 
5408
5590
  function fileTreeSearchQueryText() {
@@ -5489,7 +5671,9 @@ function renderFileTree() {
5489
5671
  function appendFileSearchEntry(parent, entry) {
5490
5672
  const path = normalizeFileTreePath(entry.path);
5491
5673
  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" : ""}`);
5674
+ const gitStatus = fileTreeGitStatusForEntry(entry);
5675
+ const gitStatusClasses = fileTreeGitStatusClasses(gitStatus);
5676
+ const item = make("li", `file-tree-node file-tree-search-node ${entry.type || "file"}${gitStatusClasses ? ` ${gitStatusClasses}` : ""}${fileTreeState.selectedPath === path ? " selected" : ""}`);
5493
5677
  item.setAttribute("role", "none");
5494
5678
  const button = make("button", "file-tree-item file-tree-search-item");
5495
5679
  button.type = "button";
@@ -5497,7 +5681,7 @@ function appendFileSearchEntry(parent, entry) {
5497
5681
  button.dataset.type = entry.type || "file";
5498
5682
  button.style.setProperty("--file-tree-depth", "0");
5499
5683
  button.setAttribute("role", "treeitem");
5500
- button.title = [path || ".", entry.error || ""].filter(Boolean).join("\n");
5684
+ button.title = [path || ".", fileTreeGitStatusTitle(gitStatus), entry.error || ""].filter(Boolean).join("\n");
5501
5685
  const label = make("span", "file-tree-search-label");
5502
5686
  label.append(
5503
5687
  make("span", "file-tree-name", entry.name || fileDisplayName(path)),
@@ -5507,6 +5691,8 @@ function appendFileSearchEntry(parent, entry) {
5507
5691
  make("span", "file-tree-icon", fileEntryIcon(entry)),
5508
5692
  label,
5509
5693
  );
5694
+ const gitBadge = fileTreeGitStatusBadge(gitStatus);
5695
+ if (gitBadge) button.append(gitBadge);
5510
5696
  if (entry.type === "file") button.append(make("span", "file-tree-kind", entry.extension || "file"));
5511
5697
  else if (entry.type && entry.type !== "directory") button.append(make("span", "file-tree-kind", entry.type));
5512
5698
  if (entry.error) button.append(make("span", "file-tree-error", entry.error));
@@ -5520,6 +5706,7 @@ function appendFileSearchEntry(parent, entry) {
5520
5706
  else if (entry.type === "file") openFileInViewer(path);
5521
5707
  });
5522
5708
  button.addEventListener("contextmenu", (event) => showFileContextMenu(event, entry));
5709
+ bindFileTreeDragAndDrop(button, item, entry);
5523
5710
  item.append(button);
5524
5711
  parent.append(item);
5525
5712
  }
@@ -5552,7 +5739,9 @@ function appendFileTreeEntry(parent, entry, depth = 0) {
5552
5739
  const isDirectory = entry.type === "directory" || entry.directory === true;
5553
5740
  const expanded = isDirectory && fileTreeState.expanded.has(path);
5554
5741
  const loading = isDirectory && fileTreeState.loading.has(path);
5555
- const item = make("li", `file-tree-node ${entry.type || "file"}${expanded ? " expanded" : ""}${fileTreeState.selectedPath === path ? " selected" : ""}`);
5742
+ const gitStatus = fileTreeGitStatusForEntry(entry);
5743
+ const gitStatusClasses = fileTreeGitStatusClasses(gitStatus);
5744
+ const item = make("li", `file-tree-node ${entry.type || "file"}${gitStatusClasses ? ` ${gitStatusClasses}` : ""}${expanded ? " expanded" : ""}${fileTreeState.selectedPath === path ? " selected" : ""}`);
5556
5745
  item.setAttribute("role", "none");
5557
5746
  const button = make("button", "file-tree-item");
5558
5747
  button.type = "button";
@@ -5561,11 +5750,13 @@ function appendFileTreeEntry(parent, entry, depth = 0) {
5561
5750
  button.style.setProperty("--file-tree-depth", String(depth));
5562
5751
  button.setAttribute("role", "treeitem");
5563
5752
  if (isDirectory) button.setAttribute("aria-expanded", expanded ? "true" : "false");
5564
- button.title = [path || ".", entry.error || ""].filter(Boolean).join("\n");
5753
+ button.title = [path || ".", fileTreeGitStatusTitle(gitStatus), entry.error || ""].filter(Boolean).join("\n");
5565
5754
  button.append(
5566
5755
  make("span", `file-tree-icon ${isDirectory && expanded ? "expanded" : ""}`, loading ? "…" : fileEntryIcon(entry)),
5567
5756
  make("span", "file-tree-name", entry.name || fileDisplayName(path)),
5568
5757
  );
5758
+ const gitBadge = fileTreeGitStatusBadge(gitStatus);
5759
+ if (gitBadge) button.append(gitBadge);
5569
5760
  if (entry.type === "file") button.append(make("span", "file-tree-kind", entry.extension || "file"));
5570
5761
  if (entry.error) button.append(make("span", "file-tree-error", entry.error));
5571
5762
  button.addEventListener("click", () => {
@@ -5579,6 +5770,7 @@ function appendFileTreeEntry(parent, entry, depth = 0) {
5579
5770
  else openFileInViewer(path);
5580
5771
  });
5581
5772
  button.addEventListener("contextmenu", (event) => showFileContextMenu(event, entry));
5773
+ bindFileTreeDragAndDrop(button, item, entry);
5582
5774
  item.append(button);
5583
5775
  if (isDirectory && expanded) {
5584
5776
  const children = fileTreeState.entriesByPath.get(path) || [];
@@ -5611,6 +5803,7 @@ async function loadFileTreeDirectory(path = FILE_TREE_ROOT_PATH, { force = false
5611
5803
  fileTreeState.expanded.clear();
5612
5804
  }
5613
5805
  const entries = Array.isArray(data.entries) ? data.entries : [];
5806
+ updateFileTreeGitStatus(data.gitStatus, entries);
5614
5807
  fileTreeState.entriesByPath.set(normalized, entries);
5615
5808
  setFileTreeStatus(fileTreeEntriesStatus(entries, { truncated: data.truncated, total: data.total || entries.length }));
5616
5809
  return entries;
@@ -5668,6 +5861,7 @@ async function runFileTreeSearch() {
5668
5861
  const data = response.data || {};
5669
5862
  const entries = Array.isArray(data.entries) ? data.entries : [];
5670
5863
  if (data.root) fileTreeState.root = data.root;
5864
+ updateFileTreeGitStatus(data.gitStatus, entries);
5671
5865
  fileTreeState.searchQuery = data.query || query;
5672
5866
  fileTreeState.searchEntries = entries;
5673
5867
  fileTreeState.searchLoading = false;
@@ -5768,6 +5962,352 @@ async function openPathInDefaultEditor(path = currentFileViewerPath()) {
5768
5962
  }
5769
5963
  }
5770
5964
 
5965
+ function filePathWithinOrEqual(filePath = "", parentPath = "") {
5966
+ const path = normalizeFileTreePath(filePath);
5967
+ const parent = normalizeFileTreePath(parentPath);
5968
+ if (!parent) return path === parent;
5969
+ return path === parent || path.startsWith(`${parent}/`);
5970
+ }
5971
+
5972
+ function remapFileTreePathAfterMove(filePath = "", sourcePath = "", destinationPath = "") {
5973
+ const path = normalizeFileTreePath(filePath);
5974
+ const source = normalizeFileTreePath(sourcePath);
5975
+ const destination = normalizeFileTreePath(destinationPath);
5976
+ if (!path || !source || !destination) return path;
5977
+ if (path === source) return destination;
5978
+ return path.startsWith(`${source}/`) ? `${destination}/${path.slice(source.length + 1)}` : path;
5979
+ }
5980
+
5981
+ function fileExtensionForPath(filePath = "") {
5982
+ const name = fileDisplayName(filePath);
5983
+ const dot = name.lastIndexOf(".");
5984
+ return dot > 0 ? name.slice(dot).toLowerCase() : "";
5985
+ }
5986
+
5987
+ function fileLanguageForPath(filePath = "") {
5988
+ const extension = fileExtensionForPath(filePath);
5989
+ return extension === ".md" || extension === ".markdown" ? "markdown" : "text";
5990
+ }
5991
+
5992
+ function fileOperationTypeLabel(entry = {}) {
5993
+ if (entry.type === "directory" || entry.directory === true) return "directory";
5994
+ if (entry.type === "file" || entry.file === true) return "file";
5995
+ return "entry";
5996
+ }
5997
+
5998
+ function fileTreeEntryIsMovable(entry = {}) {
5999
+ const path = normalizeFileTreePath(entry.path || "");
6000
+ return !!path && (entry.type === "file" || entry.file === true || entry.type === "directory" || entry.directory === true);
6001
+ }
6002
+
6003
+ function fileTreeEntryIsDirectory(entry = {}) {
6004
+ return entry.type === "directory" || entry.directory === true;
6005
+ }
6006
+
6007
+ function fileTreeDragSourceFromEvent(event) {
6008
+ const statePath = normalizeFileTreePath(fileTreeDragState?.sourcePath || "");
6009
+ return statePath ? { path: statePath, type: fileTreeDragState?.sourceType || "entry", entry: fileTreeDragState?.entry || null } : null;
6010
+ }
6011
+
6012
+ function fileTreeEntryFromElement(element) {
6013
+ const path = normalizeFileTreePath(element?.dataset?.path || "");
6014
+ const type = element?.dataset?.type || "";
6015
+ return path || type ? { path, type, directory: type === "directory", file: type === "file" } : null;
6016
+ }
6017
+
6018
+ function fileTreeDropTargetFromEvent(event) {
6019
+ const button = event?.target?.closest?.(".file-tree-item");
6020
+ if (!button || !elements.fileTreeRoot?.contains?.(button)) return null;
6021
+ const entry = fileTreeEntryFromElement(button);
6022
+ if (!entry || !fileTreeEntryIsDirectory(entry)) return null;
6023
+ return { entry, item: button.closest(".file-tree-node"), button };
6024
+ }
6025
+
6026
+ function fileTreeCanDropOnDirectory(sourcePath = "", targetDirectoryPath = "", sourceEntry = fileTreeDragState?.entry) {
6027
+ const source = normalizeFileTreePath(sourcePath);
6028
+ const target = normalizeFileTreePath(targetDirectoryPath);
6029
+ if (!source) return false;
6030
+ if (fileParentPath(source) === target) return false;
6031
+ if (fileTreeEntryIsDirectory(sourceEntry || {}) && (target === source || target.startsWith(`${source}/`))) return false;
6032
+ return true;
6033
+ }
6034
+
6035
+ function clearFileTreeDragVisuals() {
6036
+ for (const node of document.querySelectorAll(".file-tree-node.dragging, .file-tree-node.drop-target, .file-tree-node.drop-blocked")) {
6037
+ node.classList.remove("dragging", "drop-target", "drop-blocked");
6038
+ }
6039
+ elements.fileTreeRoot?.classList.remove("drag-root-drop", "drop-blocked");
6040
+ }
6041
+
6042
+ function finishFileTreeDrag() {
6043
+ clearFileTreeDragVisuals();
6044
+ fileTreeDragState = null;
6045
+ }
6046
+
6047
+ function beginFileTreeDrag(event, entry = {}, item) {
6048
+ if (!fileTreeEntryIsMovable(entry)) {
6049
+ event.preventDefault();
6050
+ return;
6051
+ }
6052
+ const sourcePath = normalizeFileTreePath(entry.path || "");
6053
+ closeFileContextMenu();
6054
+ fileTreeDragState = { sourcePath, sourceType: fileOperationTypeLabel(entry), entry: { ...entry, path: sourcePath } };
6055
+ event.dataTransfer.effectAllowed = "move";
6056
+ event.dataTransfer.setData(FILE_TREE_DRAG_MIME, sourcePath);
6057
+ event.dataTransfer.setData("text/plain", sourcePath);
6058
+ item?.classList.add("dragging");
6059
+ setFileTreeStatus(`Drag ${sourcePath} onto a folder or empty file-tree space to move it.`);
6060
+ }
6061
+
6062
+ function updateFileTreeDropTarget(event, entry = {}, item) {
6063
+ const source = fileTreeDragSourceFromEvent(event);
6064
+ if (!source || !fileTreeEntryIsDirectory(entry)) return false;
6065
+ const targetPath = normalizeFileTreePath(entry.path || "");
6066
+ const allowed = fileTreeCanDropOnDirectory(source.path, targetPath, source.entry);
6067
+ for (const node of document.querySelectorAll(".file-tree-node.drop-target, .file-tree-node.drop-blocked")) node.classList.remove("drop-target", "drop-blocked");
6068
+ elements.fileTreeRoot?.classList.remove("drag-root-drop", "drop-blocked");
6069
+ if (!allowed) {
6070
+ item?.classList.add("drop-blocked");
6071
+ event.dataTransfer.dropEffect = "none";
6072
+ return false;
6073
+ }
6074
+ event.preventDefault();
6075
+ event.stopPropagation();
6076
+ event.dataTransfer.dropEffect = "move";
6077
+ item?.classList.add("drop-target");
6078
+ if (fileTreeDragState) fileTreeDragState.targetPath = targetPath;
6079
+ return true;
6080
+ }
6081
+
6082
+ function clearFileTreeDropTarget(event, item) {
6083
+ if (!item?.contains?.(event.relatedTarget)) item?.classList.remove("drop-target", "drop-blocked");
6084
+ }
6085
+
6086
+ async function dropFileTreeEntry(event, entry = {}) {
6087
+ const source = fileTreeDragSourceFromEvent(event);
6088
+ if (!source || !fileTreeEntryIsDirectory(entry)) return;
6089
+ const targetPath = normalizeFileTreePath(entry.path || "");
6090
+ if (!fileTreeCanDropOnDirectory(source.path, targetPath, source.entry)) return;
6091
+ event.preventDefault();
6092
+ event.stopPropagation();
6093
+ finishFileTreeDrag();
6094
+ await moveFileTreeEntryToDestination(source.entry || { path: source.path, type: source.type }, targetPath, { viaDragDrop: true });
6095
+ }
6096
+
6097
+ function bindFileTreeDragAndDrop(button, item, entry = {}) {
6098
+ if (!button || !item) return;
6099
+ const movable = fileTreeEntryIsMovable(entry);
6100
+ button.draggable = movable;
6101
+ button.classList.toggle("file-tree-draggable", movable);
6102
+ if (movable) {
6103
+ button.addEventListener("dragstart", (event) => beginFileTreeDrag(event, entry, item));
6104
+ button.addEventListener("dragend", finishFileTreeDrag);
6105
+ }
6106
+ if (fileTreeEntryIsDirectory(entry)) {
6107
+ for (const target of [button, item]) {
6108
+ target.addEventListener("dragenter", (event) => updateFileTreeDropTarget(event, entry, item));
6109
+ target.addEventListener("dragover", (event) => updateFileTreeDropTarget(event, entry, item));
6110
+ target.addEventListener("dragleave", (event) => clearFileTreeDropTarget(event, item));
6111
+ target.addEventListener("drop", (event) => dropFileTreeEntry(event, entry).catch((error) => addEvent(error.message || String(error), "error")));
6112
+ }
6113
+ }
6114
+ }
6115
+
6116
+ function handleFileTreeRootDragOver(event) {
6117
+ const delegatedTarget = fileTreeDropTargetFromEvent(event);
6118
+ if (delegatedTarget) {
6119
+ updateFileTreeDropTarget(event, delegatedTarget.entry, delegatedTarget.item);
6120
+ return;
6121
+ }
6122
+ const source = fileTreeDragSourceFromEvent(event);
6123
+ if (!source) return;
6124
+ const allowed = fileTreeCanDropOnDirectory(source.path, FILE_TREE_ROOT_PATH, source.entry);
6125
+ elements.fileTreeRoot?.classList.toggle("drop-blocked", !allowed);
6126
+ if (!allowed) {
6127
+ event.dataTransfer.dropEffect = "none";
6128
+ return;
6129
+ }
6130
+ event.preventDefault();
6131
+ event.dataTransfer.dropEffect = "move";
6132
+ elements.fileTreeRoot?.classList.add("drag-root-drop");
6133
+ }
6134
+
6135
+ function handleFileTreeRootDragLeave(event) {
6136
+ if (elements.fileTreeRoot?.contains?.(event.relatedTarget)) return;
6137
+ elements.fileTreeRoot?.classList.remove("drag-root-drop", "drop-blocked");
6138
+ }
6139
+
6140
+ async function handleFileTreeRootDrop(event) {
6141
+ const delegatedTarget = fileTreeDropTargetFromEvent(event);
6142
+ if (delegatedTarget) {
6143
+ await dropFileTreeEntry(event, delegatedTarget.entry);
6144
+ return;
6145
+ }
6146
+ const source = fileTreeDragSourceFromEvent(event);
6147
+ if (!source || !fileTreeCanDropOnDirectory(source.path, FILE_TREE_ROOT_PATH, source.entry)) return;
6148
+ event.preventDefault();
6149
+ finishFileTreeDrag();
6150
+ await moveFileTreeEntryToDestination(source.entry || { path: source.path, type: source.type }, FILE_TREE_ROOT_PATH, { viaDragDrop: true });
6151
+ }
6152
+
6153
+ function clearFileTreeEntryCache(filePath = "") {
6154
+ const normalized = normalizeFileTreePath(filePath);
6155
+ if (!normalized) {
6156
+ fileTreeState.entriesByPath.clear();
6157
+ fileTreeState.expanded.clear();
6158
+ fileTreeState.loading.clear();
6159
+ return;
6160
+ }
6161
+ for (const key of [...fileTreeState.entriesByPath.keys()]) {
6162
+ if (key === normalized || key.startsWith(`${normalized}/`)) fileTreeState.entriesByPath.delete(key);
6163
+ }
6164
+ for (const key of [...fileTreeState.expanded]) {
6165
+ if (key === normalized || key.startsWith(`${normalized}/`)) fileTreeState.expanded.delete(key);
6166
+ }
6167
+ for (const key of [...fileTreeState.loading]) {
6168
+ if (key === normalized || key.startsWith(`${normalized}/`)) fileTreeState.loading.delete(key);
6169
+ }
6170
+ }
6171
+
6172
+ async function refreshFileTreeAfterOperation(paths = []) {
6173
+ if (fileTreeSearchQueryText()) {
6174
+ await runFileTreeSearch();
6175
+ return;
6176
+ }
6177
+ const uniquePaths = [...new Set(paths.map((item) => normalizeFileTreePath(item)))];
6178
+ if (!uniquePaths.length) {
6179
+ renderFileTree();
6180
+ return;
6181
+ }
6182
+ for (const path of uniquePaths) await loadFileTreeDirectory(path, { force: true });
6183
+ renderFileTree();
6184
+ }
6185
+
6186
+ function updateActiveFileViewerAfterMove(sourcePath = "", destinationPath = "") {
6187
+ if (!activeFileViewer) return;
6188
+ const currentPath = normalizeFileTreePath(activeFileViewer.path || "");
6189
+ const nextPath = remapFileTreePathAfterMove(currentPath, sourcePath, destinationPath);
6190
+ if (!nextPath || nextPath === currentPath) return;
6191
+ const language = fileLanguageForPath(nextPath);
6192
+ activeFileViewer = {
6193
+ ...activeFileViewer,
6194
+ path: nextPath,
6195
+ name: fileDisplayName(nextPath),
6196
+ extension: fileExtensionForPath(nextPath),
6197
+ language,
6198
+ mode: activeFileViewer.mode === "preview" && language === "markdown" ? "preview" : "source",
6199
+ };
6200
+ if (fileViewerSelection) fileViewerSelection = { ...fileViewerSelection, path: nextPath, fileName: activeFileViewer.name };
6201
+ updateFileViewerUi();
6202
+ }
6203
+
6204
+ function closeActiveFileViewerIfDeleted(deletedPath = "") {
6205
+ if (!activeFileViewer || !filePathWithinOrEqual(activeFileViewer.path, deletedPath)) return false;
6206
+ closeFileViewer();
6207
+ return true;
6208
+ }
6209
+
6210
+ async function deleteFileTreeEntry(entry = fileContextMenuState?.entry) {
6211
+ if (!entry) return;
6212
+ const sourcePath = normalizeFileTreePath(entry.path || "");
6213
+ if (!sourcePath) {
6214
+ addEvent("Workspace root cannot be deleted from the Files panel.", "warn");
6215
+ return;
6216
+ }
6217
+ const typeLabel = fileOperationTypeLabel(entry);
6218
+ const dirtyWarning = activeFileViewer?.dirty && filePathWithinOrEqual(activeFileViewer.path, sourcePath)
6219
+ ? "\n\nThe currently open file has unsaved edits that will be discarded from the viewer."
6220
+ : "";
6221
+ const recursiveWarning = typeLabel === "directory" ? "\n\nThis permanently deletes the directory and all of its contents." : "";
6222
+ if (!window.confirm(`Delete ${typeLabel} ${sourcePath}?${recursiveWarning}${dirtyWarning}\n\nThis cannot be undone.`)) return;
6223
+ const tabContext = activeTabContext();
6224
+ setFileTreeStatus(`Deleting ${sourcePath}…`);
6225
+ try {
6226
+ const response = await api("/api/files", { method: "DELETE", body: { path: sourcePath, confirmed: true }, tabId: tabContext.tabId });
6227
+ if (!isCurrentTabContext(tabContext)) return;
6228
+ const data = response.data || {};
6229
+ closeActiveFileViewerIfDeleted(sourcePath);
6230
+ clearFileTreeEntryCache(sourcePath);
6231
+ fileTreeState.selectedPath = "";
6232
+ await refreshFileTreeAfterOperation([data.parentPath ?? fileParentPath(sourcePath)]);
6233
+ setFileTreeStatus(`Deleted ${data.path || sourcePath}.`, "success");
6234
+ addEvent(`deleted ${data.path || sourcePath}`, "warn");
6235
+ } catch (error) {
6236
+ if (isCurrentTabContext(tabContext)) {
6237
+ setFileTreeStatus(error.message || String(error), "error");
6238
+ addEvent(`file delete failed: ${error.message || String(error)}`, "error");
6239
+ }
6240
+ }
6241
+ }
6242
+
6243
+ async function moveFileTreeEntryToDestination(entry = {}, destinationPath = "", { viaDragDrop = false, confirmMove = false } = {}) {
6244
+ const sourcePath = normalizeFileTreePath(entry.path || "");
6245
+ const normalizedDestination = normalizeFileTreePath(destinationPath);
6246
+ if (!sourcePath) {
6247
+ addEvent("Workspace root cannot be moved from the Files panel.", "warn");
6248
+ return;
6249
+ }
6250
+ if (!normalizedDestination && normalizedDestination !== FILE_TREE_ROOT_PATH) {
6251
+ addEvent("Destination path is required.", "warn");
6252
+ return;
6253
+ }
6254
+ const typeLabel = fileOperationTypeLabel(entry);
6255
+ if (confirmMove && !window.confirm(`Move ${typeLabel}?\n\nFrom: ${sourcePath}\nTo: ${normalizedDestination || "."}\n\nExisting destination paths are refused.`)) return;
6256
+ const tabContext = activeTabContext();
6257
+ const isDirectory = fileTreeEntryIsDirectory(entry);
6258
+ const restoreSourceExpanded = isDirectory && fileTreeState.expanded.has(sourcePath) && !fileTreeSearchQueryText();
6259
+ const expandDestinationDirectory = viaDragDrop && !fileTreeSearchQueryText();
6260
+ setFileTreeStatus(`Moving ${sourcePath}…`);
6261
+ try {
6262
+ const response = await api("/api/files/move", { method: "POST", body: { path: sourcePath, toPath: normalizedDestination || ".", confirmed: true }, tabId: tabContext.tabId });
6263
+ if (!isCurrentTabContext(tabContext)) return;
6264
+ const data = response.data || {};
6265
+ const nextPath = normalizeFileTreePath(data.destination || normalizedDestination);
6266
+ const sourceParent = data.parentPath ?? fileParentPath(sourcePath);
6267
+ const destinationParent = data.destinationParentPath ?? fileParentPath(nextPath);
6268
+ clearFileTreeEntryCache(sourcePath);
6269
+ clearFileTreeEntryCache(nextPath);
6270
+ if (restoreSourceExpanded && nextPath) fileTreeState.expanded.add(nextPath);
6271
+ if (expandDestinationDirectory) fileTreeState.expanded.add(normalizedDestination);
6272
+ fileTreeState.selectedPath = nextPath;
6273
+ updateActiveFileViewerAfterMove(sourcePath, nextPath);
6274
+ await refreshFileTreeAfterOperation([sourceParent, destinationParent]);
6275
+ if (restoreSourceExpanded && nextPath) await loadFileTreeDirectory(nextPath, { force: true });
6276
+ if (expandDestinationDirectory) await loadFileTreeDirectory(normalizedDestination, { force: true });
6277
+ renderFileTree();
6278
+ setFileTreeStatus(`Moved ${sourcePath} to ${nextPath}.`, "success");
6279
+ addEvent(`${viaDragDrop ? "drag-moved" : "moved"} ${sourcePath} to ${nextPath}`, "info");
6280
+ } catch (error) {
6281
+ if (isCurrentTabContext(tabContext)) {
6282
+ setFileTreeStatus(error.message || String(error), "error");
6283
+ addEvent(`file move failed: ${error.message || String(error)}`, "error");
6284
+ }
6285
+ }
6286
+ }
6287
+
6288
+ async function moveFileTreeEntry(entry = fileContextMenuState?.entry) {
6289
+ if (!entry) return;
6290
+ const sourcePath = normalizeFileTreePath(entry.path || "");
6291
+ if (!sourcePath) {
6292
+ addEvent("Workspace root cannot be moved from the Files panel.", "warn");
6293
+ return;
6294
+ }
6295
+ const typeLabel = fileOperationTypeLabel(entry);
6296
+ const destinationInput = window.prompt([
6297
+ `Move/rename ${typeLabel} ${sourcePath}`,
6298
+ "",
6299
+ "Enter a destination path inside the current workspace.",
6300
+ `Existing directories receive the ${typeLabel} as a child.`,
6301
+ ].join("\n"), sourcePath);
6302
+ if (destinationInput === null) return;
6303
+ const destinationPath = String(destinationInput || "").trim();
6304
+ if (!destinationPath) {
6305
+ addEvent("Destination path is required.", "warn");
6306
+ return;
6307
+ }
6308
+ await moveFileTreeEntryToDestination(entry, destinationPath, { confirmMove: true });
6309
+ }
6310
+
5771
6311
  function readStoredFileViewerWidth() {
5772
6312
  try {
5773
6313
  const width = Number.parseFloat(localStorage.getItem(FILE_VIEWER_WIDTH_STORAGE_KEY) || "");
@@ -6482,7 +7022,7 @@ function restoreActiveDraft() {
6482
7022
 
6483
7023
  function focusPromptInput({ defer = false } = {}) {
6484
7024
  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;
7025
+ 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.statsOverlayDialog?.open || elements.promptListDialog?.open || elements.attachmentTextDialog?.open || elements.skillEditorDialog?.open || document.visibilityState === "hidden") return;
6486
7026
  try {
6487
7027
  elements.promptInput.focus({ preventScroll: true });
6488
7028
  } catch {
@@ -6647,6 +7187,7 @@ function resetActiveTabUi() {
6647
7187
  hideCommandSuggestions();
6648
7188
  cancelPendingDialogs();
6649
7189
  if (elements.nativeCommandDialog.open) closeNativeCommandDialog();
7190
+ if (elements.gitFooterVisibilityDialog?.open) closeGitFooterVisibilityDialog();
6650
7191
  if (pathPickerState) closePathPicker(null);
6651
7192
  bindGitWorkflowToActiveTab();
6652
7193
  resetChatOutput();
@@ -7866,7 +8407,7 @@ function applyOptimisticThinkingSelection(data, tabContext = activeTabContext())
7866
8407
 
7867
8408
  function footerThinkingLevels() {
7868
8409
  const levels = Array.from(elements.thinkingSelect?.options || []).map((option) => option.value).filter(Boolean);
7869
- return levels.length ? levels : ["off", "minimal", "low", "medium", "high", "xhigh"];
8410
+ return levels.length ? levels : ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
7870
8411
  }
7871
8412
 
7872
8413
  function formatFooterTokenCount(value) {
@@ -8329,6 +8870,297 @@ const GIT_FOOTER_TOOLTIP_COPY = {
8329
8870
  thinking: "Reasoning/thinking effort for this tab.",
8330
8871
  };
8331
8872
 
8873
+ const GIT_FOOTER_VISIBILITY_GROUPS = Object.freeze([
8874
+ {
8875
+ label: "Cards & chips",
8876
+ description: "Main footer cards and extra status chips rendered in the browser footer.",
8877
+ keys: ["tokens", "cache", "pi", "speed", "cost", "context", "cwd", "git", "git-state", "sync", "changes", "git-extra", "worktree", "model", "thinking", "context-meta"],
8878
+ },
8879
+ {
8880
+ label: "Git subitems",
8881
+ description: "Fine-grained pieces inside the Git branch, sync, changes, and git+ chips.",
8882
+ 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"],
8883
+ },
8884
+ {
8885
+ label: "WebUI actions & modals",
8886
+ description: "Buttons, pickers, popovers, and modal affordances attached to footer chips.",
8887
+ 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"],
8888
+ },
8889
+ {
8890
+ label: "Native parity keys",
8891
+ description: "Keys shared with the native footer command set; these are kept for parity even when they have little browser-visible effect.",
8892
+ keys: ["cwd-branch", "git-status", "extension-statuses"],
8893
+ },
8894
+ ]);
8895
+ const GIT_FOOTER_VISIBILITY_GROUPED_KEYS = new Set(GIT_FOOTER_VISIBILITY_GROUPS.flatMap((group) => group.keys));
8896
+ const GIT_FOOTER_VISIBILITY_DIALOG_KEYS = Object.freeze([
8897
+ ...GIT_FOOTER_VISIBILITY_GROUPS.flatMap((group) => group.keys),
8898
+ ...Object.keys(GIT_FOOTER_WEBUI_VISIBILITY_DEFAULTS).filter((key) => !GIT_FOOTER_VISIBILITY_GROUPED_KEYS.has(key)),
8899
+ ]);
8900
+ const GIT_FOOTER_VISIBILITY_LABELS = Object.freeze({
8901
+ tokens: "Tokens card",
8902
+ cache: "Cache card",
8903
+ pi: "PI estimate card",
8904
+ speed: "Speed card",
8905
+ cost: "Cost card",
8906
+ context: "Context card",
8907
+ cwd: "Working directory chip",
8908
+ git: "Git branch chip",
8909
+ "git-state": "Git state chip",
8910
+ sync: "Sync chip",
8911
+ changes: "Changes chip",
8912
+ "git-extra": "Git+ chip",
8913
+ worktree: "Worktree chip",
8914
+ model: "Model chip",
8915
+ thinking: "Thinking chip",
8916
+ "context-meta": "Context meta chip",
8917
+ "git-branch-indicator": "Branch indicator",
8918
+ "git-detached": "Detached marker",
8919
+ "git-operation": "Operation marker",
8920
+ "git-ahead": "Ahead count",
8921
+ "git-behind": "Behind count",
8922
+ "git-upstream": "Upstream name",
8923
+ "git-staged": "Staged count",
8924
+ "git-unstaged": "Unstaged count",
8925
+ "git-untracked": "Untracked count",
8926
+ "git-conflicted": "Conflicted count",
8927
+ "git-clean": "Clean marker",
8928
+ "git-stash": "Stash count",
8929
+ "git-submodules": "Submodule state",
8930
+ "git-worktrees": "Worktree count",
8931
+ "git-tag": "HEAD tag",
8932
+ "git-last-commit-age": "Last commit age",
8933
+ "git-signing-mismatch": "Signing mismatch",
8934
+ "webui-fetch-state": "Fetch state",
8935
+ "webui-refresh-button": "Refresh button",
8936
+ "webui-details-button": "Details button",
8937
+ "webui-cwd-picker": "CWD picker",
8938
+ "webui-pi-calibration": "PI calibration action",
8939
+ "webui-context-auto-compaction": "Auto-compaction action",
8940
+ "webui-branch-picker": "Branch/worktree picker",
8941
+ "webui-git-init": "Git init affordance",
8942
+ "webui-sync-push": "Sync push action",
8943
+ "webui-changes-modal": "Changes modal",
8944
+ "webui-git-tools-modal": "Git tools modal",
8945
+ "webui-model-picker": "Model picker",
8946
+ "webui-thinking-picker": "Thinking picker",
8947
+ "webui-changed-files-popover": "Changed-files popover",
8948
+ "cwd-branch": "CWD branch suffix",
8949
+ "git-status": "Native git status line",
8950
+ "extension-statuses": "Extension status line",
8951
+ });
8952
+ const GIT_FOOTER_VISIBILITY_HINTS = Object.freeze({
8953
+ "context-meta": "Secondary context chip shown in the footer details row.",
8954
+ "git-branch-indicator": "Optional branch glyph/name inside the generated git state section; off by default in WebUI.",
8955
+ "git-detached": "Detached-HEAD warning inside the git state chip.",
8956
+ "git-operation": "Merge/rebase/cherry-pick/revert/bisect operation text inside the git state chip.",
8957
+ "git-ahead": "Outgoing commit count inside the sync chip.",
8958
+ "git-behind": "Incoming commit count inside the sync/changes chips.",
8959
+ "git-upstream": "Tracked upstream branch name inside the sync chip.",
8960
+ "git-staged": "Staged-file count inside the changes chip.",
8961
+ "git-unstaged": "Modified-but-unstaged count inside the changes chip.",
8962
+ "git-untracked": "Untracked-file count inside the changes chip.",
8963
+ "git-conflicted": "Conflict count inside the changes chip.",
8964
+ "git-clean": "Clean working-tree checkmark inside the changes chip.",
8965
+ "git-stash": "Stash count inside the git+ chip.",
8966
+ "git-submodules": "Dirty submodule count inside the git+ chip.",
8967
+ "git-worktrees": "Repository worktree count inside the git+ chip.",
8968
+ "git-tag": "Tag at HEAD inside the git+ chip.",
8969
+ "git-last-commit-age": "Last-commit age inside the git+ chip.",
8970
+ "git-signing-mismatch": "Signing-key mismatch marker inside the git+ chip.",
8971
+ "webui-fetch-state": "Fetch progress/success/error marker in the changes chip.",
8972
+ "webui-refresh-button": "Floating footer refresh button.",
8973
+ "webui-details-button": "Mobile/details-row expander button.",
8974
+ "webui-cwd-picker": "Click action on the working-directory chip.",
8975
+ "webui-pi-calibration": "Click action on the PI card for calibration/probe commands.",
8976
+ "webui-context-auto-compaction": "Click action on context chips for auto-compaction.",
8977
+ "webui-branch-picker": "Click action on the git branch/worktree chips.",
8978
+ "webui-git-init": "Git initialization affordance when a tab has no repository.",
8979
+ "webui-sync-push": "Click-to-push action on outgoing sync chips.",
8980
+ "webui-changes-modal": "Click action opening the changes/conflicts modal.",
8981
+ "webui-git-tools-modal": "Click action opening extra git tools.",
8982
+ "webui-model-picker": "Click action opening the footer model picker.",
8983
+ "webui-thinking-picker": "Click action opening the thinking-effort picker.",
8984
+ "webui-changed-files-popover": "Hover/focus popover listing changed files from the changes chip.",
8985
+ "cwd-branch": "Native footer branch suffix for the cwd text; included here for command parity.",
8986
+ "git-status": "Native footer git status status-entry gate; included here for command parity.",
8987
+ "extension-statuses": "Native footer extension-status gate; included here for command parity.",
8988
+ });
8989
+
8990
+ function gitFooterVisibilityLabel(key) {
8991
+ return GIT_FOOTER_VISIBILITY_LABELS[key] || String(key).split("-").map((part) => part ? `${part[0].toUpperCase()}${part.slice(1)}` : part).join(" ");
8992
+ }
8993
+
8994
+ function gitFooterVisibilityHint(key) {
8995
+ return GIT_FOOTER_VISIBILITY_HINTS[key] || GIT_FOOTER_TOOLTIP_COPY[key] || `Controls the ${key} footer visibility key for the Web UI.`;
8996
+ }
8997
+
8998
+ function gitFooterVisibilityCommandName() {
8999
+ return resolveAvailableCommandName("git-footer-visibility", { rpcOnly: true });
9000
+ }
9001
+
9002
+ function gitFooterVisibilityCommandAvailable() {
9003
+ return !!gitFooterVisibilityCommandName();
9004
+ }
9005
+
9006
+ function currentGitFooterVisibilityState() {
9007
+ return normalizeGitFooterWebuiVisibility(parseGitFooterWebuiPayload()?.visibility);
9008
+ }
9009
+
9010
+ function setGitFooterVisibilityStatus(message = "", level = "muted") {
9011
+ if (!elements.gitFooterVisibilityStatus) return;
9012
+ elements.gitFooterVisibilityStatus.textContent = message;
9013
+ elements.gitFooterVisibilityStatus.className = `git-footer-visibility-status ${level || "muted"}`;
9014
+ elements.gitFooterVisibilityStatus.hidden = !message;
9015
+ }
9016
+
9017
+ function setGitFooterVisibilityBusy(busy) {
9018
+ gitFooterVisibilityApplyInFlight = !!busy;
9019
+ const commandAvailable = gitFooterVisibilityCommandAvailable();
9020
+ for (const button of [elements.gitFooterVisibilityApplyButton, elements.gitFooterVisibilityResetButton]) {
9021
+ if (button) button.disabled = gitFooterVisibilityApplyInFlight || !commandAvailable;
9022
+ }
9023
+ const inputs = elements.gitFooterVisibilityBody?.querySelectorAll("input[data-git-footer-visibility-key]") || [];
9024
+ for (const input of inputs) input.disabled = gitFooterVisibilityApplyInFlight || !commandAvailable;
9025
+ for (const button of [elements.gitFooterVisibilitySelectAllButton, elements.gitFooterVisibilitySelectNoneButton]) {
9026
+ if (button) button.disabled = gitFooterVisibilityApplyInFlight || !commandAvailable;
9027
+ }
9028
+ if (elements.gitFooterVisibilityCloseButton) elements.gitFooterVisibilityCloseButton.disabled = gitFooterVisibilityApplyInFlight;
9029
+ }
9030
+
9031
+ function renderGitFooterVisibilityToggle(key, visibility) {
9032
+ const label = make("label", "toggle-control git-footer-visibility-toggle");
9033
+ const input = make("input");
9034
+ input.type = "checkbox";
9035
+ input.checked = visibility[key] ?? true;
9036
+ input.dataset.gitFooterVisibilityKey = key;
9037
+ input.addEventListener("change", () => {
9038
+ gitFooterVisibilityDirty = true;
9039
+ setGitFooterVisibilityStatus("Unsaved WebUI footer visibility changes.", "warn");
9040
+ });
9041
+ const text = make("span", "git-footer-visibility-toggle-text");
9042
+ text.append(
9043
+ make("span", "toggle-control-label", gitFooterVisibilityLabel(key)),
9044
+ make("span", "toggle-control-hint", gitFooterVisibilityHint(key)),
9045
+ make("code", "git-footer-visibility-key", key),
9046
+ );
9047
+ label.append(input, text);
9048
+ return label;
9049
+ }
9050
+
9051
+ function renderGitFooterVisibilityDialog() {
9052
+ if (!elements.gitFooterVisibilityBody) return;
9053
+ const visibility = currentGitFooterVisibilityState();
9054
+ elements.gitFooterVisibilityBody.replaceChildren();
9055
+ for (const group of GIT_FOOTER_VISIBILITY_GROUPS) {
9056
+ const section = make("section", "git-footer-visibility-group");
9057
+ const header = make("div", "git-footer-visibility-group-header");
9058
+ header.append(make("h3", "", group.label), make("p", "muted", group.description));
9059
+ const grid = make("div", "git-footer-visibility-grid");
9060
+ for (const key of group.keys) grid.append(renderGitFooterVisibilityToggle(key, visibility));
9061
+ section.append(header, grid);
9062
+ elements.gitFooterVisibilityBody.append(section);
9063
+ }
9064
+ setGitFooterVisibilityBusy(gitFooterVisibilityApplyInFlight);
9065
+ if (!gitFooterVisibilityDirty) {
9066
+ setGitFooterVisibilityStatus(
9067
+ gitFooterVisibilityCommandAvailable()
9068
+ ? "Runtime changes last until Pi/package restart. Use PI_GIT_FOOTER_WEBUI_HIDE or per-key env vars for persistence."
9069
+ : commandUnavailableMessage("git-footer-visibility"),
9070
+ gitFooterVisibilityCommandAvailable() ? "muted" : "warn",
9071
+ );
9072
+ }
9073
+ }
9074
+
9075
+ function readGitFooterVisibilitySelection() {
9076
+ const next = currentGitFooterVisibilityState();
9077
+ const inputs = elements.gitFooterVisibilityBody?.querySelectorAll("input[data-git-footer-visibility-key]") || [];
9078
+ for (const input of inputs) {
9079
+ const key = input.dataset.gitFooterVisibilityKey;
9080
+ if (key && key in next) next[key] = input.checked;
9081
+ }
9082
+ return next;
9083
+ }
9084
+
9085
+ async function runGitFooterVisibilityCommand(action, keys = []) {
9086
+ const commandName = gitFooterVisibilityCommandName();
9087
+ if (!commandName) throw new Error(commandUnavailableMessage("git-footer-visibility"));
9088
+ const suffix = keys.length > 0 ? ` ${keys.join(" ")}` : "";
9089
+ await sendPrompt("prompt", `/${commandName} ${action} webui${suffix}`, { targetTabId: activeTabId, throwOnError: true });
9090
+ }
9091
+
9092
+ async function applyGitFooterVisibilityDialog() {
9093
+ if (gitFooterVisibilityApplyInFlight) return;
9094
+ const current = currentGitFooterVisibilityState();
9095
+ const next = readGitFooterVisibilitySelection();
9096
+ const show = [];
9097
+ const hide = [];
9098
+ for (const key of GIT_FOOTER_VISIBILITY_DIALOG_KEYS) {
9099
+ if (next[key] === current[key]) continue;
9100
+ if (next[key]) show.push(key);
9101
+ else hide.push(key);
9102
+ }
9103
+ if (show.length === 0 && hide.length === 0) {
9104
+ gitFooterVisibilityDirty = false;
9105
+ setGitFooterVisibilityStatus("No footer visibility changes to apply.", "muted");
9106
+ return;
9107
+ }
9108
+
9109
+ setGitFooterVisibilityBusy(true);
9110
+ setGitFooterVisibilityStatus("Applying WebUI footer visibility…", "muted");
9111
+ try {
9112
+ if (hide.length) await runGitFooterVisibilityCommand("hide", hide);
9113
+ if (show.length) await runGitFooterVisibilityCommand("show", show);
9114
+ gitFooterVisibilityDirty = false;
9115
+ setGitFooterVisibilityStatus(`Applied ${hide.length + show.length} WebUI footer visibility change${hide.length + show.length === 1 ? "" : "s"}.`, "success");
9116
+ requestGitFooterWebuiPayload(activeTabContext(), { force: true, allowDuringRun: true });
9117
+ renderFooter();
9118
+ } catch (error) {
9119
+ setGitFooterVisibilityStatus(error.message || String(error), "error");
9120
+ } finally {
9121
+ setGitFooterVisibilityBusy(false);
9122
+ }
9123
+ }
9124
+
9125
+ async function resetGitFooterVisibilityDialog() {
9126
+ if (gitFooterVisibilityApplyInFlight) return;
9127
+ setGitFooterVisibilityBusy(true);
9128
+ setGitFooterVisibilityStatus("Resetting WebUI footer visibility…", "muted");
9129
+ try {
9130
+ await runGitFooterVisibilityCommand("reset");
9131
+ gitFooterVisibilityDirty = false;
9132
+ setGitFooterVisibilityStatus("Reset WebUI footer visibility overrides.", "success");
9133
+ requestGitFooterWebuiPayload(activeTabContext(), { force: true, allowDuringRun: true });
9134
+ } catch (error) {
9135
+ setGitFooterVisibilityStatus(error.message || String(error), "error");
9136
+ } finally {
9137
+ setGitFooterVisibilityBusy(false);
9138
+ }
9139
+ }
9140
+
9141
+ function setGitFooterVisibilitySelection(checked) {
9142
+ const inputs = elements.gitFooterVisibilityBody?.querySelectorAll("input[data-git-footer-visibility-key]") || [];
9143
+ for (const input of inputs) input.checked = !!checked;
9144
+ gitFooterVisibilityDirty = true;
9145
+ setGitFooterVisibilityStatus(checked ? "Selected all WebUI footer options." : "Deselected all WebUI footer options.", "warn");
9146
+ }
9147
+
9148
+ function openGitFooterVisibilityDialog() {
9149
+ if (!elements.gitFooterVisibilityDialog) return;
9150
+ setOptionsMenuOpen(false);
9151
+ hideFooterTooltip();
9152
+ gitFooterVisibilityDirty = false;
9153
+ renderGitFooterVisibilityDialog();
9154
+ if (!elements.gitFooterVisibilityDialog.open) elements.gitFooterVisibilityDialog.showModal();
9155
+ queueMicrotask(() => elements.gitFooterVisibilityBody?.querySelector("input")?.focus());
9156
+ }
9157
+
9158
+ function closeGitFooterVisibilityDialog() {
9159
+ gitFooterVisibilityDirty = false;
9160
+ gitFooterVisibilityApplyInFlight = false;
9161
+ if (elements.gitFooterVisibilityDialog?.open) elements.gitFooterVisibilityDialog.close();
9162
+ }
9163
+
8332
9164
  function cleanFooterPayloadText(value, fallback = "", maxLength = 240) {
8333
9165
  const text = cleanStatusText(value).slice(0, maxLength);
8334
9166
  return text || fallback;
@@ -8349,6 +9181,30 @@ function normalizeFooterPayloadChangedFile(value) {
8349
9181
  return file;
8350
9182
  }
8351
9183
 
9184
+ function normalizeGitFooterWebuiVisibility(value) {
9185
+ const visibility = { ...GIT_FOOTER_WEBUI_VISIBILITY_DEFAULTS };
9186
+ if (!value || typeof value !== "object") return visibility;
9187
+ for (const key of Object.keys(visibility)) {
9188
+ if (typeof value[key] === "boolean") visibility[key] = value[key];
9189
+ }
9190
+ return visibility;
9191
+ }
9192
+
9193
+ function gitFooterPayloadVisible(payload, key) {
9194
+ if (!key) return true;
9195
+ if (typeof payload?.visibility?.[key] === "boolean") return payload.visibility[key];
9196
+ return GIT_FOOTER_WEBUI_VISIBILITY_DEFAULTS[key] ?? true;
9197
+ }
9198
+
9199
+ function currentGitFooterPayloadVisible(key) {
9200
+ return gitFooterPayloadVisible(parseGitFooterWebuiPayload(), key);
9201
+ }
9202
+
9203
+ function gitFooterPayloadVisibilityKey(payload) {
9204
+ const visibility = normalizeGitFooterWebuiVisibility(payload?.visibility);
9205
+ return Object.keys(visibility).sort().map((key) => `${key}:${visibility[key] ? 1 : 0}`).join("|");
9206
+ }
9207
+
8352
9208
  function normalizeFooterPayloadChip(value, index) {
8353
9209
  if (!value || typeof value !== "object") return null;
8354
9210
  const key = cleanFooterPayloadText(value.key, `item-${index}`).replace(/[^a-z0-9_.:-]/gi, "-").slice(0, 64) || `item-${index}`;
@@ -8364,7 +9220,14 @@ function normalizeFooterPayloadChip(value, index) {
8364
9220
  if (FOOTER_PAYLOAD_ACTIONS.has(value.action)) chip.action = value.action;
8365
9221
  if (Array.isArray(value.files)) {
8366
9222
  const files = value.files.map(normalizeFooterPayloadChangedFile).filter(Boolean).slice(0, 80);
8367
- if (files.length) chip.files = files;
9223
+ if (files.length) {
9224
+ chip.files = files;
9225
+ const filesTotal = Number(value.filesTotal);
9226
+ if (value.filesTruncated === true && Number.isFinite(filesTotal) && filesTotal > files.length) {
9227
+ chip.filesTotal = filesTotal;
9228
+ chip.filesTruncated = true;
9229
+ }
9230
+ }
8368
9231
  }
8369
9232
  if (value.contextUsage && typeof value.contextUsage === "object") {
8370
9233
  const percent = typeof value.contextUsage.percent === "number" ? value.contextUsage.percent : Number.NaN;
@@ -8389,8 +9252,9 @@ function parseGitFooterWebuiPayloadRaw(raw) {
8389
9252
  if (!parsed || parsed.type !== GIT_FOOTER_WEBUI_PAYLOAD_TYPE || parsed.version !== GIT_FOOTER_WEBUI_PAYLOAD_VERSION) return null;
8390
9253
  const main = Array.isArray(parsed.main) ? parsed.main.map(normalizeFooterPayloadChip).filter(Boolean).slice(0, 8) : [];
8391
9254
  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 };
9255
+ const visibility = normalizeGitFooterWebuiVisibility(parsed.visibility);
9256
+ if (!main.length && !meta.length && !parsed.visibility) return null;
9257
+ return { main, meta, visibility };
8394
9258
  } catch {
8395
9259
  return null;
8396
9260
  }
@@ -8493,14 +9357,23 @@ function parseGitFooterWebuiPayload() {
8493
9357
  return parseGitFooterWebuiPayloadRaw(readCachedGitFooterWebuiPayloadRaw());
8494
9358
  }
8495
9359
 
9360
+ function footerPayloadChipVisible(payload, chip, area = "main") {
9361
+ if (!chip?.key) return true;
9362
+ if (area === "meta" && chip.key === "context") return gitFooterPayloadVisible(payload, "context-meta");
9363
+ return gitFooterPayloadVisible(payload, chip.key);
9364
+ }
9365
+
8496
9366
  function footerPayloadWithLiveModel(payload) {
8497
9367
  if (!payload) return payload;
9368
+ const visible = (key) => gitFooterPayloadVisible(payload, key);
9369
+ const mainSource = payload.main.filter((chip) => footerPayloadChipVisible(payload, chip, "main"));
9370
+ const metaSource = payload.meta.filter((chip) => footerPayloadChipVisible(payload, chip, "meta"));
8498
9371
  const model = currentState?.model ? shortModelLabel(currentState.model) : "";
8499
9372
  const effort = footerThinkingDisplay();
8500
9373
  const workspace = normalizeGitWorkspaceInfo(activeTab()?.gitWorkspace);
8501
9374
  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");
9375
+ const hasThinkingChip = [...mainSource, ...metaSource].some((chip) => chip?.key === "thinking");
9376
+ const hasWorktreeChip = [...mainSource, ...metaSource].some((chip) => chip?.key === "worktree");
8504
9377
  const contextChip = (chip) => {
8505
9378
  const usageUnknown = contextUsageUnknownAfterCompaction();
8506
9379
  const value = usageUnknown ? footerContextDisplayWithAuto(unknownFooterContextText(chip?.contextUsage)) : footerContextDisplayWithAuto(chip?.value);
@@ -8511,16 +9384,17 @@ function footerPayloadWithLiveModel(payload) {
8511
9384
  const worktreeChip = () => ({ key: "worktree", label: "worktree", value: worktreeLabel, icon: "🌳", tone: workspace?.isMainWorktree ? "teal" : "green", title: workspace?.worktreePath || "Git worktree" });
8512
9385
  const splitChip = (chip) => {
8513
9386
  if (chip?.key === "context") return [contextChip(chip)];
8514
- if (chip?.key === "thinking") return [effortChip(chip)];
9387
+ if (chip?.key === "thinking") return visible("thinking") ? [effortChip(chip)] : [];
8515
9388
  if (chip?.key !== "model" || !model) return [chip];
8516
9389
  const modelChip = { ...chip, value: model, title: `model: ${model}` };
8517
- return hasThinkingChip ? [modelChip] : [modelChip, effortChip(chip)];
9390
+ return hasThinkingChip || !visible("thinking") ? [modelChip] : [modelChip, effortChip(chip)];
8518
9391
  };
8519
- const meta = payload.meta.flatMap(splitChip);
8520
- if (worktreeLabel && !hasWorktreeChip) meta.splice(Math.min(meta.length, 2), 0, worktreeChip());
9392
+ const meta = metaSource.flatMap(splitChip);
9393
+ if (visible("worktree") && worktreeLabel && !hasWorktreeChip) meta.splice(Math.min(meta.length, 2), 0, worktreeChip());
8521
9394
  return {
8522
- main: payload.main.flatMap(splitChip),
9395
+ main: mainSource.flatMap(splitChip),
8523
9396
  meta,
9397
+ visibility: payload.visibility,
8524
9398
  };
8525
9399
  }
8526
9400
 
@@ -8637,26 +9511,29 @@ function renderChangedFilesGroup(kind, files) {
8637
9511
  return group;
8638
9512
  }
8639
9513
 
8640
- function applyFooterChangedFilesDropdown(node, chip) {
8641
- if (chip?.key !== "changes" || !Array.isArray(chip.files) || chip.files.length === 0) return node;
9514
+ function applyFooterChangedFilesDropdown(node, chip, payload) {
9515
+ if (!gitFooterPayloadVisible(payload, "webui-changed-files-popover") || chip?.key !== "changes" || !Array.isArray(chip.files) || chip.files.length === 0) return node;
8642
9516
  node.classList.add("footer-changes-with-files");
8643
9517
  node.tabIndex = 0;
8644
9518
  node.removeAttribute("data-tooltip");
8645
9519
  node.setAttribute("aria-label", `changes: ${chip.value}. Hover or focus to choose changed files. Click a file to add it as an @ reference.`);
8646
9520
 
8647
9521
  const popover = make("span", "footer-changed-files-popover");
8648
- popover.append(make("span", "footer-changed-files-title", "Changed files"));
9522
+ popover.append(make("span", "footer-changed-files-title", chip.filesTruncated ? `Changed files (showing ${chip.files.length} of ${chip.filesTotal})` : "Changed files"));
8649
9523
  for (const kind of FOOTER_CHANGED_FILE_KIND_ORDER) {
8650
9524
  const group = renderChangedFilesGroup(kind, chip.files.filter((file) => file.kind === kind));
8651
9525
  if (group) popover.append(group);
8652
9526
  }
9527
+ 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
9528
  node.append(popover);
8654
9529
  return node;
8655
9530
  }
8656
9531
 
8657
- function renderGitFooterPayloadMetric(chip) {
9532
+ function renderGitFooterPayloadMetric(chip, payload) {
8658
9533
  const options = { tooltipAlign: gitFooterTooltipAlign(chip) };
8659
- const action = applyGitFooterPiCalibrationOptions(chip, options) || applyGitFooterContextToggleOptions(chip, options);
9534
+ const piAction = gitFooterPayloadVisible(payload, "webui-pi-calibration") ? applyGitFooterPiCalibrationOptions(chip, options) : "";
9535
+ const contextAction = gitFooterPayloadVisible(payload, "webui-context-auto-compaction") ? applyGitFooterContextToggleOptions(chip, options) : "";
9536
+ const action = piAction || contextAction;
8660
9537
  options.title = gitFooterPayloadTooltip(chip, { action });
8661
9538
  const node = footerMetric(chip.icon || "•", chip.label, chip.value, chip.tone ? `tone-${chip.tone}` : "", options);
8662
9539
  return chip.contextUsage ? applyFooterContextUsage(node, chip.contextUsage) : node;
@@ -8671,6 +9548,12 @@ function gitFooterSyncChipHasOutgoing(chip) {
8671
9548
  return chip?.key === "sync" && gitFooterSyncOutgoingCount(chip.value) > 0;
8672
9549
  }
8673
9550
 
9551
+ function gitFooterCurrentBranch() {
9552
+ const gitChip = parseGitFooterWebuiPayload()?.meta?.find((chip) => chip.key === "git");
9553
+ const value = cleanFooterPayloadText(gitChip?.value, "").toLowerCase();
9554
+ return value && value !== "no repo" ? cleanFooterPayloadText(gitChip.value, "") : "";
9555
+ }
9556
+
8674
9557
  async function pushGitFooterSync(tabId = activeTabId, syncValue = "") {
8675
9558
  if (!tabId || gitFooterSyncPushInFlightByTab.has(tabId)) return;
8676
9559
  const outgoing = gitFooterSyncOutgoingCount(syncValue);
@@ -8679,14 +9562,47 @@ async function pushGitFooterSync(tabId = activeTabId, syncValue = "") {
8679
9562
  const tab = tabs.find((item) => item.id === tabId);
8680
9563
  const target = tab?.title || tab?.cwd || "this tab";
8681
9564
  hideFooterTooltip();
8682
- if (!window.confirm(`Run git push for ${outgoing} outgoing commit${outgoing === 1 ? "" : "s"} in ${target}?`)) return;
9565
+ const branch = gitFooterCurrentBranch();
9566
+ const protectedWarning = ["main", "master"].includes(branch)
9567
+ ? `\n\nWarning: ${branch} is usually a protected/shared branch. Consider pushing a feature branch and opening a PR instead.`
9568
+ : "";
9569
+ if (!window.confirm(`Run git push for ${outgoing} outgoing commit${outgoing === 1 ? "" : "s"} in ${target}?${protectedWarning}`)) return;
8683
9570
 
8684
9571
  gitFooterSyncPushInFlightByTab.add(tabId);
8685
9572
  if (isCurrentTabContext(tabContext)) renderFooter();
8686
9573
  try {
8687
9574
  const response = await api("/api/git-workflow/push", { method: "POST", body: {}, tabId });
8688
9575
  if (!response.ok) {
8689
- const detail = [response.error, formatGitCommandResult(response.data)].filter(Boolean).join("\n\n").trim();
9576
+ if (response.code === "NO_UPSTREAM") {
9577
+ 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?`);
9578
+ if (publish) {
9579
+ const upstreamResponse = await api("/api/git-workflow/push", { method: "POST", body: { setUpstream: true }, tabId });
9580
+ if (!upstreamResponse.ok) throw new Error([upstreamResponse.error, upstreamResponse.hint].filter(Boolean).join("\n"));
9581
+ addEvent(`Published ${upstreamResponse.data?.branch || "branch"} to ${upstreamResponse.data?.remote || "the remote"} and set its upstream.`, "success");
9582
+ requestGitFooterWebuiPayload(tabContext, { force: true });
9583
+ return;
9584
+ }
9585
+ throw new Error([response.error, response.hint].filter(Boolean).join("\n"));
9586
+ }
9587
+ if (response.code === "NON_FAST_FORWARD") {
9588
+ const forcePush = window.confirm([
9589
+ response.error,
9590
+ "",
9591
+ response.hint || "",
9592
+ "",
9593
+ "Recommended: open the Git Changes dialog, fetch, and review the incoming diff first.",
9594
+ `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).`,
9595
+ ].join("\n"));
9596
+ if (forcePush) {
9597
+ const forceResponse = await api("/api/git-workflow/push", { method: "POST", body: { forceWithLease: true, confirmed: true }, tabId });
9598
+ if (!forceResponse.ok) throw new Error([forceResponse.error, forceResponse.hint].filter(Boolean).join("\n"));
9599
+ addEvent("Force-pushed with --force-with-lease.", "success");
9600
+ requestGitFooterWebuiPayload(tabContext, { force: true });
9601
+ return;
9602
+ }
9603
+ throw new Error([response.error, response.hint].filter(Boolean).join("\n"));
9604
+ }
9605
+ const detail = [response.error, response.hint, formatGitCommandResult(response.data)].filter(Boolean).join("\n\n").trim();
8690
9606
  throw new Error(detail || "git push failed");
8691
9607
  }
8692
9608
  addEvent(`Pushed ${outgoing} outgoing commit${outgoing === 1 ? "" : "s"}.`, "success");
@@ -8699,43 +9615,51 @@ async function pushGitFooterSync(tabId = activeTabId, syncValue = "") {
8699
9615
  }
8700
9616
  }
8701
9617
 
8702
- function renderGitFooterPayloadMeta(chip, tab) {
9618
+ function renderGitFooterPayloadMeta(chip, tab, payload) {
8703
9619
  const options = {};
9620
+ const visible = (key) => gitFooterPayloadVisible(payload, key);
8704
9621
  let action = "";
8705
- if (chip.key === "cwd" && tab) {
9622
+ if (chip.key === "cwd" && tab && visible("webui-cwd-picker")) {
8706
9623
  options.onClick = changeActiveTabCwd;
8707
9624
  action = `Click to change the working directory for ${tab.title}.`;
8708
- } else if (chip.key === "git" && cleanFooterPayloadText(chip.value, "").toLowerCase() === "no repo") {
9625
+ } else if (chip.key === "git" && cleanFooterPayloadText(chip.value, "").toLowerCase() === "no repo" && visible("webui-git-init")) {
8709
9626
  options.onClick = () => startGitInitWorkflow();
8710
9627
  action = "No Git repository detected. Click to initialize a repo, create README.md, add origin, and push main.";
8711
- } else if (chip.key === "git") {
9628
+ } else if (chip.key === "git" && visible("webui-branch-picker")) {
8712
9629
  options.onClick = () => setFooterBranchPickerOpen(!footerBranchPickerOpen);
8713
9630
  action = "Click to open, create, or switch branches. Worktree actions are the safe default for parallel work.";
8714
- } else if (chip.key === "worktree") {
9631
+ } else if (chip.key === "worktree" && visible("webui-branch-picker")) {
8715
9632
  options.onClick = () => setFooterBranchPickerOpen(!footerBranchPickerOpen);
8716
9633
  action = "Click to manage branch worktrees for this repository.";
8717
- } else if (chip.key === "sync" && gitFooterSyncChipHasOutgoing(chip)) {
9634
+ } else if (chip.key === "sync" && visible("webui-sync-push") && gitFooterSyncChipHasOutgoing(chip)) {
8718
9635
  const tabId = tab?.id || activeTabId;
8719
9636
  const inFlight = tabId ? gitFooterSyncPushInFlightByTab.has(tabId) : false;
8720
9637
  options.onClick = () => pushGitFooterSync(tabId, chip.value);
8721
9638
  options.ariaBusy = inFlight;
8722
9639
  options.disabled = inFlight;
8723
9640
  action = inFlight ? "Pushing local commits to the configured remote." : "Click to push local commits to the configured remote.";
8724
- } else if (chip.key === "changes") {
9641
+ } else if (chip.key === "changes" && visible("webui-changes-modal")) {
8725
9642
  options.onClick = openGitChangesDialog;
8726
9643
  action = "Click to view the current git diff.";
8727
- } else if (chip.key === "model") {
9644
+ } else if (chip.key === "git-state" && visible("webui-changes-modal")) {
9645
+ options.onClick = openGitChangesDialog;
9646
+ action = "Click to open the conflicts and operation panel with continue/abort actions.";
9647
+ } else if (chip.key === "git-extra" && visible("webui-git-tools-modal")) {
9648
+ const toolsSection = gitToolsSectionForExtraChip(chip.value);
9649
+ options.onClick = () => openGitToolsFromFooter(toolsSection);
9650
+ action = `Click to open git tools (${toolsSection} first): stash, worktrees, undo, submodules, tags, signing.`;
9651
+ } else if (chip.key === "model" && visible("webui-model-picker")) {
8728
9652
  options.onClick = () => setFooterModelPickerOpen(!footerModelPickerOpen);
8729
9653
  action = "Click to choose another model.";
8730
- } else if (chip.key === "thinking") {
9654
+ } else if (chip.key === "thinking" && visible("webui-thinking-picker")) {
8731
9655
  options.onClick = () => setFooterThinkingPickerOpen(!footerThinkingPickerOpen);
8732
9656
  action = "Click to change thinking effort.";
8733
9657
  }
8734
- action = applyGitFooterContextToggleOptions(chip, options) || action;
9658
+ action = (visible("webui-context-auto-compaction") ? applyGitFooterContextToggleOptions(chip, options) : "") || action;
8735
9659
  options.title = gitFooterPayloadTooltip(chip, { action });
8736
9660
  options.tooltipAlign = gitFooterTooltipAlign(chip);
8737
9661
  const node = footerMeta(chip.label, chip.value, footerMetaClassForPayload(chip), options);
8738
- applyFooterChangedFilesDropdown(node, chip);
9662
+ applyFooterChangedFilesDropdown(node, chip, payload);
8739
9663
  if (["git", "worktree"].includes(chip.key) && options.onClick && cleanFooterPayloadText(chip.value, "").toLowerCase() !== "no repo") {
8740
9664
  node.setAttribute("aria-haspopup", "listbox");
8741
9665
  node.setAttribute("aria-expanded", footerBranchPickerOpen ? "true" : "false");
@@ -8759,12 +9683,12 @@ function gitFooterChipShapeKey(chip) {
8759
9683
  return JSON.stringify(shape);
8760
9684
  }
8761
9685
 
8762
- function gitFooterPickerStateKey() {
9686
+ function gitFooterPickerStateKey(payload) {
8763
9687
  const tabContext = activeTabContext();
8764
9688
  const refreshInFlight = tabContext.tabId ? gitFooterPayloadRefreshInFlightByTab.has(tabContext.tabId) : false;
8765
9689
  const syncPushInFlight = tabContext.tabId ? gitFooterSyncPushInFlightByTab.has(tabContext.tabId) : false;
8766
9690
  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}`;
9691
+ 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
9692
  }
8769
9693
 
8770
9694
  function updateGitFooterChipNodeValue(node, chip, valueSelector) {
@@ -8816,7 +9740,11 @@ function renderGitFooterRefreshButton() {
8816
9740
 
8817
9741
  function renderGitFooterPayload(payload) {
8818
9742
  const tab = activeTab();
8819
- const pickerKey = gitFooterPickerStateKey();
9743
+ if (!gitFooterPayloadVisible(payload, "webui-details-button")) mobileFooterExpanded = false;
9744
+ if (!gitFooterPayloadVisible(payload, "webui-model-picker")) footerModelPickerOpen = false;
9745
+ if (!gitFooterPayloadVisible(payload, "webui-thinking-picker")) footerThinkingPickerOpen = false;
9746
+ if (!gitFooterPayloadVisible(payload, "webui-branch-picker")) footerBranchPickerOpen = false;
9747
+ const pickerKey = gitFooterPickerStateKey(payload);
8820
9748
  const mainKeys = payload.main.map(gitFooterChipShapeKey);
8821
9749
  const metaKeys = payload.meta.map(gitFooterChipShapeKey);
8822
9750
 
@@ -8847,23 +9775,28 @@ function renderGitFooterPayload(payload) {
8847
9775
  elements.statusBar.classList.add("statusbar-git-footer");
8848
9776
  document.body.classList.toggle("footer-model-picker-open", isFooterPickerOpen());
8849
9777
 
8850
- const mainNodes = payload.main.map(renderGitFooterPayloadMetric);
9778
+ const mainNodes = payload.main.map((chip) => renderGitFooterPayloadMetric(chip, payload));
8851
9779
  const row1 = make("div", "footer-line footer-line-main");
8852
9780
  row1.append(...mainNodes);
8853
9781
 
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));
9782
+ const metaNodes = payload.meta.map((chip) => renderGitFooterPayloadMeta(chip, tab, payload));
8860
9783
  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());
9784
+ const row2Children = [...metaNodes];
9785
+ if (gitFooterPayloadVisible(payload, "webui-details-button")) {
9786
+ const footerToggle = make("button", "footer-details-toggle", mobileFooterExpanded ? "Less" : "Details");
9787
+ footerToggle.type = "button";
9788
+ footerToggle.setAttribute("aria-expanded", mobileFooterExpanded ? "true" : "false");
9789
+ footerToggle.addEventListener("click", () => setMobileFooterExpanded(!mobileFooterExpanded));
9790
+ row2Children.push(footerToggle);
9791
+ }
9792
+ row2.append(...row2Children);
9793
+
9794
+ const statusChildren = [row1, row2];
9795
+ if (gitFooterPayloadVisible(payload, "webui-refresh-button")) statusChildren.push(renderGitFooterRefreshButton());
9796
+ elements.statusBar.append(...statusChildren);
9797
+ if (footerModelPickerOpen && gitFooterPayloadVisible(payload, "webui-model-picker")) elements.statusBar.append(renderFooterModelPicker());
9798
+ if (footerThinkingPickerOpen && gitFooterPayloadVisible(payload, "webui-thinking-picker")) elements.statusBar.append(renderFooterThinkingPicker());
9799
+ if (footerBranchPickerOpen && gitFooterPayloadVisible(payload, "webui-branch-picker")) elements.statusBar.append(renderFooterBranchPicker());
8867
9800
  gitFooterRenderCache = { pickerKey, mainKeys, metaKeys, mainNodes, metaNodes };
8868
9801
  setMobileFooterExpanded(mobileFooterExpanded);
8869
9802
  updateFooterModelPickerPosition();
@@ -9057,7 +9990,81 @@ function renderGitDiffGrid(file) {
9057
9990
  return grid;
9058
9991
  }
9059
9992
 
9060
- function renderGitDiffFile(file) {
9993
+ function gitFileActionButtons(actions) {
9994
+ if (!actions?.length) return null;
9995
+ const wrap = make("span", "git-file-actions");
9996
+ for (const action of actions) {
9997
+ const button = make("button", `git-file-action ${action.className || ""}`.trim(), action.label);
9998
+ button.type = "button";
9999
+ button.title = action.title || action.label;
10000
+ button.addEventListener("click", (event) => {
10001
+ event.preventDefault();
10002
+ event.stopPropagation();
10003
+ action.onClick();
10004
+ });
10005
+ wrap.append(button);
10006
+ }
10007
+ return wrap;
10008
+ }
10009
+
10010
+ function copyGitTextToClipboard(text, label = "text") {
10011
+ navigator.clipboard?.writeText(text)
10012
+ .then(() => addEvent(`Copied ${label}: ${text}`, "info"))
10013
+ .catch(() => addEvent(`Clipboard unavailable; copy the ${label} manually.`, "error"));
10014
+ }
10015
+
10016
+ function copyGitPathToClipboard(path) {
10017
+ copyGitTextToClipboard(path, "path");
10018
+ }
10019
+
10020
+ // Git paths are repo-root-relative; the file viewer resolves against the tab
10021
+ // cwd. Translate when the tab sits at (or above within) the repo root.
10022
+ async function openGitFileFromChanges(repoRelPath) {
10023
+ const tabId = gitChangesState.tabId || activeTabId;
10024
+ const root = gitChangesState.data?.root || "";
10025
+ const tab = tabs.find((item) => item.id === tabId);
10026
+ let viewerPath = repoRelPath;
10027
+ if (root && tab?.cwd) {
10028
+ const absolute = `${root.replace(/\/+$/, "")}/${repoRelPath}`;
10029
+ const cwd = tab.cwd.replace(/\/+$/, "");
10030
+ if (absolute.startsWith(`${cwd}/`)) viewerPath = absolute.slice(cwd.length + 1);
10031
+ else if (root !== cwd) {
10032
+ addEvent(`Cannot open ${repoRelPath}: it is outside this tab's working directory.`, "error");
10033
+ return;
10034
+ }
10035
+ }
10036
+ closeGitChangesDialog();
10037
+ setSidePanelCollapsed(false);
10038
+ await openFileInViewer(viewerPath);
10039
+ }
10040
+
10041
+ function gitChangesCommonFileActions(path) {
10042
+ return [
10043
+ { label: "Open", title: "Open this file in the WebUI file viewer", onClick: () => openGitFileFromChanges(path) },
10044
+ { label: "Copy path", title: "Copy the repo-relative path", onClick: () => copyGitPathToClipboard(path) },
10045
+ ];
10046
+ }
10047
+
10048
+ function gitChangesFileActionsFor(sectionKey, path) {
10049
+ if (!path || gitChangesState.loading || gitChangesState.pulling || gitChangesState.fetching) return [];
10050
+ if (sectionKey === "unstaged") {
10051
+ return [
10052
+ { label: "Stage", title: `git add -- ${path}`, onClick: () => runGitFileAction("stage", path) },
10053
+ ...gitChangesCommonFileActions(path),
10054
+ { label: "Discard", className: "danger", title: `git restore -- ${path} (destructive)`, onClick: () => runGitFileAction("discard", path) },
10055
+ ];
10056
+ }
10057
+ if (sectionKey === "staged") {
10058
+ return [
10059
+ { label: "Unstage", title: `git restore --staged -- ${path}`, onClick: () => runGitFileAction("unstage", path) },
10060
+ ...gitChangesCommonFileActions(path),
10061
+ ];
10062
+ }
10063
+ if (sectionKey === "incoming") return [{ label: "Copy path", title: "Copy the repo-relative path", onClick: () => copyGitPathToClipboard(path) }];
10064
+ return [];
10065
+ }
10066
+
10067
+ function renderGitDiffFile(file, actions = []) {
9061
10068
  const details = make("details", `git-diff-file ${file.className || ""}`.trim());
9062
10069
  details.open = true;
9063
10070
  details.dataset.gitDiffFile = file.path || "diff";
@@ -9066,6 +10073,8 @@ function renderGitDiffFile(file) {
9066
10073
  make("span", "git-diff-file-name", file.path || "diff"),
9067
10074
  make("span", "git-diff-file-stats", file.statsText || `+${file.additions || 0} −${file.deletions || 0}`),
9068
10075
  );
10076
+ const actionButtons = gitFileActionButtons(actions);
10077
+ if (actionButtons) summary.append(actionButtons);
9069
10078
  details.append(summary);
9070
10079
  if (file.hunks?.length) {
9071
10080
  details.append(renderGitDiffGrid(file));
@@ -9083,7 +10092,20 @@ function renderGitDiffSection(section, files) {
9083
10092
  make("div", "git-diff-section-title", section?.label || "Git diff"),
9084
10093
  make("div", "git-diff-section-meta", `${files.length} file${files.length === 1 ? "" : "s"} · ${section?.command || "git diff"}`),
9085
10094
  );
9086
- wrapper.append(header, ...files.map(renderGitDiffFile));
10095
+ wrapper.append(header);
10096
+ if (section?.truncated) {
10097
+ const notice = make("div", "git-diff-truncated-notice");
10098
+ const fullCommand = String(section?.command || "git diff").replace(/\s--unified=0\b/, "");
10099
+ 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:`));
10100
+ notice.append(make("code", "git-tools-command", fullCommand));
10101
+ const copy = make("button", "git-file-action", "Copy command");
10102
+ copy.type = "button";
10103
+ copy.title = "Copy the full diff command";
10104
+ copy.addEventListener("click", () => copyGitTextToClipboard(fullCommand, "command"));
10105
+ notice.append(copy);
10106
+ wrapper.append(notice);
10107
+ }
10108
+ wrapper.append(...files.map((file) => renderGitDiffFile(file, gitChangesFileActionsFor(section?.key, file.path))));
9087
10109
  return wrapper;
9088
10110
  }
9089
10111
 
@@ -9157,9 +10179,21 @@ function renderGitUntrackedLoadingFile(entry) {
9157
10179
  }
9158
10180
 
9159
10181
  function renderGitUntrackedFile(entry) {
9160
- if (entry.contentMissing) return renderGitUntrackedLoadingFile(entry);
9161
- if (entry.error || entry.binary) return renderGitUntrackedRawFile(entry);
9162
- return renderGitDiffFile(gitUntrackedEntryToDiffFile(entry));
10182
+ const node = entry.contentMissing
10183
+ ? renderGitUntrackedLoadingFile(entry)
10184
+ : entry.error || entry.binary
10185
+ ? renderGitUntrackedRawFile(entry)
10186
+ : renderGitDiffFile(gitUntrackedEntryToDiffFile(entry));
10187
+ if (!gitChangesState.loading && !gitChangesState.pulling && !gitChangesState.fetching) {
10188
+ const summary = node.querySelector("summary");
10189
+ const actions = gitFileActionButtons([
10190
+ { label: "Stage", title: `git add -- ${entry.path}`, onClick: () => runGitFileAction("stage", entry.path) },
10191
+ ...gitChangesCommonFileActions(entry.path),
10192
+ { label: "Delete", className: "danger", title: "Delete this untracked file from disk (destructive)", onClick: () => runGitFileAction("delete-untracked", entry.path) },
10193
+ ]);
10194
+ if (summary && actions) summary.append(actions);
10195
+ }
10196
+ return node;
9163
10197
  }
9164
10198
 
9165
10199
  function replaceGitUntrackedEntry(entry, tabId = gitChangesState.tabId) {
@@ -9410,9 +10444,12 @@ function renderGitPullResultPanel(result) {
9410
10444
 
9411
10445
  function renderGitChangesDialog() {
9412
10446
  if (!elements.gitChangesDialog || !elements.gitChangesBody) return;
9413
- const { loading, pulling, error, message, pullResult, data } = gitChangesState;
10447
+ const { loading, pulling, fetching, error, message, pullResult, data, operation } = gitChangesState;
10448
+ const busyAction = pulling || fetching;
9414
10449
  const behind = Number(data?.remote?.behind ?? data?.summary?.behind ?? 0) || 0;
9415
- const canPull = behind > 0 && data?.remote?.canPull !== false;
10450
+ const diverged = data?.remote?.diverged === true;
10451
+ const canPull = behind > 0 && data?.remote?.canPull !== false && !diverged;
10452
+ const hasOperation = Boolean(operation?.operation);
9416
10453
  const remoteNotice = !error && data?.remote?.error ? `Incoming diff unavailable: ${data.remote.error}` : "";
9417
10454
  if (elements.gitChangesTitle) elements.gitChangesTitle.textContent = "Git Changes";
9418
10455
  if (elements.gitChangesSubtitle) {
@@ -9420,16 +10457,25 @@ function renderGitChangesDialog() {
9420
10457
  elements.gitChangesSubtitle.textContent = data?.remote?.upstream ? `${base} · upstream ${data.remote.upstream}` : base;
9421
10458
  }
9422
10459
  if (elements.gitChangesRefreshButton) {
9423
- elements.gitChangesRefreshButton.disabled = loading || pulling;
10460
+ elements.gitChangesRefreshButton.disabled = loading || busyAction;
9424
10461
  elements.gitChangesRefreshButton.textContent = loading ? "Refreshing…" : "Refresh";
9425
10462
  }
10463
+ if (elements.gitChangesFetchButton) {
10464
+ elements.gitChangesFetchButton.disabled = loading || busyAction || !data?.root;
10465
+ elements.gitChangesFetchButton.textContent = fetching ? "Fetching…" : "Fetch";
10466
+ elements.gitChangesFetchButton.title = "Run git fetch --prune to refresh remote tracking state";
10467
+ }
9426
10468
  if (elements.gitChangesPullButton) {
9427
- elements.gitChangesPullButton.disabled = loading || pulling || !canPull;
10469
+ elements.gitChangesPullButton.disabled = loading || busyAction || !canPull;
9428
10470
  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";
10471
+ elements.gitChangesPullButton.title = canPull
10472
+ ? "Run git pull --ff-only for the current repository"
10473
+ : diverged
10474
+ ? "Local and remote branches have diverged; use the integrate actions below instead of one-click pull."
10475
+ : "No remote commits to pull";
9430
10476
  }
9431
10477
  if (elements.gitChangesStatus) {
9432
- const statusText = error || (pulling ? "Pulling changes…" : loading ? "Loading git diff…" : message || remoteNotice || (data ? gitChangesGeneratedLabel(data) : ""));
10478
+ const statusText = error || (pulling ? "Pulling changes…" : fetching ? "Fetching from remote…" : loading ? "Loading git diff…" : message || remoteNotice || (data ? gitChangesGeneratedLabel(data) : ""));
9433
10479
  elements.gitChangesStatus.className = `git-changes-status ${error || remoteNotice ? "error" : message ? "success" : "muted"}`;
9434
10480
  elements.gitChangesStatus.textContent = statusText;
9435
10481
  elements.gitChangesStatus.hidden = !elements.gitChangesStatus.textContent;
@@ -9451,7 +10497,18 @@ function renderGitChangesDialog() {
9451
10497
  }
9452
10498
 
9453
10499
  if (pullResult) body.append(renderGitPullResultPanel(pullResult));
10500
+ if (hasOperation) {
10501
+ const panel = renderGitOperationPanel(operation);
10502
+ if (panel) body.append(panel);
10503
+ }
9454
10504
  body.append(renderGitChangesOverview(data));
10505
+ const fetchStateLines = gitChangesFetchStateLines();
10506
+ if (fetchStateLines.length) {
10507
+ const fetchNote = make("div", "git-tools-note git-fetch-state-note");
10508
+ for (const line of fetchStateLines) fetchNote.append(make("div", undefined, line));
10509
+ body.append(fetchNote);
10510
+ }
10511
+ if (diverged && !hasOperation) body.append(renderGitDivergedBar(data));
9455
10512
  const parsedSections = (Array.isArray(data.sections) ? data.sections : [])
9456
10513
  .map((section) => ({ section, files: parseGitUnifiedDiff(section.diff || "") }))
9457
10514
  .filter((entry) => entry.files.length > 0);
@@ -9464,23 +10521,40 @@ function renderGitChangesDialog() {
9464
10521
  }
9465
10522
  for (const entry of parsedSections) body.append(renderGitDiffSection(entry.section, entry.files));
9466
10523
  if (untracked.length) body.append(renderGitUntrackedSection(untracked));
9467
- if (!hasVisibleFiles) {
10524
+ if (!hasVisibleFiles && !hasOperation) {
9468
10525
  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
10526
  body.append(make("div", "git-changes-empty success", emptyMessage));
9470
10527
  }
10528
+ body.append(renderGitToolsSection());
9471
10529
  if (hasVisibleFiles) requestAnimationFrame(updateGitChangesCurrentFileHeader);
9472
10530
  }
9473
10531
 
9474
10532
  async function loadGitChangesDialog(tabContext = activeTabContext()) {
9475
10533
  const requestSerial = ++gitChangesRequestSerial;
9476
10534
  gitChangesUntrackedContentRequests.clear();
9477
- gitChangesState = { ...gitChangesState, loading: true, error: "", message: "", pullResult: null, tabId: tabContext.tabId || activeTabId };
10535
+ gitChangesState = { ...gitChangesState, loading: true, error: "", errorCode: "", errorHint: "", message: "", pullResult: null, tabId: tabContext.tabId || activeTabId };
9478
10536
  renderGitChangesDialog();
9479
10537
  try {
9480
- const response = await api("/api/git-changes", { tabId: tabContext.tabId });
10538
+ const [response, operationResponse] = await Promise.all([
10539
+ api("/api/git-changes", { tabId: tabContext.tabId }),
10540
+ api("/api/git-operation", { tabId: tabContext.tabId }).catch(() => null),
10541
+ ]);
9481
10542
  if (requestSerial !== gitChangesRequestSerial) return;
9482
10543
  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 };
10544
+ gitChangesState = {
10545
+ ...gitChangesState,
10546
+ loading: false,
10547
+ pulling: false,
10548
+ fetching: false,
10549
+ error: "",
10550
+ errorCode: "",
10551
+ errorHint: "",
10552
+ message: "",
10553
+ pullResult: null,
10554
+ data: response.data || null,
10555
+ operation: operationResponse?.ok ? operationResponse.data : null,
10556
+ tabId: tabContext.tabId || activeTabId,
10557
+ };
9484
10558
  } catch (error) {
9485
10559
  if (requestSerial !== gitChangesRequestSerial) return;
9486
10560
  gitChangesState = { ...gitChangesState, loading: false, error: error.message || String(error) };
@@ -9493,7 +10567,22 @@ function openGitChangesDialog() {
9493
10567
  hideFooterTooltip();
9494
10568
  const tabContext = activeTabContext();
9495
10569
  const tabId = tabContext.tabId || activeTabId;
9496
- gitChangesState = { loading: true, pulling: false, error: "", message: "", pullResult: null, data: gitChangesState.tabId === tabId ? gitChangesState.data : null, tabId };
10570
+ if (gitToolsState.tabId !== tabId) resetGitToolsState(tabId);
10571
+ gitChangesState = {
10572
+ ...gitChangesState,
10573
+ loading: true,
10574
+ pulling: false,
10575
+ fetching: false,
10576
+ error: "",
10577
+ errorCode: "",
10578
+ errorHint: "",
10579
+ message: "",
10580
+ pullResult: null,
10581
+ data: gitChangesState.tabId === tabId ? gitChangesState.data : null,
10582
+ operation: gitChangesState.tabId === tabId ? gitChangesState.operation : null,
10583
+ lastFetch: gitChangesState.tabId === tabId ? gitChangesState.lastFetch : null,
10584
+ tabId,
10585
+ };
9497
10586
  renderGitChangesDialog();
9498
10587
  if (!elements.gitChangesDialog.open) elements.gitChangesDialog.showModal();
9499
10588
  loadGitChangesDialog(tabContext).catch((error) => addEvent(error.message || String(error), "error"));
@@ -9507,25 +10596,30 @@ function refreshGitChangesDialog() {
9507
10596
  async function pullGitChangesDialog() {
9508
10597
  const tabContext = { tabId: gitChangesState.tabId || activeTabId };
9509
10598
  const behind = Number(gitChangesState.data?.remote?.behind ?? gitChangesState.data?.summary?.behind ?? 0) || 0;
9510
- if (behind <= 0 || gitChangesState.pulling || gitChangesState.loading) return;
10599
+ if (behind <= 0 || gitChangesState.pulling || gitChangesState.loading || gitChangesState.fetching) return;
10600
+ if (gitChangesState.data?.remote?.diverged === true) return;
9511
10601
  const root = gitChangesState.data?.root || "the current repository";
9512
10602
  if (!window.confirm(`Run git pull --ff-only in ${root}?`)) return;
9513
10603
 
9514
10604
  const requestSerial = ++gitChangesRequestSerial;
9515
- gitChangesState = { ...gitChangesState, pulling: true, loading: false, error: "", message: "", pullResult: null, tabId: tabContext.tabId };
10605
+ gitChangesState = { ...gitChangesState, pulling: true, loading: false, error: "", errorCode: "", errorHint: "", message: "", pullResult: null, tabId: tabContext.tabId };
9516
10606
  renderGitChangesDialog();
9517
10607
  try {
9518
10608
  const response = await api("/api/git-changes/pull", { method: "POST", body: {}, tabId: tabContext.tabId });
9519
10609
  if (requestSerial !== gitChangesRequestSerial) return;
9520
10610
  if (!response.ok) {
9521
- const detail = [response.error, response.data?.stderr || response.data?.stdout].filter(Boolean).join("\n").trim();
10611
+ gitChangesState = { ...gitChangesState, errorCode: response.code || "" };
10612
+ const detail = [response.error, response.hint].filter(Boolean).join("\n").trim();
9522
10613
  throw new Error(detail || "Failed to pull git changes");
9523
10614
  }
9524
10615
  const pullResult = normalizeGitPullResult(response.data || {});
9525
10616
  gitChangesState = {
10617
+ ...gitChangesState,
9526
10618
  loading: false,
9527
10619
  pulling: false,
9528
10620
  error: "",
10621
+ errorCode: "",
10622
+ errorHint: "",
9529
10623
  message: gitPullResultStatus(pullResult),
9530
10624
  pullResult,
9531
10625
  data: response.data?.changes || gitChangesState.data,
@@ -9544,10 +10638,742 @@ async function pullGitChangesDialog() {
9544
10638
  function closeGitChangesDialog() {
9545
10639
  gitChangesRequestSerial += 1;
9546
10640
  gitChangesUntrackedContentRequests.clear();
9547
- gitChangesState = { ...gitChangesState, loading: false, pulling: false };
10641
+ gitChangesState = { ...gitChangesState, loading: false, pulling: false, fetching: false };
9548
10642
  if (elements.gitChangesDialog?.open) elements.gitChangesDialog.close();
9549
10643
  }
9550
10644
 
10645
+ async function fetchGitChangesDialog() {
10646
+ const tabId = gitChangesState.tabId || activeTabId;
10647
+ if (gitChangesState.fetching || gitChangesState.loading || gitChangesState.pulling) return;
10648
+ const requestSerial = ++gitChangesRequestSerial;
10649
+ gitChangesState = { ...gitChangesState, fetching: true, error: "", errorCode: "", errorHint: "", message: "", pullResult: null };
10650
+ renderGitChangesDialog();
10651
+ try {
10652
+ const response = await api("/api/git-fetch", { method: "POST", body: {}, tabId });
10653
+ if (requestSerial !== gitChangesRequestSerial) return;
10654
+ if (!response.ok) {
10655
+ gitChangesState = { ...gitChangesState, errorCode: response.code || "" };
10656
+ throw new Error([response.error, response.hint].filter(Boolean).join("\n") || "git fetch failed");
10657
+ }
10658
+ const summaryLine = String(response.data?.summary || "").split(/\r?\n/).map((line) => line.trim()).filter(Boolean).slice(-1)[0] || "";
10659
+ gitChangesState = {
10660
+ ...gitChangesState,
10661
+ fetching: false,
10662
+ data: response.data?.changes || gitChangesState.data,
10663
+ lastFetch: { at: Date.now(), summary: summaryLine, error: "" },
10664
+ message: summaryLine && !/^fetching/i.test(summaryLine) ? `Fetched (--prune). ${summaryLine}` : "Fetched remote state (git fetch --prune).",
10665
+ };
10666
+ addEvent("Fetched remote state (git fetch --prune).", "success");
10667
+ requestGitFooterWebuiPayload(activeTabContext(tabId), { force: true });
10668
+ } catch (error) {
10669
+ if (requestSerial !== gitChangesRequestSerial) return;
10670
+ gitChangesState = { ...gitChangesState, fetching: false, error: error.message || String(error), lastFetch: { at: Date.now(), summary: "", error: error.message || String(error) } };
10671
+ }
10672
+ renderGitChangesDialog();
10673
+ }
10674
+
10675
+ // Fetch state lines shown inside the dialog: the extension's startup/tab fetch
10676
+ // state (from the changes-chip tooltip payload) plus this dialog's last fetch.
10677
+ function gitChangesFetchStateLines() {
10678
+ const lines = [];
10679
+ const chip = parseGitFooterWebuiPayload()?.meta?.find((item) => item.key === "changes");
10680
+ const extensionLine = String(chip?.title || "").split("\n").find((line) => /git fetch/i.test(line));
10681
+ if (extensionLine) lines.push(`Tab fetch state: ${extensionLine.trim()}`);
10682
+ const lastFetch = gitChangesState.lastFetch;
10683
+ if (lastFetch?.at) {
10684
+ const time = new Date(lastFetch.at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
10685
+ 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."}`);
10686
+ }
10687
+ return lines;
10688
+ }
10689
+
10690
+ async function integrateGitChangesDialog(mode) {
10691
+ const tabId = gitChangesState.tabId || activeTabId;
10692
+ const data = gitChangesState.data;
10693
+ const upstream = data?.remote?.upstream || "@{upstream}";
10694
+ const command = mode === "merge" ? `git merge --no-edit ${upstream}` : `git rebase ${upstream}`;
10695
+ if (!window.confirm([
10696
+ `${mode === "merge" ? "Merge" : "Rebase onto"} ${upstream} in ${data?.root || "the current repository"}?`,
10697
+ "",
10698
+ `Command: ${command}`,
10699
+ mode === "rebase" ? "Rebase rewrites local commits. Conflicts open the conflicts panel." : "Conflicts open the conflicts panel.",
10700
+ "For risky integration, prefer a separate worktree instead.",
10701
+ ].join("\n"))) return;
10702
+ gitChangesState = { ...gitChangesState, pulling: true, error: "", errorCode: "", errorHint: "", message: "", pullResult: null };
10703
+ renderGitChangesDialog();
10704
+ try {
10705
+ const response = await api("/api/git-changes/integrate", { method: "POST", body: { mode, confirmed: true }, tabId });
10706
+ if (!response.ok) {
10707
+ const errText = [response.error, response.hint].filter(Boolean).join("\n") || `git ${mode} failed`;
10708
+ gitChangesState = { ...gitChangesState, pulling: false };
10709
+ await loadGitChangesDialog({ tabId });
10710
+ gitChangesState = { ...gitChangesState, error: errText, errorCode: response.code || "" };
10711
+ renderGitChangesDialog();
10712
+ return;
10713
+ }
10714
+ gitChangesState = { ...gitChangesState, pulling: false, message: `Integrated ${upstream} via ${mode}.`, data: response.data?.changes || gitChangesState.data };
10715
+ addEvent(`Integrated ${upstream} via ${mode}.`, "success");
10716
+ renderGitChangesDialog();
10717
+ requestGitFooterWebuiPayload(activeTabContext(tabId), { force: true });
10718
+ } catch (error) {
10719
+ gitChangesState = { ...gitChangesState, pulling: false, error: error.message || String(error) };
10720
+ renderGitChangesDialog();
10721
+ }
10722
+ }
10723
+
10724
+ async function runGitFileAction(action, path) {
10725
+ const tabId = gitChangesState.tabId || activeTabId;
10726
+ const root = gitChangesState.data?.root || "the repository";
10727
+ const config = {
10728
+ stage: { url: "/api/git-changes/stage-file", body: { path }, label: `Staged ${path}.` },
10729
+ unstage: { url: "/api/git-changes/unstage-file", body: { path }, label: `Unstaged ${path}.` },
10730
+ discard: {
10731
+ url: "/api/git-changes/discard-file",
10732
+ body: { path, confirmed: true },
10733
+ label: `Discarded changes in ${path}.`,
10734
+ confirm: `Discard working tree changes in ${path}?\n\nRepository: ${root}\nCommand: git restore -- ${path}\n\nThis permanently reverts unstaged edits to this file.`,
10735
+ },
10736
+ "delete-untracked": {
10737
+ url: "/api/git-changes/delete-untracked",
10738
+ body: { path, confirmed: true },
10739
+ label: `Deleted untracked file ${path}.`,
10740
+ confirm: `Delete untracked file ${path}?\n\nRepository: ${root}\n\nThis permanently removes the file from disk.`,
10741
+ },
10742
+ }[action];
10743
+ if (!config) return;
10744
+ if (config.confirm && !window.confirm(config.confirm)) return;
10745
+ try {
10746
+ const response = await api(config.url, { method: "POST", body: config.body, tabId });
10747
+ if (!response.ok) throw new Error([response.error, response.hint].filter(Boolean).join("\n") || `git ${action} failed`);
10748
+ gitChangesState = { ...gitChangesState, data: response.data?.changes || gitChangesState.data, message: config.label, error: "", errorCode: "", errorHint: "" };
10749
+ addEvent(config.label, "success");
10750
+ renderGitChangesDialog();
10751
+ requestGitFooterWebuiPayload(activeTabContext(tabId), { force: true });
10752
+ } catch (error) {
10753
+ gitChangesState = { ...gitChangesState, error: error.message || String(error) };
10754
+ renderGitChangesDialog();
10755
+ addEvent(error.message || String(error), "error");
10756
+ }
10757
+ }
10758
+
10759
+ const GIT_OPERATION_TITLES = {
10760
+ merge: "Merge in progress",
10761
+ rebase: "Rebase in progress",
10762
+ "cherry-pick": "Cherry-pick in progress",
10763
+ revert: "Revert in progress",
10764
+ bisect: "Bisect in progress",
10765
+ };
10766
+
10767
+ function renderGitConflictPreview(preview) {
10768
+ if (!preview) return null;
10769
+ 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.`);
10770
+ if (preview.kind === "large") return make("pre", "git-conflict-preview muted", `File too large to preview (${formatBytes(preview.size || 0)}).`);
10771
+ if (preview.kind === "missing") return make("pre", "git-conflict-preview muted", "File is missing in the working tree (deleted on one side).");
10772
+ if (preview.kind === "error") return make("pre", "git-conflict-preview muted", preview.error || "Preview unavailable.");
10773
+ if (preview.kind !== "text") return null;
10774
+ if (!preview.hunks?.length) {
10775
+ 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.");
10776
+ }
10777
+ const text = preview.hunks.map((hunk) => hunk.lines.join("\n") + (hunk.truncated ? "\n…" : "")).join("\n⋯\n");
10778
+ return make("pre", "git-conflict-preview", text);
10779
+ }
10780
+
10781
+ async function runGitOperationRequest(url, body, successLabel) {
10782
+ const tabId = gitChangesState.tabId || activeTabId;
10783
+ gitToolsState.busy.add("operation");
10784
+ renderGitChangesDialog();
10785
+ try {
10786
+ const response = await api(url, { method: "POST", body, tabId });
10787
+ if (!response.ok) throw new Error([response.error, response.hint].filter(Boolean).join("\n") || "git operation failed");
10788
+ gitToolsState.busy.delete("operation");
10789
+ addEvent(`${successLabel}.`, "success");
10790
+ await loadGitChangesDialog({ tabId });
10791
+ gitChangesState = { ...gitChangesState, message: `${successLabel}.` };
10792
+ renderGitChangesDialog();
10793
+ requestGitFooterWebuiPayload(activeTabContext(tabId), { force: true });
10794
+ } catch (error) {
10795
+ gitToolsState.busy.delete("operation");
10796
+ gitChangesState = { ...gitChangesState, error: error.message || String(error) };
10797
+ renderGitChangesDialog();
10798
+ }
10799
+ }
10800
+
10801
+ function renderGitOperationPanel(operation) {
10802
+ const kind = operation?.operation;
10803
+ if (!kind) return null;
10804
+ const busy = gitToolsState.busy.has("operation") || gitChangesState.loading || gitChangesState.pulling || gitChangesState.fetching;
10805
+ const conflicts = operation.conflicts || [];
10806
+ const panel = make("section", "git-operation-panel");
10807
+ const header = make("div", "git-operation-header");
10808
+ header.append(
10809
+ make("strong", "git-operation-title", GIT_OPERATION_TITLES[kind] || `${kind} in progress`),
10810
+ make("span", "git-operation-meta", `${conflicts.length} conflicted file${conflicts.length === 1 ? "" : "s"} · ${operation.root || ""}`),
10811
+ );
10812
+ panel.append(header);
10813
+
10814
+ if (kind === "bisect") {
10815
+ if (operation.bisect?.log) panel.append(make("pre", "git-conflict-preview", operation.bisect.log));
10816
+ const row = make("div", "git-operation-actions");
10817
+ for (const verdict of ["good", "bad", "skip"]) {
10818
+ const button = make("button", "git-operation-button", `bisect ${verdict}`);
10819
+ button.type = "button";
10820
+ button.disabled = busy;
10821
+ button.title = `git bisect ${verdict}`;
10822
+ button.addEventListener("click", () => runGitOperationRequest("/api/git-operation/bisect", { verdict }, `Marked the current revision as ${verdict}`));
10823
+ row.append(button);
10824
+ }
10825
+ const reset = make("button", "git-operation-button danger", "Reset bisect");
10826
+ reset.type = "button";
10827
+ reset.disabled = busy;
10828
+ reset.title = "git bisect reset";
10829
+ reset.addEventListener("click", () => {
10830
+ if (!window.confirm(`Reset the bisect session in ${operation.root}?\n\nCommand: git bisect reset\nThis returns to the pre-bisect checkout.`)) return;
10831
+ runGitOperationRequest("/api/git-operation/bisect", { verdict: "reset", confirmed: true }, "Reset the bisect session");
10832
+ });
10833
+ row.append(reset);
10834
+ panel.append(row);
10835
+ return panel;
10836
+ }
10837
+
10838
+ if (conflicts.length) {
10839
+ const list = make("div", "git-conflict-list");
10840
+ for (const conflict of conflicts) {
10841
+ const item = make("details", "git-conflict-file");
10842
+ item.open = conflicts.length <= 3;
10843
+ const summary = make("summary", "git-conflict-summary");
10844
+ summary.append(
10845
+ make("span", "git-conflict-status", conflict.status || "UU"),
10846
+ make("span", "git-conflict-path", conflict.path),
10847
+ );
10848
+ const actions = gitFileActionButtons([
10849
+ {
10850
+ label: "Mark resolved",
10851
+ title: `git add -- ${conflict.path}`,
10852
+ onClick: () => runGitOperationRequest("/api/git-operation/stage-file", { path: conflict.path }, `Marked ${conflict.path} as resolved`),
10853
+ },
10854
+ ]);
10855
+ if (actions) summary.append(actions);
10856
+ item.append(summary);
10857
+ const preview = renderGitConflictPreview(conflict.preview);
10858
+ if (preview) item.append(preview);
10859
+ list.append(item);
10860
+ }
10861
+ panel.append(list);
10862
+ } else {
10863
+ panel.append(make("div", "git-changes-empty success", "No unmerged paths remain. Continue to finish the operation."));
10864
+ }
10865
+
10866
+ const row = make("div", "git-operation-actions");
10867
+ const refresh = make("button", "git-operation-button", "Refresh conflicts");
10868
+ refresh.type = "button";
10869
+ refresh.disabled = busy;
10870
+ refresh.addEventListener("click", refreshGitChangesDialog);
10871
+ row.append(refresh);
10872
+
10873
+ const cont = make("button", "git-operation-button primary", kind === "merge" ? "Continue (commit merge)" : "Continue");
10874
+ cont.type = "button";
10875
+ cont.disabled = busy || operation.canContinue !== true;
10876
+ cont.title = operation.canContinue ? operation.commands?.continue || "" : "Resolve and stage every conflicted file first.";
10877
+ cont.addEventListener("click", () => runGitOperationRequest("/api/git-operation/continue", {}, `Continued the ${kind}`));
10878
+ row.append(cont);
10879
+
10880
+ if (operation.canSkip) {
10881
+ const skip = make("button", "git-operation-button", "Skip");
10882
+ skip.type = "button";
10883
+ skip.disabled = busy;
10884
+ skip.title = operation.commands?.skip || "";
10885
+ skip.addEventListener("click", () => {
10886
+ 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;
10887
+ runGitOperationRequest("/api/git-operation/skip", {}, `Skipped the current ${kind} step`);
10888
+ });
10889
+ row.append(skip);
10890
+ }
10891
+
10892
+ const abort = make("button", "git-operation-button danger", "Abort");
10893
+ abort.type = "button";
10894
+ abort.disabled = busy;
10895
+ abort.title = operation.commands?.abort || "";
10896
+ abort.addEventListener("click", () => {
10897
+ const summary = operation.summary || {};
10898
+ if (!window.confirm([
10899
+ `Abort the ${kind} in ${operation.root}?`,
10900
+ "",
10901
+ `Command: ${operation.commands?.abort || `git ${kind} --abort`}`,
10902
+ `Working tree: ${summary.staged || 0} staged · ${summary.unstaged || 0} unstaged · ${conflicts.length} conflicted`,
10903
+ "",
10904
+ "This discards the in-progress operation state and returns to the pre-operation HEAD.",
10905
+ ].join("\n"))) return;
10906
+ runGitOperationRequest("/api/git-operation/abort", { confirmed: true }, `Aborted the ${kind}`);
10907
+ });
10908
+ row.append(abort);
10909
+ panel.append(row);
10910
+ return panel;
10911
+ }
10912
+
10913
+ function renderGitDivergedBar(data) {
10914
+ const remote = data?.remote || {};
10915
+ const bar = make("section", "git-diverged-bar");
10916
+ bar.append(make("strong", "git-diverged-title", `Diverged from ${remote.upstream || "upstream"}: ↑${remote.ahead || 0} local · ↓${remote.behind || 0} remote.`));
10917
+ 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."));
10918
+ const row = make("div", "git-operation-actions");
10919
+ const busy = gitChangesState.loading || gitChangesState.pulling || gitChangesState.fetching;
10920
+ const addButton = (label, className, title, handler) => {
10921
+ const button = make("button", `git-operation-button ${className}`.trim(), label);
10922
+ button.type = "button";
10923
+ button.disabled = busy;
10924
+ button.title = title;
10925
+ button.addEventListener("click", handler);
10926
+ row.append(button);
10927
+ };
10928
+ addButton("Merge upstream…", "", `git merge --no-edit ${remote.upstream || "@{upstream}"}`, () => integrateGitChangesDialog("merge"));
10929
+ addButton("Rebase onto upstream…", "", `git rebase ${remote.upstream || "@{upstream}"}`, () => integrateGitChangesDialog("rebase"));
10930
+ addButton("Create integration worktree", "", "Open the branch picker to integrate in a separate worktree tab", () => {
10931
+ closeGitChangesDialog();
10932
+ openBranchWorktreePicker();
10933
+ });
10934
+ bar.append(row);
10935
+ return bar;
10936
+ }
10937
+
10938
+ // ---- Git tools (stash, undo, worktrees, submodules, tags, signing) ----
10939
+
10940
+ const GIT_TOOLS_SECTIONS = [
10941
+ { key: "stash", title: "Stash", detail: "List, apply, pop, drop, or create stashes." },
10942
+ { key: "undo", title: "Undo & recovery", detail: "Undo the last unpushed commit, amend its message, review recent HEAD history." },
10943
+ { key: "worktrees", title: "Worktrees", detail: "Health, removal, and pruning of git worktrees." },
10944
+ { key: "submodules", title: "Submodules", detail: "Status and recursive update." },
10945
+ { key: "tags", title: "Tags", detail: "Recent tags and annotated tag creation." },
10946
+ { key: "signing", title: "Signing", detail: "Commit signing configuration and diagnostics." },
10947
+ ];
10948
+
10949
+ const GIT_TOOLS_ENDPOINTS = {
10950
+ stash: "/api/git-stash",
10951
+ undo: "/api/git-undo",
10952
+ worktrees: "/api/git-worktrees",
10953
+ submodules: "/api/git-submodules",
10954
+ tags: "/api/git-tags",
10955
+ signing: "/api/git-signing",
10956
+ };
10957
+
10958
+ function resetGitToolsState(tabId) {
10959
+ gitToolsState = { tabId, openSections: new Set(), cache: {}, busy: new Set(), notice: {} };
10960
+ }
10961
+
10962
+ async function loadGitToolsSection(key, { force = false } = {}) {
10963
+ const tabId = gitChangesState.tabId || activeTabId;
10964
+ if (!force && gitToolsState.cache[key]) return;
10965
+ if (gitToolsState.busy.has(`load:${key}`)) return;
10966
+ gitToolsState.busy.add(`load:${key}`);
10967
+ try {
10968
+ const response = await api(GIT_TOOLS_ENDPOINTS[key], { tabId });
10969
+ if (!response.ok) throw new Error(response.error || `Failed to load ${key}`);
10970
+ gitToolsState.cache[key] = response.data;
10971
+ if (key === "undo") {
10972
+ const reflog = await api("/api/git-reflog", { tabId }).catch(() => null);
10973
+ gitToolsState.cache.reflog = reflog?.ok ? reflog.data : null;
10974
+ }
10975
+ gitToolsState.notice[key] = "";
10976
+ } catch (error) {
10977
+ gitToolsState.notice[key] = error.message || String(error);
10978
+ } finally {
10979
+ gitToolsState.busy.delete(`load:${key}`);
10980
+ renderGitChangesDialog();
10981
+ }
10982
+ }
10983
+
10984
+ async function runGitToolAction(sectionKey, { url, method = "POST", body, confirm, success, successMessage, refreshChanges = false }) {
10985
+ const tabId = gitChangesState.tabId || activeTabId;
10986
+ if (confirm && !window.confirm(confirm)) return;
10987
+ gitToolsState.busy.add(sectionKey);
10988
+ renderGitChangesDialog();
10989
+ try {
10990
+ const response = await api(url, { method, body, tabId });
10991
+ if (!response.ok) throw new Error([response.error, response.hint].filter(Boolean).join("\n") || "git action failed");
10992
+ const finalMessage = (typeof successMessage === "function" ? successMessage(response) : "") || success;
10993
+ gitToolsState.notice[sectionKey] = "";
10994
+ gitToolsState.busy.delete(sectionKey);
10995
+ addEvent(finalMessage, "success");
10996
+ await loadGitToolsSection(sectionKey, { force: true });
10997
+ if (refreshChanges) await loadGitChangesDialog({ tabId });
10998
+ gitChangesState = { ...gitChangesState, message: finalMessage };
10999
+ renderGitChangesDialog();
11000
+ requestGitFooterWebuiPayload(activeTabContext(tabId), { force: true });
11001
+ } catch (error) {
11002
+ gitToolsState.busy.delete(sectionKey);
11003
+ gitToolsState.notice[sectionKey] = error.message || String(error);
11004
+ renderGitChangesDialog();
11005
+ }
11006
+ }
11007
+
11008
+ function gitToolsButton(label, { className = "", disabled = false, title = "" } = {}, handler) {
11009
+ const button = make("button", `git-operation-button ${className}`.trim(), label);
11010
+ button.type = "button";
11011
+ button.disabled = disabled;
11012
+ if (title) button.title = title;
11013
+ button.addEventListener("click", handler);
11014
+ return button;
11015
+ }
11016
+
11017
+ // Apply/pop/drop always show the stash's --stat preview in the confirmation,
11018
+ // so no stash is modified sight-unseen.
11019
+ async function confirmGitStashActionWithPreview(stash, question) {
11020
+ const tabId = gitChangesState.tabId || activeTabId;
11021
+ let statText = "";
11022
+ try {
11023
+ const preview = await api(`/api/git-stash/show?ref=${encodeURIComponent(stash.ref)}`, { tabId });
11024
+ statText = preview?.ok ? String(preview.data?.stat || "").trim() : "";
11025
+ } catch {
11026
+ // Preview is best-effort; the confirmation still shows the stash subject.
11027
+ }
11028
+ return window.confirm([
11029
+ question,
11030
+ "",
11031
+ stash.subject || stash.ref,
11032
+ "",
11033
+ statText ? `Preview (git stash show --stat):\n${statText.slice(0, 2000)}` : "Preview unavailable.",
11034
+ ].join("\n"));
11035
+ }
11036
+
11037
+ function renderGitStashTools(body, data, busy) {
11038
+ const row = make("div", "git-operation-actions");
11039
+ row.append(
11040
+ gitToolsButton("Stash tracked changes", { disabled: busy, title: "git stash push" }, () =>
11041
+ runGitToolAction("stash", { url: "/api/git-stash/save", body: {}, success: "Stashed tracked changes.", refreshChanges: true })),
11042
+ gitToolsButton("Stash incl. untracked", { disabled: busy, title: "git stash push --include-untracked" }, () =>
11043
+ runGitToolAction("stash", { url: "/api/git-stash/save", body: { includeUntracked: true }, success: "Stashed tracked and untracked changes.", refreshChanges: true })),
11044
+ );
11045
+ body.append(row);
11046
+ const stashes = data.stashes || [];
11047
+ if (!stashes.length) {
11048
+ body.append(make("div", "git-changes-empty", "No stashes."));
11049
+ return body;
11050
+ }
11051
+ for (const stash of stashes) {
11052
+ const item = make("details", "git-tools-item");
11053
+ const summary = make("summary", "git-tools-item-summary");
11054
+ summary.append(make("span", "git-tools-item-ref", stash.ref), make("span", "git-tools-item-subject", stash.subject || ""));
11055
+ const actions = gitFileActionButtons([
11056
+ {
11057
+ label: "Apply",
11058
+ title: `git stash apply ${stash.ref}`,
11059
+ onClick: () => confirmGitStashActionWithPreview(stash, `Apply ${stash.ref} to the working tree?`).then((confirmed) => {
11060
+ if (confirmed) runGitToolAction("stash", { url: "/api/git-stash/apply", body: { ref: stash.ref }, success: `Applied ${stash.ref}.`, refreshChanges: true });
11061
+ }),
11062
+ },
11063
+ {
11064
+ label: "Pop",
11065
+ title: `git stash pop ${stash.ref}`,
11066
+ onClick: () => confirmGitStashActionWithPreview(stash, `Pop ${stash.ref}? This applies the stash and removes the entry on success.`).then((confirmed) => {
11067
+ if (confirmed) runGitToolAction("stash", { url: "/api/git-stash/pop", body: { ref: stash.ref }, success: `Popped ${stash.ref}.`, refreshChanges: true });
11068
+ }),
11069
+ },
11070
+ {
11071
+ label: "Drop",
11072
+ className: "danger",
11073
+ title: `git stash drop ${stash.ref}`,
11074
+ onClick: () => confirmGitStashActionWithPreview(stash, `Drop ${stash.ref}? This permanently deletes the stash entry.`).then((confirmed) => {
11075
+ if (confirmed) runGitToolAction("stash", { url: "/api/git-stash/drop", body: { ref: stash.ref, confirmed: true }, success: `Dropped ${stash.ref}.` });
11076
+ }),
11077
+ },
11078
+ ]);
11079
+ if (actions) summary.append(actions);
11080
+ item.append(summary);
11081
+ item.addEventListener("toggle", async () => {
11082
+ if (!item.open || item.dataset.previewLoaded) return;
11083
+ item.dataset.previewLoaded = "1";
11084
+ const placeholder = make("pre", "git-conflict-preview muted", "Loading stash preview…");
11085
+ item.append(placeholder);
11086
+ const preview = await api(`/api/git-stash/show?ref=${encodeURIComponent(stash.ref)}`, { tabId: gitChangesState.tabId || activeTabId }).catch(() => null);
11087
+ const text = preview?.ok ? [preview.data?.stat, preview.data?.patch].filter(Boolean).join("\n\n") : "Preview unavailable.";
11088
+ placeholder.textContent = text || "Empty stash preview.";
11089
+ placeholder.classList.toggle("muted", !preview?.ok);
11090
+ });
11091
+ body.append(item);
11092
+ }
11093
+ return body;
11094
+ }
11095
+
11096
+ function renderGitUndoTools(body, data, busy) {
11097
+ const last = data.lastCommit;
11098
+ body.append(make("div", "git-tools-note", last ? `Last commit: ${last.hash} ${last.subject}` : "No commits yet."));
11099
+ const row = make("div", "git-operation-actions");
11100
+ row.append(gitToolsButton(
11101
+ "Undo last commit (keep changes)",
11102
+ { disabled: busy || !data.canUndoLastCommit, title: data.canUndoLastCommit ? "git reset --soft HEAD~1" : "Requires an unpushed commit with a parent and no operation in progress." },
11103
+ () => runGitToolAction("undo", {
11104
+ url: "/api/git-undo/last-commit",
11105
+ body: { confirmed: true },
11106
+ confirm: [
11107
+ `Undo the last commit in ${data.root}?`,
11108
+ "",
11109
+ `Commit: ${last?.hash || ""} ${last?.subject || ""}`,
11110
+ "Command: git reset --soft HEAD~1 (the commit's changes stay staged)",
11111
+ "Restore afterwards with: git reset --soft ORIG_HEAD",
11112
+ ].join("\n"),
11113
+ success: "Undid the last commit; its changes remain staged.",
11114
+ successMessage: (response) => {
11115
+ const undone = response.data?.undoneCommit;
11116
+ const restore = response.data?.restoreCommand || "git reset --soft ORIG_HEAD";
11117
+ return `Undid commit ${undone?.hash || ""} "${undone?.subject || ""}"; its changes remain staged. Restore with: ${restore}`;
11118
+ },
11119
+ refreshChanges: true,
11120
+ }),
11121
+ ));
11122
+ row.append(gitToolsButton(
11123
+ "Amend last commit message",
11124
+ { disabled: busy || !data.canAmendMessage, title: data.canAmendMessage ? "git commit --amend -m <message>" : "Requires an unpushed commit and an empty staging area." },
11125
+ () => {
11126
+ const message = window.prompt("New commit message:", last?.subject || "");
11127
+ if (!message || !message.trim()) return;
11128
+ runGitToolAction("undo", {
11129
+ url: "/api/git-undo/amend-message",
11130
+ body: { confirmed: true, message: message.trim() },
11131
+ confirm: `Rewrite the last commit message?\n\nOld: ${last?.subject || ""}\nNew: ${message.trim()}`,
11132
+ success: "Amended the last commit message.",
11133
+ successMessage: (response) => {
11134
+ const previous = response.data?.previousCommit;
11135
+ const restore = response.data?.restoreCommand || "git reset --soft ORIG_HEAD";
11136
+ return `Amended the last commit message${previous?.hash ? ` (was ${previous.hash} "${previous.subject}")` : ""}. Restore with: ${restore}`;
11137
+ },
11138
+ });
11139
+ },
11140
+ ));
11141
+ body.append(row);
11142
+ const reflog = gitToolsState.cache.reflog;
11143
+ if (reflog?.entries?.length) {
11144
+ const details = make("details", "git-tools-item");
11145
+ details.append(make("summary", "git-tools-item-summary", `Recent HEAD history (${reflog.entries.length})`));
11146
+ details.append(make("pre", "git-conflict-preview", reflog.entries.map((entry) => `${entry.selector}\t${entry.hash}\t${entry.subject}`).join("\n")));
11147
+ body.append(details);
11148
+ 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."));
11149
+ }
11150
+ return body;
11151
+ }
11152
+
11153
+ function renderGitWorktreeTools(body, data, busy) {
11154
+ const worktrees = data.worktrees || [];
11155
+ for (const worktree of worktrees) {
11156
+ const item = make("div", "git-tools-row");
11157
+ const health = [
11158
+ worktree.isMainWorktree ? "main" : "",
11159
+ worktree.current ? "current" : "",
11160
+ worktree.detached ? "detached" : "",
11161
+ worktree.locked ? `locked${worktree.lockedReason ? `: ${worktree.lockedReason}` : ""}` : "",
11162
+ worktree.prunable ? "prunable" : "",
11163
+ ].filter(Boolean).join(" · ");
11164
+ item.append(
11165
+ make("span", "git-tools-item-ref", worktree.branch || "detached"),
11166
+ make("span", "git-tools-item-subject", `${normalizeDisplayPath(worktree.path)}${health ? ` · ${health}` : ""}`),
11167
+ );
11168
+ if (!worktree.isMainWorktree && !worktree.current) {
11169
+ const actions = gitFileActionButtons([
11170
+ {
11171
+ label: "Remove",
11172
+ className: "danger",
11173
+ title: `git worktree remove ${worktree.path}`,
11174
+ onClick: () => runGitToolAction("worktrees", {
11175
+ method: "DELETE",
11176
+ url: "/api/git-worktrees",
11177
+ body: { path: worktree.path, confirmed: true },
11178
+ confirm: [
11179
+ `Remove worktree ${worktree.path}?`,
11180
+ "",
11181
+ `Branch: ${worktree.branch || "detached"}`,
11182
+ "This deletes the checkout directory. Dirty worktrees and worktrees with open tabs are refused.",
11183
+ ].join("\n"),
11184
+ success: `Removed worktree ${worktree.path}.`,
11185
+ }),
11186
+ },
11187
+ ]);
11188
+ if (actions) item.append(actions);
11189
+ }
11190
+ body.append(item);
11191
+ }
11192
+ const row = make("div", "git-operation-actions");
11193
+ row.append(gitToolsButton("Prune stale worktrees…", { disabled: busy, title: "git worktree prune (with dry-run preview)" }, async () => {
11194
+ const tabId = gitChangesState.tabId || activeTabId;
11195
+ try {
11196
+ const preview = await api("/api/git-worktrees/prune", { tabId });
11197
+ const previewData = preview?.data || preview || {};
11198
+ const output = String(previewData.output || "").trim();
11199
+ const prunable = previewData.prunable || [];
11200
+ if (!output && !prunable.length) {
11201
+ window.alert("No stale worktree records to prune.");
11202
+ return;
11203
+ }
11204
+ const lines = prunable.map((item) => `${item.path}${item.reason ? ` (${item.reason})` : ""}`).join("\n");
11205
+ runGitToolAction("worktrees", {
11206
+ url: "/api/git-worktrees/prune",
11207
+ body: { confirmed: true },
11208
+ 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.`,
11209
+ success: "Pruned stale worktree records.",
11210
+ });
11211
+ } catch (error) {
11212
+ gitToolsState.notice.worktrees = error.message || String(error);
11213
+ renderGitChangesDialog();
11214
+ }
11215
+ }));
11216
+ body.append(row);
11217
+ return body;
11218
+ }
11219
+
11220
+ function renderGitSubmoduleTools(body, data, busy) {
11221
+ if (!data.hasSubmodules) {
11222
+ body.append(make("div", "git-changes-empty", "This repository has no submodules."));
11223
+ return body;
11224
+ }
11225
+ for (const submodule of data.submodules || []) {
11226
+ const item = make("div", "git-tools-row");
11227
+ item.append(
11228
+ make("span", "git-tools-item-ref", submodule.state),
11229
+ make("span", "git-tools-item-subject", `${submodule.path} · ${String(submodule.sha || "").slice(0, 10)}${submodule.describe ? ` · ${submodule.describe}` : ""}`),
11230
+ );
11231
+ const actions = gitFileActionButtons([
11232
+ {
11233
+ label: "Open tab",
11234
+ title: "Open a Web UI tab rooted at this submodule",
11235
+ onClick: () => {
11236
+ const root = String(data.root || "").replace(/\/+$/, "");
11237
+ closeGitChangesDialog();
11238
+ createTerminalTab(`${root}/${submodule.path}`).catch((error) => addEvent(error.message || String(error), "error"));
11239
+ },
11240
+ },
11241
+ { label: "Copy path", title: "Copy the submodule path", onClick: () => copyGitPathToClipboard(submodule.path) },
11242
+ ]);
11243
+ if (actions) item.append(actions);
11244
+ body.append(item);
11245
+ }
11246
+ const row = make("div", "git-operation-actions");
11247
+ row.append(gitToolsButton("Update / init recursively…", { disabled: busy, title: "git submodule update --init --recursive" }, () =>
11248
+ runGitToolAction("submodules", {
11249
+ url: "/api/git-submodules/update",
11250
+ body: { confirmed: true },
11251
+ confirm: "Run git submodule update --init --recursive?\n\nThis can check out new commits in every submodule and may take a while.",
11252
+ success: "Updated submodules recursively.",
11253
+ refreshChanges: true,
11254
+ })));
11255
+ body.append(row);
11256
+ return body;
11257
+ }
11258
+
11259
+ function renderGitTagTools(body, data, busy) {
11260
+ const tags = data.tags || [];
11261
+ if (!tags.length) body.append(make("div", "git-changes-empty", "No tags."));
11262
+ for (const tag of tags.slice(0, 15)) {
11263
+ const item = make("div", "git-tools-row");
11264
+ item.append(
11265
+ make("span", "git-tools-item-ref", tag.name),
11266
+ make("span", "git-tools-item-subject", [tag.annotated ? "annotated" : "lightweight", tag.target ? `@ ${tag.target}` : "", tag.atHead ? "at HEAD" : "", tag.date || ""].filter(Boolean).join(" · ")),
11267
+ );
11268
+ body.append(item);
11269
+ }
11270
+ const row = make("div", "git-operation-actions");
11271
+ row.append(gitToolsButton("Create annotated tag…", { disabled: busy, title: "git tag -a <name> -m <message> (never pushed automatically)" }, () => {
11272
+ const name = window.prompt("Tag name (annotated tag at HEAD):", "");
11273
+ if (!name || !name.trim()) return;
11274
+ const message = window.prompt("Tag message:", name.trim());
11275
+ if (message === null) return;
11276
+ runGitToolAction("tags", {
11277
+ url: "/api/git-tags/create",
11278
+ body: { confirmed: true, name: name.trim(), message: (message || name).trim() },
11279
+ confirm: `Create annotated tag ${name.trim()} at HEAD?\n\nTags are not pushed automatically; push explicitly with: git push origin ${name.trim()}`,
11280
+ success: `Created tag ${name.trim()}.`,
11281
+ });
11282
+ }));
11283
+ body.append(row);
11284
+ return body;
11285
+ }
11286
+
11287
+ function renderGitSigningTools(body, data) {
11288
+ body.append(make("div", "git-tools-note", `commit.gpgsign: ${data.commitSignRequired ? "true" : "false"} · gpg.format: ${data.gpgFormat} · user.signingkey: ${data.signingKey}`));
11289
+ 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})` : ""}`));
11290
+ 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."));
11291
+ for (const suggestion of data.suggestions || []) {
11292
+ const item = make("div", "git-tools-row");
11293
+ item.append(make("span", "git-tools-item-subject", suggestion.label), make("code", "git-tools-command", suggestion.command));
11294
+ const actions = gitFileActionButtons([
11295
+ { label: "Copy", title: "Copy this command", onClick: () => navigator.clipboard?.writeText(suggestion.command).catch(() => {}) },
11296
+ ]);
11297
+ if (actions) item.append(actions);
11298
+ body.append(item);
11299
+ }
11300
+ body.append(make("div", "git-tools-note", "Commands are copyable only; config is never rewritten automatically."));
11301
+ return body;
11302
+ }
11303
+
11304
+ function renderGitToolsSectionBody(key) {
11305
+ const body = make("div", "git-tools-body");
11306
+ const notice = gitToolsState.notice[key];
11307
+ if (notice) body.append(make("div", "git-changes-empty error", notice));
11308
+ const data = gitToolsState.cache[key];
11309
+ const busy = gitToolsState.busy.has(key) || gitToolsState.busy.has(`load:${key}`);
11310
+ if (!data) {
11311
+ if (!notice) body.append(make("div", "git-changes-empty", "Loading…"));
11312
+ return body;
11313
+ }
11314
+ switch (key) {
11315
+ case "stash":
11316
+ return renderGitStashTools(body, data, busy);
11317
+ case "undo":
11318
+ return renderGitUndoTools(body, data, busy);
11319
+ case "worktrees":
11320
+ return renderGitWorktreeTools(body, data, busy);
11321
+ case "submodules":
11322
+ return renderGitSubmoduleTools(body, data, busy);
11323
+ case "tags":
11324
+ return renderGitTagTools(body, data, busy);
11325
+ case "signing":
11326
+ return renderGitSigningTools(body, data);
11327
+ default:
11328
+ return body;
11329
+ }
11330
+ }
11331
+
11332
+ function renderGitToolsSection() {
11333
+ const wrapper = make("section", "git-tools");
11334
+ wrapper.append(make("div", "git-diff-section-heading git-tools-heading", "Git tools"));
11335
+ for (const section of GIT_TOOLS_SECTIONS) {
11336
+ const details = make("details", "git-tools-section");
11337
+ details.dataset.gitTools = section.key;
11338
+ details.open = gitToolsState.openSections.has(section.key);
11339
+ const summary = make("summary", "git-tools-summary");
11340
+ summary.append(make("span", "git-tools-title", section.title), make("span", "git-tools-detail", section.detail));
11341
+ details.append(summary);
11342
+ if (details.open) details.append(renderGitToolsSectionBody(section.key));
11343
+ details.addEventListener("toggle", () => {
11344
+ if (details.open) {
11345
+ if (gitToolsState.openSections.has(section.key)) return;
11346
+ gitToolsState.openSections.add(section.key);
11347
+ loadGitToolsSection(section.key);
11348
+ renderGitChangesDialog();
11349
+ } else {
11350
+ gitToolsState.openSections.delete(section.key);
11351
+ }
11352
+ });
11353
+ wrapper.append(details);
11354
+ }
11355
+ return wrapper;
11356
+ }
11357
+
11358
+ // Route the git+ chip to the tools section matching its leading indicator
11359
+ // (📦 stash, 🧩 submodules, 🔓 signing, 🏷 tag, 🌳 worktrees).
11360
+ function gitToolsSectionForExtraChip(value = "") {
11361
+ const text = String(value || "");
11362
+ if (text.includes("📦")) return "stash";
11363
+ if (text.includes("🧩")) return "submodules";
11364
+ if (text.includes("🔓")) return "signing";
11365
+ if (text.includes("🏷")) return "tags";
11366
+ if (text.includes("🌳")) return "worktrees";
11367
+ return "stash";
11368
+ }
11369
+
11370
+ function openGitToolsFromFooter(section = "stash") {
11371
+ openGitChangesDialog();
11372
+ gitToolsState.openSections.add(section);
11373
+ loadGitToolsSection(section);
11374
+ renderGitChangesDialog();
11375
+ }
11376
+
9551
11377
  function gitFooterFallbackMessage() {
9552
11378
  if (isOptionalFeatureDisabled("gitFooterStatus")) return "";
9553
11379
  const tabContext = activeTabContext();
@@ -10010,6 +11836,7 @@ function applyOptimisticGitFooterBranch(branch, tabContext = activeTabContext())
10010
11836
  generatedAt: Date.now(),
10011
11837
  main: payload.main,
10012
11838
  meta: payload.meta.map((chip) => chip.key === "git" ? { ...chip, value: nextBranch, title: `git branch: ${nextBranch}` } : chip),
11839
+ visibility: payload.visibility,
10013
11840
  };
10014
11841
  const nextRaw = JSON.stringify(nextPayload);
10015
11842
  statusEntries.set(GIT_FOOTER_WEBUI_STATUS_KEY, nextRaw);
@@ -10108,15 +11935,33 @@ function footerBranchAgentWarningLines(tabContext = activeTabContext()) {
10108
11935
  ];
10109
11936
  }
10110
11937
 
11938
+ function footerBranchDirtySummaryLines() {
11939
+ const changesChip = parseGitFooterWebuiPayload()?.meta?.find((chip) => chip.key === "changes");
11940
+ const files = Array.isArray(changesChip?.files) ? changesChip.files : [];
11941
+ if (!files.length) return [];
11942
+ const counts = {};
11943
+ for (const file of files) counts[file.kind] = (counts[file.kind] || 0) + 1;
11944
+ const parts = FOOTER_CHANGED_FILE_KIND_ORDER
11945
+ .filter((kind) => counts[kind])
11946
+ .map((kind) => `${counts[kind]} ${FOOTER_CHANGED_FILE_KIND_LABELS[kind]?.toLowerCase() || kind}`);
11947
+ const total = changesChip?.filesTruncated && changesChip?.filesTotal ? changesChip.filesTotal : files.length;
11948
+ return [
11949
+ `Dirty working tree: ${total} changed file${total === 1 ? "" : "s"} (${parts.join(", ")}).`,
11950
+ "Switching branches carries these changes along; consider a worktree instead.",
11951
+ ];
11952
+ }
11953
+
10111
11954
  function confirmFooterGitBranchAction(branch, { create = false, requireConfirm = false, tabContext = activeTabContext() } = {}) {
10112
11955
  const branchName = cleanStatusText(branch);
10113
11956
  const warningLines = footerBranchAgentWarningLines(tabContext);
10114
- if (!requireConfirm && warningLines.length === 0) return true;
11957
+ const dirtyLines = footerBranchDirtySummaryLines();
11958
+ if (!requireConfirm && warningLines.length === 0 && dirtyLines.length === 0) return true;
10115
11959
  const action = create ? "Create and switch to new git branch" : "Switch git branch";
10116
11960
  const message = [
10117
11961
  `${action}: ${branchName}?`,
10118
11962
  "",
10119
11963
  `Repository: ${footerBranchPickerState.root || currentGitFooterCacheCwd(tabContext.tabId) || "current tab"}`,
11964
+ ...dirtyLines,
10120
11965
  ...warningLines,
10121
11966
  "",
10122
11967
  "Continue?",
@@ -10500,26 +12345,94 @@ function renderFooterBranchOption(branch, state = footerBranchPickerState) {
10500
12345
  advanced.addEventListener("click", () => applyFooterGitBranch(branch.name));
10501
12346
  row.append(advanced);
10502
12347
  }
10503
- return row;
12348
+ return row;
12349
+ }
12350
+
12351
+ async function removeFooterGitWorktree(worktree, tabContext = activeTabContext()) {
12352
+ const tabId = tabContext.tabId || activeTabId;
12353
+ if (!window.confirm([
12354
+ `Remove worktree ${worktree.path}?`,
12355
+ "",
12356
+ `Branch: ${worktree.branch || "detached"}`,
12357
+ "Command: git worktree remove",
12358
+ "This deletes the checkout directory. Dirty worktrees and worktrees with open tabs are refused.",
12359
+ ].join("\n"))) return;
12360
+ footerBranchPickerState = { ...footerBranchPickerState, loading: true, error: "" };
12361
+ renderFooter();
12362
+ try {
12363
+ const response = await api("/api/git-worktrees", { method: "DELETE", body: { path: worktree.path, confirmed: true }, tabId });
12364
+ if (!response.ok) throw new Error(response.error || "Failed to remove the worktree");
12365
+ addEvent(`Removed worktree ${worktree.path}.`, "success");
12366
+ } catch (error) {
12367
+ addEvent(error.message || String(error), "error");
12368
+ }
12369
+ await loadFooterBranchPicker(tabContext).catch(() => {});
12370
+ }
12371
+
12372
+ async function pruneFooterGitWorktrees(tabContext = activeTabContext()) {
12373
+ const tabId = tabContext.tabId || activeTabId;
12374
+ try {
12375
+ const preview = await api("/api/git-worktrees/prune", { tabId });
12376
+ const previewData = preview?.data || {};
12377
+ const prunable = previewData.prunable || [];
12378
+ const output = String(previewData.output || "").trim();
12379
+ if (!prunable.length && !output) {
12380
+ addEvent("No stale worktree records to prune.", "info");
12381
+ return;
12382
+ }
12383
+ const lines = prunable.map((item) => `${item.path}${item.reason ? ` (${item.reason})` : ""}`).join("\n");
12384
+ 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;
12385
+ const response = await api("/api/git-worktrees/prune", { method: "POST", body: { confirmed: true }, tabId });
12386
+ if (!response.ok) throw new Error(response.error || "Failed to prune worktrees");
12387
+ addEvent("Pruned stale worktree records.", "success");
12388
+ } catch (error) {
12389
+ addEvent(error.message || String(error), "error");
12390
+ }
12391
+ await loadFooterBranchPicker(tabContext).catch(() => {});
10504
12392
  }
10505
12393
 
10506
12394
  function renderFooterWorktreeList(state = footerBranchPickerState) {
10507
- const worktrees = (state.worktrees || []).filter((item) => item.path && !item.prunable);
10508
- if (worktrees.length <= 1) return null;
12395
+ const allWorktrees = (state.worktrees || []).filter((item) => item.path);
12396
+ const worktrees = allWorktrees.filter((item) => !item.prunable);
12397
+ const prunableCount = allWorktrees.length - worktrees.length;
12398
+ if (worktrees.length <= 1 && prunableCount === 0) return null;
12399
+ const busy = state.loading || !!state.switching;
10509
12400
  const section = make("div", "footer-branch-worktree-section");
10510
12401
  section.append(make("div", "footer-branch-section-title", `Open worktrees (${worktrees.length})`));
10511
12402
  for (const worktree of worktrees.slice(0, 8)) {
10512
12403
  const selected = worktree.current || worktree.path === state.currentWorktreePath;
12404
+ const row = make("div", "footer-branch-option-row");
10513
12405
  const button = make("button", `footer-model-option footer-worktree-option${selected ? " active" : ""}`);
10514
12406
  button.type = "button";
10515
- button.disabled = selected || state.loading || !!state.switching;
12407
+ button.disabled = selected || busy;
10516
12408
  button.title = selected ? `Current worktree: ${worktree.path}` : `Open worktree: ${worktree.path}`;
12409
+ const health = [
12410
+ worktree.detached ? "detached" : "",
12411
+ worktree.locked ? `locked${worktree.lockedReason ? `: ${worktree.lockedReason}` : ""}` : "",
12412
+ ].filter(Boolean).join(" · ");
10517
12413
  button.append(
10518
12414
  make("span", "footer-model-option-main", worktree.branch || "detached"),
10519
- make("span", "footer-model-option-name", `${selected ? "current" : "open"} · ${normalizeDisplayPath(worktree.path)}`),
12415
+ make("span", "footer-model-option-name", `${selected ? "current" : "open"}${health ? ` · ${health}` : ""} · ${normalizeDisplayPath(worktree.path)}`),
10520
12416
  );
10521
12417
  if (!button.disabled) button.addEventListener("click", () => openFooterGitWorktree(worktree.path, { branchName: worktree.branch || "", skipConfirm: true }));
10522
- section.append(button);
12418
+ row.append(button);
12419
+ if (!selected && !worktree.isMainWorktree) {
12420
+ const remove = make("button", "footer-branch-advanced-action footer-worktree-remove", "Remove");
12421
+ remove.type = "button";
12422
+ remove.disabled = busy || worktree.locked;
12423
+ remove.title = worktree.locked ? `Worktree is locked${worktree.lockedReason ? `: ${worktree.lockedReason}` : ""}` : `git worktree remove ${worktree.path}`;
12424
+ remove.addEventListener("click", () => removeFooterGitWorktree(worktree));
12425
+ row.append(remove);
12426
+ }
12427
+ section.append(row);
12428
+ }
12429
+ if (prunableCount > 0) {
12430
+ const prune = make("button", "footer-branch-advanced-action footer-worktree-prune", `Prune ${prunableCount} stale worktree record${prunableCount === 1 ? "" : "s"}…`);
12431
+ prune.type = "button";
12432
+ prune.disabled = busy;
12433
+ prune.title = "git worktree prune (with dry-run preview)";
12434
+ prune.addEventListener("click", () => pruneFooterGitWorktrees());
12435
+ section.append(prune);
10523
12436
  }
10524
12437
  return section;
10525
12438
  }
@@ -11592,6 +13505,320 @@ function initializeClaudeUsage() {
11592
13505
  claudeUsageRenderTimer = setInterval(renderClaudeUsage, CLAUDE_USAGE_RENDER_TICK_MS);
11593
13506
  }
11594
13507
 
13508
+ function subagentTabsWithRunningAgents() {
13509
+ return (Array.isArray(latestSubagents?.tabs) ? latestSubagents.tabs : [])
13510
+ .filter((tab) => Number(tab?.agentCount || 0) > 0)
13511
+ .sort((a, b) => Number(a.tabIndex || 0) - Number(b.tabIndex || 0) || String(a.tabTitle || "").localeCompare(String(b.tabTitle || "")));
13512
+ }
13513
+
13514
+ function subagentSessionFileName(value) {
13515
+ return String(value || "").split(/[\\/]/).filter(Boolean).pop() || "";
13516
+ }
13517
+
13518
+ function subagentTabMeta(tab) {
13519
+ const sessionName = String(tab?.sessionName || "").trim();
13520
+ const title = String(tab?.tabTitle || "").trim();
13521
+ if (sessionName && sessionName !== title) return sessionName;
13522
+ return subagentSessionFileName(tab?.sessionFile) || normalizeDisplayPath(tab?.cwd || "") || "session";
13523
+ }
13524
+
13525
+ function subagentRunElapsed(run) {
13526
+ const startedAt = Number(run?.startedAt);
13527
+ return Number.isFinite(startedAt) ? formatDuration(Math.max(0, Date.now() - startedAt)) : "";
13528
+ }
13529
+
13530
+ function subagentOverlayOutputLines(data = subagentOverlayData) {
13531
+ const agent = data?.agent || subagentOverlaySelection?.agent || {};
13532
+ const output = (Array.isArray(agent.recentOutput) ? agent.recentOutput : [])
13533
+ .flatMap((line) => stripAnsi(String(line ?? "")).replace(/\r/g, "").split("\n"));
13534
+ if (output.length) return output;
13535
+ const tools = (Array.isArray(agent.recentTools) ? agent.recentTools : [])
13536
+ .map((entry) => `✓ ${entry.tool || "tool"}${entry.args ? ` ${entry.args}` : ""}`);
13537
+ if (agent.currentTool) tools.push(`▶ ${agent.currentTool}${agent.currentToolArgs ? ` ${agent.currentToolArgs}` : ""}`);
13538
+ return tools;
13539
+ }
13540
+
13541
+ function appendSubagentOutputWaitingIndicator(parent) {
13542
+ const row = make("div", "release-npm-line subagent-output-waiting");
13543
+ row.setAttribute("role", "status");
13544
+ row.setAttribute("aria-label", "Waiting for agent output");
13545
+ row.append(
13546
+ make("span", "subagent-output-waiting-dot", "."),
13547
+ make("span", "subagent-output-waiting-dot", "."),
13548
+ make("span", "subagent-output-waiting-dot", "."),
13549
+ );
13550
+ parent.append(row);
13551
+ }
13552
+
13553
+ function subagentOverlayStateFacts(data = subagentOverlayData) {
13554
+ const agent = data?.agent || subagentOverlaySelection?.agent || {};
13555
+ return [
13556
+ agent.status || "running",
13557
+ data?.mode || subagentOverlaySelection?.run?.mode,
13558
+ data?.source || subagentOverlaySelection?.run?.source,
13559
+ agent.nested ? "nested" : "",
13560
+ agent.currentTool ? `tool ${agent.currentTool}` : "",
13561
+ Number.isFinite(agent.turnCount) ? `${agent.turnCount} turns` : "",
13562
+ Number.isFinite(agent.toolCount) ? `${agent.toolCount} tools` : "",
13563
+ Number.isFinite(agent.tokens) ? `${Number(agent.tokens).toLocaleString()} tokens` : "",
13564
+ ].filter(Boolean);
13565
+ }
13566
+
13567
+ function subagentOverlayMeaningfulSignature() {
13568
+ return JSON.stringify({
13569
+ selection: subagentOverlaySelection ? {
13570
+ tabId: subagentOverlaySelection.tabId,
13571
+ runId: subagentOverlaySelection.runId,
13572
+ agentId: subagentOverlaySelection.agentId,
13573
+ finished: subagentOverlaySelection.finished === true,
13574
+ } : null,
13575
+ data: subagentOverlayData ? { ...subagentOverlayData, updatedAt: undefined } : null,
13576
+ error: subagentOverlayError,
13577
+ });
13578
+ }
13579
+
13580
+ function renderSubagentOverlayWidget() {
13581
+ const selection = subagentOverlaySelection;
13582
+ if (!selection || selection.tabId !== activeTabId) return null;
13583
+ const data = subagentOverlayData;
13584
+ const agent = data?.agent || selection.agent || {};
13585
+ const tab = tabs.find((item) => item.id === selection.tabId) || selection.tab;
13586
+ const running = !selection.finished && (agent.status === "running" || agent.status === "queued" || agent.status === "pending" || !agent.status);
13587
+ const lines = subagentOverlayOutputLines(data);
13588
+ const shownLines = lines.length ? lines : running && agent.currentTool ? [] : [running ? "Waiting for the first agent activity…" : "No recent output was captured."];
13589
+ const widget = make("section", `widget release-npm-widget app-runner-widget subagent-overlay-widget${running ? " app-runner-live-widget" : " app-runner-log-widget"}`);
13590
+ widget.setAttribute("aria-label", `Live output for subagent ${agent.name || "subagent"}`);
13591
+
13592
+ const header = make("div", "release-npm-header");
13593
+ const titleWrap = make("div", "release-npm-title-wrap");
13594
+ titleWrap.append(make("span", "release-npm-kicker", "subagent"), make("strong", "release-npm-title", agent.name || "subagent"));
13595
+ const meta = make("div", "release-npm-meta");
13596
+ for (const fact of subagentOverlayStateFacts(data)) meta.append(make("span", "release-npm-pill", fact));
13597
+ header.append(titleWrap, meta);
13598
+
13599
+ const streamHeader = releaseNpmStreamHeader(running ? "Live agent output" : "Agent output", shownLines.length, { live: running });
13600
+ const terminal = make("div", "release-npm-terminal subagent-overlay-terminal");
13601
+ terminal.setAttribute("role", "log");
13602
+ terminal.setAttribute("aria-live", running ? "polite" : "off");
13603
+ for (const line of shownLines) appendReleaseNpmTerminalLine(terminal, line);
13604
+ if (running && agent.currentTool) appendSubagentOutputWaitingIndicator(terminal);
13605
+
13606
+ const controls = make("div", "release-npm-controls subagent-overlay-output-controls");
13607
+ const actions = make("div", "app-runner-output-actions");
13608
+ const copyButton = appRunnerActionButton("Copy output", copySubagentOverlayOutput, "subagent-overlay-copy-action");
13609
+ copyButton.disabled = subagentOverlayOutputLines(data).length === 0;
13610
+ const refreshButton = appRunnerActionButton(subagentOverlayLoading ? "Refreshing…" : "Refresh", () => {
13611
+ refreshSubagentOverlay().finally(() => scheduleSubagentOverlayRefresh());
13612
+ }, "subagent-overlay-refresh-action");
13613
+ refreshButton.disabled = subagentOverlayLoading || selection.finished;
13614
+ actions.append(copyButton, refreshButton, appRunnerActionButton("Close", closeSubagentOverlay, "subagent-overlay-close-action"));
13615
+ const details = [
13616
+ `${tab?.title || `Terminal ${selection.tabIndex || "?"}`} · run ${selection.runId}`,
13617
+ agent.currentPath ? `path: ${agent.currentPath}` : "",
13618
+ agent.activityState ? `activity: ${agent.activityState}` : "",
13619
+ agent.error ? `status warning: ${agent.error}` : "",
13620
+ subagentOverlayError,
13621
+ ].filter(Boolean);
13622
+ controls.append(actions, make("span", `app-runner-output-meta${subagentOverlayError ? " warning" : ""}`, details.join(" · ")));
13623
+ const outputDetails = renderReleaseNpmOutputDetails(`subagent:${selection.tabId}:${selection.agentId}`, streamHeader, terminal, controls);
13624
+ widget.append(header, outputDetails);
13625
+ requestAnimationFrame(() => { if (outputDetails.open) terminal.scrollTop = terminal.scrollHeight; });
13626
+ return widget;
13627
+ }
13628
+
13629
+ function scheduleSubagentOverlayRefresh(delay = SUBAGENT_OVERLAY_REFRESH_MS) {
13630
+ clearTimeout(subagentOverlayRefreshTimer);
13631
+ if (!subagentOverlaySelection || subagentOverlaySelection.finished) return;
13632
+ subagentOverlayRefreshTimer = setTimeout(() => {
13633
+ refreshSubagentOverlay().finally(() => scheduleSubagentOverlayRefresh());
13634
+ }, delay);
13635
+ }
13636
+
13637
+ async function refreshSubagentOverlay() {
13638
+ const selection = subagentOverlaySelection;
13639
+ if (!selection || subagentOverlayLoading) return;
13640
+ const requestSerial = ++subagentOverlayRequestSerial;
13641
+ const previousSignature = subagentOverlayMeaningfulSignature();
13642
+ subagentOverlayLoading = true;
13643
+ try {
13644
+ const query = new URLSearchParams({ tab: selection.tabId, run: selection.runId, agent: selection.agentId });
13645
+ const response = await api(`/api/subagents/output?${query}`, { scoped: false });
13646
+ if (requestSerial !== subagentOverlayRequestSerial || subagentOverlaySelection !== selection) return;
13647
+ subagentOverlayData = response.data || null;
13648
+ subagentOverlayError = "";
13649
+ } catch (error) {
13650
+ if (requestSerial !== subagentOverlayRequestSerial || subagentOverlaySelection !== selection) return;
13651
+ if (error?.statusCode === 404) selection.finished = true;
13652
+ subagentOverlayError = error?.statusCode === 404
13653
+ ? "This subagent has finished or is no longer tracked. Showing the last captured output."
13654
+ : `Subagent output refresh failed: ${error.message || String(error)}`;
13655
+ } finally {
13656
+ if (requestSerial === subagentOverlayRequestSerial && subagentOverlaySelection === selection) {
13657
+ subagentOverlayLoading = false;
13658
+ if (selection.tabId === activeTabId && previousSignature !== subagentOverlayMeaningfulSignature()) renderWidgets();
13659
+ }
13660
+ }
13661
+ }
13662
+
13663
+ async function openSubagentOverlay(tab, run, agent) {
13664
+ if (!tab?.tabId || !run?.id || !agent?.id) return;
13665
+ try {
13666
+ if (activeTabId !== tab.tabId) await switchTab(tab.tabId);
13667
+ subagentOverlaySelection = {
13668
+ tabId: tab.tabId,
13669
+ tabIndex: tab.tabIndex,
13670
+ tab,
13671
+ run,
13672
+ agent,
13673
+ runId: run.id,
13674
+ agentId: agent.id,
13675
+ finished: false,
13676
+ };
13677
+ subagentOverlayData = null;
13678
+ subagentOverlayError = "";
13679
+ subagentOverlayRequestSerial += 1;
13680
+ renderWidgets();
13681
+ await refreshSubagentOverlay();
13682
+ scheduleSubagentOverlayRefresh();
13683
+ } catch (error) {
13684
+ addEvent(`could not open subagent output: ${error.message || String(error)}`, "error");
13685
+ }
13686
+ }
13687
+
13688
+ function closeSubagentOverlay() {
13689
+ clearTimeout(subagentOverlayRefreshTimer);
13690
+ subagentOverlayRefreshTimer = null;
13691
+ subagentOverlayRequestSerial += 1;
13692
+ subagentOverlaySelection = null;
13693
+ subagentOverlayData = null;
13694
+ subagentOverlayError = "";
13695
+ subagentOverlayLoading = false;
13696
+ renderWidgets();
13697
+ }
13698
+
13699
+ async function copySubagentOverlayOutput() {
13700
+ const text = subagentOverlayOutputLines().join("\n").trimEnd();
13701
+ if (!text) {
13702
+ addEvent("subagent output is empty", "warn");
13703
+ return;
13704
+ }
13705
+ try {
13706
+ await copyText(text);
13707
+ addEvent("copied subagent output", "info");
13708
+ } catch (error) {
13709
+ addEvent(`subagent output copy failed: ${error.message || String(error)}`, "warn");
13710
+ }
13711
+ }
13712
+
13713
+ function renderSubagentAgent(tab, run, agent) {
13714
+ const row = make("button", `subagent-agent-row${agent?.nested ? " nested" : ""}`);
13715
+ row.type = "button";
13716
+ const dot = make("span", "subagent-running-dot");
13717
+ dot.setAttribute("aria-hidden", "true");
13718
+ const content = make("div", "subagent-agent-content");
13719
+ content.append(make("strong", "subagent-agent-name", agent?.name || "subagent"));
13720
+ const elapsed = subagentRunElapsed(run);
13721
+ const facts = [
13722
+ agent?.nested ? "nested" : "",
13723
+ run?.mode && run.mode !== "single" ? run.mode : "",
13724
+ run?.source === "foreground" ? "foreground" : "async",
13725
+ agent?.currentTool ? `tool: ${agent.currentTool}` : "",
13726
+ elapsed ? `running ${elapsed}` : "",
13727
+ ].filter(Boolean);
13728
+ content.append(make("span", "subagent-agent-meta", facts.join(" · ")));
13729
+ row.append(dot, content);
13730
+ row.title = `${agent?.name || "subagent"} · ${facts.join(" · ")} · run ${run?.id || "unknown"} · open live output`;
13731
+ row.setAttribute("aria-label", `Open live output for ${agent?.name || "subagent"} in ${tab?.tabTitle || `Terminal ${tab?.tabIndex || "?"}`}`);
13732
+ row.addEventListener("click", () => openSubagentOverlay(tab, run, agent));
13733
+ return row;
13734
+ }
13735
+
13736
+ function renderSubagentTabGroup(tab) {
13737
+ const group = make("section", `subagent-tab-group${tab.tabId === activeTabId ? " active" : ""}`);
13738
+ const header = make("button", "subagent-tab-header");
13739
+ header.type = "button";
13740
+ header.setAttribute("aria-label", `Open ${tab.tabTitle || `Terminal ${tab.tabIndex || ""}`}`);
13741
+ const title = make("span", "subagent-tab-title");
13742
+ title.append(
13743
+ make("strong", undefined, tab.tabTitle || `Terminal ${tab.tabIndex || "?"}`),
13744
+ make("span", "subagent-tab-session", `Terminal ${tab.tabIndex || "?"} · ${subagentTabMeta(tab)}`),
13745
+ );
13746
+ header.append(title, make("span", "subagent-tab-count", String(tab.agentCount || 0)));
13747
+ header.addEventListener("click", () => switchTab(tab.tabId));
13748
+ group.append(header);
13749
+
13750
+ const list = make("div", "subagent-agent-list");
13751
+ const runs = (Array.isArray(tab.runs) ? tab.runs : [])
13752
+ .slice()
13753
+ .sort((a, b) => Number(a.startedAt || 0) - Number(b.startedAt || 0) || String(a.id || "").localeCompare(String(b.id || "")));
13754
+ for (const run of runs) {
13755
+ const agents = (Array.isArray(run.agents) ? run.agents : [])
13756
+ .filter((agent) => agent?.status === "running")
13757
+ .sort((a, b) => Number(a.index || 0) - Number(b.index || 0) || String(a.name || "").localeCompare(String(b.name || "")));
13758
+ for (const agent of agents) list.append(renderSubagentAgent(tab, run, agent));
13759
+ }
13760
+ group.append(list);
13761
+ return group;
13762
+ }
13763
+
13764
+ function renderSubagents() {
13765
+ const box = elements.subagentsBox;
13766
+ if (!box) return;
13767
+ const activeTabs = subagentTabsWithRunningAgents();
13768
+ const totalAgents = activeTabs.reduce((count, tab) => count + Number(tab.agentCount || 0), 0);
13769
+ if (elements.subagentCountBadge) {
13770
+ elements.subagentCountBadge.textContent = String(totalAgents);
13771
+ elements.subagentCountBadge.hidden = totalAgents === 0;
13772
+ }
13773
+ if (elements.subagentsStatus) {
13774
+ elements.subagentsStatus.textContent = totalAgents > 0
13775
+ ? `${totalAgents} running across ${activeTabs.length} ${activeTabs.length === 1 ? "terminal" : "terminals"}`
13776
+ : subagentsLoading && !latestSubagents
13777
+ ? "Checking running subagents…"
13778
+ : "No running subagents.";
13779
+ }
13780
+
13781
+ box.replaceChildren();
13782
+ box.classList.toggle("muted", totalAgents === 0);
13783
+ box.classList.toggle("has-items", totalAgents > 0);
13784
+ if (totalAgents === 0) {
13785
+ box.append(make("div", "subagents-empty", subagentsError ? `Subagent status unavailable: ${subagentsError.message || subagentsError}` : "Running subagents will appear here, grouped by terminal and session."));
13786
+ return;
13787
+ }
13788
+ for (const tab of activeTabs) box.append(renderSubagentTabGroup(tab));
13789
+ if (subagentsError) box.append(make("div", "subagents-stale muted", `Latest refresh failed: ${subagentsError.message || subagentsError}`));
13790
+ }
13791
+
13792
+ async function refreshSubagents() {
13793
+ if (subagentsLoading) return;
13794
+ subagentsLoading = true;
13795
+ renderSubagents();
13796
+ try {
13797
+ const response = await api("/api/subagents", { scoped: false });
13798
+ latestSubagents = response.data || null;
13799
+ subagentsError = null;
13800
+ } catch (error) {
13801
+ subagentsError = error;
13802
+ } finally {
13803
+ subagentsLoading = false;
13804
+ renderSubagents();
13805
+ }
13806
+ }
13807
+
13808
+ function scheduleRefreshSubagents(delay) {
13809
+ clearTimeout(refreshSubagentsTimer);
13810
+ const totalAgents = Number(latestSubagents?.totalAgents || 0);
13811
+ const nextDelay = delay ?? (document.visibilityState === "hidden" ? SUBAGENTS_HIDDEN_REFRESH_MS : totalAgents > 0 ? SUBAGENTS_ACTIVE_REFRESH_MS : SUBAGENTS_IDLE_REFRESH_MS);
13812
+ refreshSubagentsTimer = setTimeout(() => {
13813
+ refreshSubagents().finally(() => scheduleRefreshSubagents());
13814
+ }, nextDelay);
13815
+ }
13816
+
13817
+ function initializeSubagents() {
13818
+ renderSubagents();
13819
+ refreshSubagents().finally(() => scheduleRefreshSubagents());
13820
+ }
13821
+
11595
13822
  function renderStatus() {
11596
13823
  if (deferUiRenderDuringPointerActivation("status", renderStatus)) return;
11597
13824
  const state = currentState;
@@ -14097,6 +16324,8 @@ function renderWidgets() {
14097
16324
  if (workflowSubprocessWidget) elements.widgetArea.append(workflowSubprocessWidget);
14098
16325
  const appRunnerWidget = renderAppRunnerWidget();
14099
16326
  if (appRunnerWidget) elements.widgetArea.append(appRunnerWidget);
16327
+ const subagentWidget = renderSubagentOverlayWidget();
16328
+ if (subagentWidget) elements.widgetArea.append(subagentWidget);
14100
16329
  const btwWidget = renderBtwOutputWidget();
14101
16330
  if (btwWidget) elements.widgetArea.append(btwWidget);
14102
16331
 
@@ -14649,7 +16878,7 @@ function gitWorkflowTitle() {
14649
16878
  case "remoteAdding": return "Adding origin remote";
14650
16879
  case "initialPush": return "Push main upstream";
14651
16880
  case "initialPushing": return "Pushing main";
14652
- case "add": return "Stage all changes";
16881
+ case "add": return (gitWorkflow.preferences || gitWorkflowPreferences)?.stagingPolicy === "all" ? "Stage all changes" : "Review staged changes";
14653
16882
  case "generate": return "Generate staged commit message";
14654
16883
  case "generating": return "Waiting for /git-staged-msg";
14655
16884
  case "message": return gitWorkflow.prMode ? "Choose PR branch commit message" : "Choose commit message";
@@ -14686,7 +16915,9 @@ function gitWorkflowHint() {
14686
16915
  case "remoteAdding": return "Adding the GitHub origin remote.";
14687
16916
  case "initialPush": return "Step 7: run git push -u origin main.";
14688
16917
  case "initialPushing": return "Pushing main upstream. Authentication must already be available to git.";
14689
- case "add": return "Step 1: run git add . in the current Pi working directory.";
16918
+ case "add": return (gitWorkflow.preferences || gitWorkflowPreferences)?.stagingPolicy === "all"
16919
+ ? "Step 1: explicitly stage all changes with git add ."
16920
+ : "Step 1: review changes, stage only intended files, then accept the current staged set.";
14690
16921
  case "generate": return "Step 2: run /git-staged-msg, or type a commit message and use Commit input.";
14691
16922
  case "generating": return "Pi is generating dev/COMMIT/staged-commit-short.txt and staged-commit-long.txt.";
14692
16923
  case "message": return gitWorkflow.prMode ? `Worktree branch ${gitWorkflow.prBranch || "created"}: choose short, long, or typed input before opening a PR.` : "Step 3/4: preview the native g-msg output, type a commit message if needed, commit here, or create a PR branch worktree first.";
@@ -14800,8 +17031,17 @@ function renderGitWorkflow() {
14800
17031
  return;
14801
17032
  }
14802
17033
 
17034
+ const preferences = gitWorkflow.preferences || gitWorkflowPreferences || {};
14803
17035
  if (gitWorkflow.step === "add") {
14804
- addGitWorkflowAction("Run git add .", () => runGitAdd(), "primary", false);
17036
+ if (preferences.stagingPolicy === "all") {
17037
+ addGitWorkflowAction("Run git add .", () => runGitAdd(), "primary", false);
17038
+ } else if (preferences.stagingPolicy === "preserve") {
17039
+ addGitWorkflowAction("Use current staged set", () => acceptCurrentGitStaging(), "primary", false);
17040
+ addGitWorkflowAction("Review/select changes", () => openGitChangesDialog(), "", false);
17041
+ } else {
17042
+ addGitWorkflowAction("Review/select changes", () => openGitChangesDialog(), "primary", false);
17043
+ addGitWorkflowAction("Use current staged set", () => acceptCurrentGitStaging(), "", false);
17044
+ }
14805
17045
  } else if (gitWorkflow.step === "generate") {
14806
17046
  const commitInputButton = renderGitWorkflowManualCommitInput({ appendCommitButton: false });
14807
17047
  addGitWorkflowAction("Run /git-staged-msg", () => runGitMessagePrompt(), "primary", false);
@@ -14810,13 +17050,16 @@ function renderGitWorkflow() {
14810
17050
  } else if (gitWorkflow.step === "generating") {
14811
17051
  addGitWorkflowAction("Refresh message preview", () => loadGitWorkflowMessage({ requireFresh: true }), "", false);
14812
17052
  } else if (gitWorkflow.step === "message") {
17053
+ const deliveryMode = preferences.deliveryMode || "ask";
17054
+ const preferredVariant = preferences.commit?.defaultVariant || "short";
14813
17055
  if (!gitWorkflow.prMode) {
14814
- addGitWorkflowAction("Create PR worktree", () => createGitPrBranch(), "primary", false, GIT_WORKFLOW_CREATE_PR_TOOLTIP);
17056
+ addGitWorkflowAction("Create PR worktree", () => createGitPrBranch(), deliveryMode === "pr-worktree" ? "primary" : "", false, GIT_WORKFLOW_CREATE_PR_TOOLTIP);
14815
17057
  addGitWorkflowAction("Manual worktree", () => createGitPrBranchManually(), "", false, GIT_WORKFLOW_MANUAL_BRANCH_TOOLTIP);
14816
17058
  }
14817
17059
  const commitInputButton = renderGitWorkflowManualCommitInput({ appendCommitButton: false });
14818
- addGitWorkflowAction("Commit short", () => commitGitWorkflow("short"), gitWorkflow.prMode ? "primary" : "", false);
14819
- addGitWorkflowAction("Commit long", () => commitGitWorkflow("long"), gitWorkflow.prMode ? "primary" : "", false);
17060
+ const highlightCommit = gitWorkflow.prMode || deliveryMode !== "pr-worktree";
17061
+ addGitWorkflowAction(`Commit short${preferredVariant === "short" ? " (default)" : ""}`, () => commitGitWorkflow("short"), highlightCommit && preferredVariant === "short" ? "primary" : "", false);
17062
+ addGitWorkflowAction(`Commit long${preferredVariant === "long" ? " (default)" : ""}`, () => commitGitWorkflow("long"), highlightCommit && preferredVariant === "long" ? "primary" : "", false);
14820
17063
  addGitWorkflowAction("Regenerate", () => runGitMessagePrompt(), "", false);
14821
17064
  elements.gitWorkflowActions.append(commitInputButton);
14822
17065
  } else if (gitWorkflow.step === "branchNaming") {
@@ -14875,7 +17118,18 @@ function failGitWorkflow(error, step, { tabId = activeTabId } = {}) {
14875
17118
  }, { tabId });
14876
17119
  }
14877
17120
 
14878
- function startGitWorkflow(tabId = activeTabId) {
17121
+ function gitWorkflowStagingReadyMessage(preferences) {
17122
+ switch (preferences?.stagingPolicy) {
17123
+ case "preserve":
17124
+ return "Using the repository's current staged set. Review it before generating a message.";
17125
+ case "all":
17126
+ return "Ready to stage all working-tree changes with git add .";
17127
+ default:
17128
+ return "Review changes and stage only the files intended for this commit, then continue with the current staged set.";
17129
+ }
17130
+ }
17131
+
17132
+ async function startGitWorkflow(tabId = activeTabId, { skipSetup = false } = {}) {
14879
17133
  if (!tabId) return;
14880
17134
  if (!isOptionalFeatureEnabled("gitWorkflow")) {
14881
17135
  const tabContext = activeTabContext(tabId);
@@ -14885,8 +17139,29 @@ function startGitWorkflow(tabId = activeTabId) {
14885
17139
  });
14886
17140
  return;
14887
17141
  }
17142
+
17143
+ let setupData;
17144
+ try {
17145
+ const response = await api("/api/git-workflow/preferences", { tabId });
17146
+ setupData = response.data || {};
17147
+ gitWorkflowPreferences = setupData.preferences || null;
17148
+ } catch (error) {
17149
+ addEvent(`guided Git setup could not be loaded: ${error.message || String(error)}`, "error");
17150
+ return;
17151
+ }
17152
+ if (!setupData.configured) {
17153
+ if (skipSetup) {
17154
+ addEvent("Guided Git setup is incomplete.", "warn");
17155
+ return;
17156
+ }
17157
+ addEvent("Complete Guided Git Setup before starting the workflow.", "info");
17158
+ await openNativeGitWorkflowSetupDialog({ onSaved: () => startGitWorkflow(tabId, { skipSetup: true }) });
17159
+ return;
17160
+ }
17161
+
14888
17162
  const workflow = gitWorkflowForTab(tabId);
14889
17163
  if (workflow.active && !["done", "cancelled", "error"].includes(workflow.step) && !confirm("Restart the active git workflow?")) return;
17164
+ const preferences = setupData.preferences;
14890
17165
  workflow.runId += 1;
14891
17166
  setGitWorkflow({
14892
17167
  active: true,
@@ -14894,7 +17169,7 @@ function startGitWorkflow(tabId = activeTabId) {
14894
17169
  step: "add",
14895
17170
  process: "stage",
14896
17171
  busy: false,
14897
- output: "Ready to stage all changes with git add .\n\nNative mode is used for g-msg/g-short/g-long: dev/COMMIT message files are read directly and git commit is run without fish. In the Message stage you can also type a commit message and use Commit input. After the message is generated, use Create PR worktree to open a branch worktree before committing.",
17172
+ output: `${gitWorkflowStagingReadyMessage(preferences)}\n\nGit text will use ${preferences.generation.provider}/${preferences.generation.modelId} at ${preferences.generation.thinkingLevel} effort. The active tab model is restored after generation.`,
14898
17173
  error: "",
14899
17174
  githubUsername: "",
14900
17175
  repoName: "",
@@ -14914,6 +17189,8 @@ function startGitWorkflow(tabId = activeTabId) {
14914
17189
  prBranch: "",
14915
17190
  pr: null,
14916
17191
  prRequestedAt: 0,
17192
+ preferences,
17193
+ verificationConfirmed: false,
14917
17194
  }, { tabId });
14918
17195
  }
14919
17196
 
@@ -15247,6 +17524,31 @@ async function runGitAdd(tabId = gitWorkflowActionTabId()) {
15247
17524
  }
15248
17525
  }
15249
17526
 
17527
+ async function acceptCurrentGitStaging(tabId = gitWorkflowActionTabId()) {
17528
+ const tabContext = activeTabContext(tabId);
17529
+ const workflow = gitWorkflowForTab(tabId, { create: false });
17530
+ if (!workflow) return;
17531
+ const runId = workflow.runId;
17532
+ setGitWorkflow({ step: "add", busy: true, error: "", output: "Checking the current staged set…" }, { tabId });
17533
+ try {
17534
+ const response = await api("/api/git-changes", { tabId });
17535
+ const staged = Number(response.data?.summary?.staged || 0);
17536
+ if (staged <= 0) throw new Error("No staged files are available. Use Review/select changes to stage the intended files first.");
17537
+ setGitWorkflow({
17538
+ step: "generate",
17539
+ process: "message",
17540
+ busy: false,
17541
+ ...resetGitWorkflowManualCommitDefaultPatch(),
17542
+ ...gitWorkflowActionDonePatch(workflow, "stage"),
17543
+ output: `Using the current staged set (${staged} file${staged === 1 ? "" : "s"}). Review the staged diff, then generate or type a commit message.`,
17544
+ }, { tabId });
17545
+ loadGitWorkflowDefaultCommitMessage({ runId, tabId });
17546
+ if (isCurrentTabContext(tabContext)) scheduleRefreshFooter();
17547
+ } catch (error) {
17548
+ if (isCurrentGitWorkflowRun(runId, tabId)) failGitWorkflow(error, "add", { tabId });
17549
+ }
17550
+ }
17551
+
15250
17552
  async function loadGitWorkflowDefaultCommitMessage({ runId, tabId = activeTabId } = {}) {
15251
17553
  const workflow = gitWorkflowForTab(tabId, { create: false });
15252
17554
  const expectedRunId = runId ?? workflow?.runId;
@@ -15298,9 +17600,9 @@ async function runGitMessagePrompt(tabId = gitWorkflowActionTabId()) {
15298
17600
  }, { tabId });
15299
17601
  if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending /git-staged-msg to Pi…");
15300
17602
  try {
15301
- await api("/api/prompt", { method: "POST", body: { message: "/git-staged-msg" }, tabId });
15302
- if (!isCurrentGitWorkflowRun(runId, tabId)) return;
15303
- appendGitWorkflowOutput("/git-staged-msg accepted. Waiting for agent_end, then the message files will be loaded.", { tabId });
17603
+ const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "commit" }, runId, tabId });
17604
+ if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
17605
+ appendGitWorkflowOutput(`/git-staged-msg accepted with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for agent_end, then the message files will be loaded.`, { tabId });
15304
17606
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
15305
17607
  setTimeout(() => {
15306
17608
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
@@ -15394,9 +17696,9 @@ async function runGitBranchNamePrompt(tabId = gitWorkflowActionTabId()) {
15394
17696
  }, { tabId });
15395
17697
  if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending branch-name request to Pi…");
15396
17698
  try {
15397
- await api("/api/prompt", { method: "POST", body: { message: gitBranchNamePromptMessage() }, tabId });
15398
- if (!isCurrentGitWorkflowRun(runId, tabId)) return;
15399
- appendGitWorkflowOutput("Branch-name request accepted. Waiting for agent_end, then the branch name will be loaded.", { tabId });
17699
+ const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "branch" }, runId, tabId });
17700
+ if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
17701
+ appendGitWorkflowOutput(`Branch-name request accepted with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for agent_end, then the branch name will be loaded.`, { tabId });
15400
17702
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
15401
17703
  setTimeout(() => {
15402
17704
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
@@ -15520,6 +17822,8 @@ async function createGitPrBranchWithSuggestion(suggestion, tabId = gitWorkflowAc
15520
17822
  prBranch: prBranch || branch,
15521
17823
  pr: null,
15522
17824
  prRequestedAt: 0,
17825
+ preferences: sourceWorkflow.preferences || gitWorkflowPreferences,
17826
+ verificationConfirmed: false,
15523
17827
  };
15524
17828
  if (targetTabId !== tabId) {
15525
17829
  setGitWorkflow({ step: "message", prMode: false, prBranch: "", branchName: prBranch || branch, busy: false, output: `${formatCommitMessagePreview(sourceWorkflow.message)}\n\nOpened PR branch worktree ${prBranch || branch} in ${result.tab?.title || "a new tab"}. Continue the commit and PR flow there; this checkout stayed on its current branch.` }, { tabId });
@@ -15542,6 +17846,18 @@ async function commitGitWorkflow(variant, tabId = gitWorkflowActionTabId()) {
15542
17846
  const runId = workflow.runId;
15543
17847
  const failureStep = variant === "input" && workflow.step === "generate" ? "generate" : "message";
15544
17848
  const inputMessage = variant === "input" ? gitWorkflowManualCommitInputMessage(workflow) : "";
17849
+ if (workflow.preferences?.verificationPolicy === "ask" && !workflow.verificationConfirmed) {
17850
+ const proceed = window.confirm([
17851
+ "Pre-commit verification reminder",
17852
+ "",
17853
+ "Review the staged diff and any relevant test, lint, or build results before committing.",
17854
+ "Git hooks and signing configuration will still run normally.",
17855
+ "",
17856
+ "Continue with this commit?",
17857
+ ].join("\n"));
17858
+ if (!proceed) return;
17859
+ workflow.verificationConfirmed = true;
17860
+ }
15545
17861
  if (variant === "input" && !inputMessage) {
15546
17862
  failGitWorkflow(new Error("Type a commit message, or stage exactly one created/updated/deleted file to use the default."), failureStep, { tabId });
15547
17863
  return;
@@ -15567,6 +17883,7 @@ async function pushGitWorkflow(tabId = gitWorkflowActionTabId()) {
15567
17883
  const tabContext = activeTabContext(tabId);
15568
17884
  const workflow = gitWorkflowForTab(tabId, { create: false });
15569
17885
  if (!workflow) return;
17886
+ if (!window.confirm("Push the committed changes to the configured upstream?\n\nGuided Git never force-pushes automatically.")) return;
15570
17887
  const runId = workflow.runId;
15571
17888
  setGitWorkflow({ step: "pushing", busy: true, error: "", output: "Running git push…" }, { tabId });
15572
17889
  try {
@@ -15604,9 +17921,9 @@ async function runGitPrPrompt(tabId = gitWorkflowActionTabId(), { prefixOutput =
15604
17921
  }, { tabId });
15605
17922
  if (isCurrentTabContext(tabContext)) setRunIndicatorActivity("Sending /pr to Pi…");
15606
17923
  try {
15607
- await api("/api/prompt", { method: "POST", body: { message: "/pr" }, tabId });
15608
- if (!isCurrentGitWorkflowRun(runId, tabId)) return;
15609
- appendGitWorkflowOutput("/pr accepted. Waiting for agent_end, then the PR description will be loaded.", { tabId });
17924
+ const generation = await gitWorkflowRequest("/api/git-workflow/generate", { body: { kind: "pr" }, runId, tabId });
17925
+ if (!generation || !isCurrentGitWorkflowRun(runId, tabId)) return;
17926
+ appendGitWorkflowOutput(`/pr accepted with ${generation.generation.provider}/${generation.generation.modelId} at ${generation.generation.thinkingLevel} effort. Waiting for agent_end, then the PR description will be loaded.`, { tabId });
15610
17927
  if (isCurrentTabContext(tabContext)) scheduleRefreshState(120, tabContext);
15611
17928
  setTimeout(() => {
15612
17929
  const currentWorkflow = gitWorkflowForTab(tabId, { create: false });
@@ -15657,8 +17974,9 @@ async function pushAndCreatePrGitWorkflow(tabId = gitWorkflowActionTabId()) {
15657
17974
  const tabContext = activeTabContext(tabId);
15658
17975
  const workflow = gitWorkflowForTab(tabId, { create: false });
15659
17976
  if (!workflow) return;
15660
- const runId = workflow.runId;
15661
17977
  const branch = workflow.prBranch || "current branch";
17978
+ if (!window.confirm(`Push ${branch} and continue to generated PR review?\n\nThe pull request is still created only after a second explicit review/confirmation.`)) return;
17979
+ const runId = workflow.runId;
15662
17980
  setGitWorkflow({ step: "pushing", busy: true, error: "", output: `Pushing PR branch ${branch}…` }, { tabId });
15663
17981
  try {
15664
17982
  const result = await gitWorkflowRequest("/api/git-workflow/push", { body: { setUpstream: true, branch: workflow.prBranch }, runId, tabId });
@@ -16232,14 +18550,101 @@ function appendText(parent, text, className = "text-block") {
16232
18550
  return block;
16233
18551
  }
16234
18552
 
18553
+ function markdownFilePathFromHref(url) {
18554
+ const href = String(url || "").trim();
18555
+ if (!href || href.startsWith("#") || /[\u0000-\u001f\u007f]/.test(href)) return "";
18556
+ if (/^(?:https?:|mailto:)/i.test(href)) return "";
18557
+ if (/^file:/i.test(href)) {
18558
+ try {
18559
+ const parsed = new URL(href);
18560
+ if (parsed.protocol !== "file:" || (parsed.hostname && parsed.hostname.toLowerCase() !== "localhost")) return "";
18561
+ let pathname = decodeURIComponent(parsed.pathname || "");
18562
+ if (/^\/[A-Za-z]:\//.test(pathname)) pathname = pathname.slice(1);
18563
+ return pathname.replace(/\\/g, "/");
18564
+ } catch {
18565
+ return "";
18566
+ }
18567
+ }
18568
+ if (/^[A-Za-z][A-Za-z\d+.-]*:/.test(href) && !/^[A-Za-z]:[\\/]/.test(href)) return "";
18569
+ if (/^(?:\/\/|\\\\)/.test(href)) return "";
18570
+ const pathText = href.replace(/[?#].*$/, "");
18571
+ try {
18572
+ return decodeURIComponent(pathText).replace(/\\/g, "/");
18573
+ } catch {
18574
+ return pathText.replace(/\\/g, "/");
18575
+ }
18576
+ }
18577
+
16235
18578
  function safeMarkdownLinkHref(url) {
16236
18579
  const href = String(url || "").trim();
16237
18580
  if (!href || /[\u0000-\u001f\u007f]/.test(href)) return "";
16238
18581
  if (/^(?:https?:|mailto:)/i.test(href)) return href;
16239
- if (/^(?:#|\/(?!\/)|\.\/|\.\.\/)/.test(href)) return href;
18582
+ if (href.startsWith("#") || markdownFilePathFromHref(href)) return href;
16240
18583
  return "";
16241
18584
  }
16242
18585
 
18586
+ function normalizeMarkdownWorkspacePath(value) {
18587
+ const parts = [];
18588
+ for (const part of String(value || "").replace(/\\/g, "/").split("/")) {
18589
+ if (!part || part === ".") continue;
18590
+ if (part === "..") {
18591
+ if (!parts.length) return "";
18592
+ parts.pop();
18593
+ continue;
18594
+ }
18595
+ parts.push(part);
18596
+ }
18597
+ return parts.join("/");
18598
+ }
18599
+
18600
+ function markdownWorkspaceFilePath(url, cwd = "", basePath = "") {
18601
+ let target = markdownFilePathFromHref(url);
18602
+ if (!target) return "";
18603
+ const absoluteTarget = target.startsWith("/") || /^[A-Za-z]:\//.test(target);
18604
+ if (absoluteTarget) {
18605
+ const normalizedCwd = String(cwd || "").trim().replace(/\\/g, "/");
18606
+ const workspaceRoot = normalizedCwd.replace(/\/+$/, "") || (normalizedCwd.startsWith("/") ? "/" : "");
18607
+ if (!workspaceRoot) return "";
18608
+ const windowsPath = /^[A-Za-z]:\//.test(target) && /^[A-Za-z]:(?:\/|$)/.test(workspaceRoot);
18609
+ const comparableTarget = windowsPath ? target.toLowerCase() : target;
18610
+ const comparableRoot = windowsPath ? workspaceRoot.toLowerCase() : workspaceRoot;
18611
+ const prefix = comparableRoot === "/" ? "/" : `${comparableRoot}/`;
18612
+ if (!comparableTarget.startsWith(prefix)) return "";
18613
+ target = target.slice(prefix.length);
18614
+ } else if (basePath) {
18615
+ target = `${basePath}/${target}`;
18616
+ }
18617
+ return normalizeMarkdownWorkspacePath(target);
18618
+ }
18619
+
18620
+ function configureMarkdownLink(link, href) {
18621
+ const filePath = markdownFilePathFromHref(href);
18622
+ if (!filePath) {
18623
+ link.href = href;
18624
+ if (/^https?:/i.test(href)) {
18625
+ link.target = "_blank";
18626
+ link.rel = "noopener noreferrer";
18627
+ }
18628
+ return;
18629
+ }
18630
+ link.href = "#";
18631
+ link.classList.add("markdown-file-link");
18632
+ link.dataset.markdownFileHref = href;
18633
+ link.title = `Open ${filePath} in the WebUI file viewer`;
18634
+ link.addEventListener("click", (event) => {
18635
+ event.preventDefault();
18636
+ const cwd = latestWorkspace?.cwd || activeTab()?.cwd || "";
18637
+ const basePath = link.closest?.(".file-viewer-preview") && activeFileViewer ? fileParentPath(activeFileViewer.path) : "";
18638
+ const workspacePath = markdownWorkspaceFilePath(href, cwd, basePath);
18639
+ if (!workspacePath) {
18640
+ addEvent(`Cannot open Markdown link outside this tab's working directory: ${filePath}`, "error");
18641
+ return;
18642
+ }
18643
+ setSidePanelCollapsed(false);
18644
+ openFileInViewer(workspacePath).catch((error) => addEvent(error.message || String(error), "error"));
18645
+ });
18646
+ }
18647
+
16243
18648
  function appendInlineMarkdown(parent, text, depth = 0) {
16244
18649
  const value = String(text || "");
16245
18650
  if (!value) return;
@@ -16270,11 +18675,7 @@ function appendInlineMarkdown(parent, text, depth = 0) {
16270
18675
  const href = safeMarkdownLinkHref(value.slice(labelEnd + 2, linkEnd));
16271
18676
  if (href) {
16272
18677
  const link = make("a");
16273
- link.href = href;
16274
- if (/^https?:/i.test(href)) {
16275
- link.target = "_blank";
16276
- link.rel = "noopener noreferrer";
16277
- }
18678
+ configureMarkdownLink(link, href);
16278
18679
  appendInlineMarkdown(link, label, depth + 1);
16279
18680
  parent.append(link);
16280
18681
  } else {
@@ -17092,13 +19493,33 @@ function assistantThinkingText(part) {
17092
19493
  return typeof part.content === "string" ? part.content : "";
17093
19494
  }
17094
19495
 
19496
+ function stripEmptyHtmlComments(text) {
19497
+ return String(text || "")
19498
+ .replace(/^[^\S\n]*<!--[\s\r\n]*-->[^\S\n]*(?:\n|$)/gm, "")
19499
+ .replace(/<!--[\s\r\n]*-->/g, "")
19500
+ .replace(/\n[^\S\n]*(?:\n[^\S\n]*){2,}/g, "\n\n");
19501
+ }
19502
+
17095
19503
  function visibleThinkingText(text) {
17096
- const value = String(text || "");
19504
+ const value = stripEmptyHtmlComments(text);
17097
19505
  const trimmed = value.trim();
17098
19506
  if (!trimmed || trimmed === UNEXPOSED_THINKING_TEXT) return "";
17099
19507
  return value;
17100
19508
  }
17101
19509
 
19510
+ function renderThinkingMarkdown(block, text) {
19511
+ if (!block) return;
19512
+ block._rawThinkingText = String(text || "");
19513
+ renderMarkdown(block, block._rawThinkingText);
19514
+ }
19515
+
19516
+ function appendThinkingMarkdown(parent, text) {
19517
+ const block = appendMarkdown(parent, text);
19518
+ block.classList.add("thinking-text");
19519
+ block._rawThinkingText = String(text || "");
19520
+ return block;
19521
+ }
19522
+
17102
19523
  function escapeRegExp(value) {
17103
19524
  return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
17104
19525
  }
@@ -18254,7 +20675,7 @@ function appendMessage(message, { streaming = false, messageIndex = -1, transien
18254
20675
  bubble._toolRenderSignature = toolExecutionRenderSignature(message);
18255
20676
  } else if (message.role === "thinking") {
18256
20677
  const thinkingText = visibleThinkingText(message.thinking || textFromContent(message.content));
18257
- if (thinkingOutputVisible && thinkingText) appendText(body, thinkingText, "thinking-text");
20678
+ if (thinkingOutputVisible && thinkingText) appendThinkingMarkdown(body, thinkingText);
18258
20679
  } else if (message.role === "toolCall") {
18259
20680
  renderToolCallMessageBody(body, message);
18260
20681
  } else if (message.role === "assistantEvent") {
@@ -19280,7 +21701,7 @@ function updateOptionalFeatureAvailability() {
19280
21701
  optionalFeatureAvailability.workflows = hasAvailableCommand("workflow") || hasAvailableCommand("workflow-clear") || optionalFeatureAvailability.workflows || widgets.has("workflow") || widgets.has("workflow:subprocess");
19281
21702
  optionalFeatureAvailability.safetyGuard = hasAvailableCommand("safety-guard") || optionalFeatureAvailability.safetyGuard || statusEntries.has("safety-guard");
19282
21703
  optionalFeatureAvailability.statsCommand = hasAvailableCommand("stats");
19283
- optionalFeatureAvailability.gitFooterStatus = hasAvailableCommand("git-footer-refresh") || optionalFeatureAvailability.gitFooterStatus || statusEntries.has("git-footer") || statusEntries.has(GIT_FOOTER_WEBUI_STATUS_KEY);
21704
+ optionalFeatureAvailability.gitFooterStatus = hasAvailableCommand("git-footer-refresh") || hasAvailableCommand("git-footer-visibility") || optionalFeatureAvailability.gitFooterStatus || statusEntries.has("git-footer") || statusEntries.has(GIT_FOOTER_WEBUI_STATUS_KEY);
19284
21705
  optionalFeatureAvailability.tuiSkillsCommand = hasLoadedRpcCommand("skills");
19285
21706
  optionalFeatureAvailability.todoProgressWidget = hasAvailableCommand("todo-progress-status") || optionalFeatureAvailability.todoProgressWidget || widgets.has("todo-progress");
19286
21707
  optionalFeatureAvailability.tuiToolsCommand = hasLoadedRpcCommand("tools");
@@ -19374,81 +21795,118 @@ function renderOptionalFeaturePanel() {
19374
21795
  elements.optionalFeaturesBox.append(notice);
19375
21796
  }
19376
21797
 
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
- }
21798
+ const renderedFeatureIds = new Set();
21799
+ for (const section of OPTIONAL_FEATURE_SECTIONS) {
21800
+ const sectionFeatures = section.featureIds
21801
+ .map((featureId) => OPTIONAL_FEATURE_BY_ID.get(featureId))
21802
+ .filter(Boolean);
21803
+ if (!sectionFeatures.length) continue;
21804
+ for (const feature of sectionFeatures) renderedFeatureIds.add(feature.id);
21805
+ renderOptionalFeatureSection(section, sectionFeatures);
21806
+ }
21807
+
21808
+ const uncategorizedFeatures = OPTIONAL_FEATURES.filter((feature) => !renderedFeatureIds.has(feature.id));
21809
+ if (uncategorizedFeatures.length) {
21810
+ renderOptionalFeatureSection({
21811
+ id: "other",
21812
+ label: "Other",
21813
+ description: "Optional companions that have not been assigned to a type section yet.",
21814
+ }, uncategorizedFeatures);
21815
+ }
21816
+ }
21817
+
21818
+ function renderOptionalFeatureSection(section, features) {
21819
+ const sectionNode = make("section", "optional-feature-section");
21820
+ sectionNode.dataset.optionalFeatureSection = section.id;
19448
21821
 
19449
- row.append(main, actions);
19450
- elements.optionalFeaturesBox.append(row);
21822
+ const header = make("div", "optional-feature-section-header");
21823
+ header.append(
21824
+ make("div", "optional-feature-section-title", section.label),
21825
+ make("span", "optional-feature-section-count", String(features.length)),
21826
+ );
21827
+ sectionNode.append(header);
21828
+ if (section.description) sectionNode.append(make("div", "optional-feature-section-description", section.description));
21829
+
21830
+ const list = make("div", "optional-feature-section-list");
21831
+ for (const feature of features) list.append(renderOptionalFeatureRow(feature));
21832
+ sectionNode.append(list);
21833
+ elements.optionalFeaturesBox.append(sectionNode);
21834
+ }
21835
+
21836
+ function renderOptionalFeatureRow(feature) {
21837
+ const detected = isOptionalFeatureDetected(feature.id);
21838
+ const enabled = isOptionalFeatureEnabled(feature.id);
21839
+ const installState = optionalFeatureInstallState(feature.id);
21840
+ const installing = optionalFeatureInstallInProgress.has(feature.id) || optionalFeatureInstallIsActive(installState);
21841
+ const failed = installState?.phase === "failed";
21842
+ const packageStatus = optionalFeaturePackageStatus(feature.id);
21843
+ const status = optionalFeatureStatus(feature.id);
21844
+ const row = make("div", `optional-feature-row ${status.className}`);
21845
+ const tooltip = optionalFeatureTooltip(feature, status);
21846
+ row.dataset.tooltip = tooltip;
21847
+ row.setAttribute("aria-label", tooltip.replace(/\s+/g, " "));
21848
+ row.tabIndex = 0;
21849
+
21850
+ const main = make("div", "optional-feature-main");
21851
+ const title = make("div", "optional-feature-title");
21852
+ title.append(make("strong", undefined, feature.label), make("span", `optional-feature-pill ${status.className}`, status.label));
21853
+ main.append(title);
21854
+ if (status.detail) {
21855
+ const detail = make("div", `optional-feature-detail ${status.className === "failed" ? "error" : ""}`.trim(), status.detail);
21856
+ detail.setAttribute("aria-live", installing ? "polite" : "off");
21857
+ main.append(detail);
21858
+ }
21859
+ if (installing) {
21860
+ const progress = make("div", "optional-feature-progress");
21861
+ progress.setAttribute("aria-hidden", "true");
21862
+ progress.append(make("span"));
21863
+ main.append(progress);
21864
+ }
21865
+ if (status.hint) main.append(make("div", "optional-feature-hint", status.hint));
21866
+ if (status.command) {
21867
+ const command = make("div", "optional-feature-command");
21868
+ command.append(make("code", undefined, status.command));
21869
+ main.append(command);
21870
+ }
21871
+ if (failed && installState?.outputTail) main.append(make("pre", "optional-feature-error-output", installState.outputTail));
21872
+
21873
+ const actions = make("div", "optional-feature-actions");
21874
+ const action = make("button", "optional-feature-action");
21875
+ action.type = "button";
21876
+ action.disabled = installing;
21877
+ if (installing) {
21878
+ action.textContent = installState?.actionLabel === "Update" ? "Updating…" : "Installing…";
21879
+ action.setAttribute("aria-busy", "true");
21880
+ } else if (failed) {
21881
+ const retryAsUpdate = installState?.actionLabel === "Update" || packageStatus?.updateAvailable;
21882
+ action.textContent = "Retry…";
21883
+ action.classList.add(retryAsUpdate ? "update" : "install");
21884
+ action.addEventListener("click", () => installOptionalFeature(feature.id, { update: retryAsUpdate }));
21885
+ } else if (packageStatus?.updateAvailable) {
21886
+ action.textContent = "Update…";
21887
+ action.classList.add("update");
21888
+ action.addEventListener("click", () => installOptionalFeature(feature.id, { update: true }));
21889
+ } else if (detected) {
21890
+ action.textContent = enabled ? "Disable" : "Enable";
21891
+ action.addEventListener("click", () => setOptionalFeatureDisabled(feature.id, enabled));
21892
+ } else if (packageStatus?.installed) {
21893
+ action.textContent = "Reload";
21894
+ action.addEventListener("click", () => sendPrompt("prompt", "/reload"));
21895
+ } else {
21896
+ action.textContent = "Install…";
21897
+ action.classList.add("install");
21898
+ action.addEventListener("click", () => installOptionalFeature(feature.id));
21899
+ }
21900
+ actions.append(action);
21901
+ if (status.command) {
21902
+ const copyCommand = make("button", "optional-feature-action copy-command", "Copy cmd");
21903
+ copyCommand.type = "button";
21904
+ copyCommand.addEventListener("click", () => copyOptionalFeatureInstallCommand(feature.id));
21905
+ actions.append(copyCommand);
19451
21906
  }
21907
+
21908
+ row.append(main, actions);
21909
+ return row;
19452
21910
  }
19453
21911
 
19454
21912
  function renderOptionalFeatureControls() {
@@ -19506,6 +21964,16 @@ function renderOptionalFeatureControls() {
19506
21964
  );
19507
21965
  }
19508
21966
 
21967
+ const hasGitFooterVisibility = isOptionalFeatureEnabled("gitFooterStatus") && gitFooterVisibilityCommandAvailable();
21968
+ if (elements.optionsFooterVisibilityButton) {
21969
+ elements.optionsFooterVisibilityButton.hidden = !hasGitFooterVisibility;
21970
+ setOptionalControlState(
21971
+ elements.optionsFooterVisibilityButton,
21972
+ hasGitFooterVisibility,
21973
+ commandUnavailableMessage("git-footer-visibility"),
21974
+ );
21975
+ }
21976
+
19509
21977
  const hasNaturalConversation = isOptionalFeatureEnabled("naturalConversation") || activeConversationMode().enabled;
19510
21978
  if (elements.optionsConversationModeButton) {
19511
21979
  elements.optionsConversationModeButton.hidden = !hasNaturalConversation;
@@ -20092,6 +22560,159 @@ async function openNativeSettingsDialog() {
20092
22560
  const save = addNativeCommandAction("Apply", () => applySettings(false, save), "primary");
20093
22561
  }
20094
22562
 
22563
+ function replaceNativeSettingSelectOptions(select, options, preferredValue) {
22564
+ const normalized = normalizedSettingOptions(options);
22565
+ select.replaceChildren();
22566
+ for (const option of normalized) {
22567
+ const element = make("option", undefined, option.label);
22568
+ element.value = option.value;
22569
+ select.append(element);
22570
+ }
22571
+ const values = normalized.map((option) => option.value);
22572
+ select.value = values.includes(String(preferredValue)) ? String(preferredValue) : values[0] || "";
22573
+ }
22574
+
22575
+ function gitWorkflowSetupModelKey(model) {
22576
+ return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
22577
+ }
22578
+
22579
+ async function openNativeGitWorkflowSetupDialog({ onSaved } = {}) {
22580
+ openNativeCommandDialog({
22581
+ title: "/git-workflow-setup",
22582
+ message: "Configure the dedicated model and safe defaults used by Guided Git. The selected generation profile is applied only while commit, branch, or PR text is generated.",
22583
+ });
22584
+ renderNativeLoading("Loading guided Git preferences and available models…");
22585
+
22586
+ let data;
22587
+ try {
22588
+ const response = await nativeCommandApi("/api/git-workflow/preferences");
22589
+ data = response.data || {};
22590
+ } catch (error) {
22591
+ setNativeCommandError(error.message || String(error));
22592
+ elements.nativeCommandBody.replaceChildren();
22593
+ return;
22594
+ }
22595
+
22596
+ const preferences = data.preferences || {};
22597
+ const models = Array.isArray(data.models) ? data.models : [];
22598
+ if (!models.length) {
22599
+ setNativeCommandError("No authenticated Pi models are available. Run /login or configure a provider first.");
22600
+ elements.nativeCommandBody.replaceChildren();
22601
+ return;
22602
+ }
22603
+
22604
+ const configuredModelKey = `${preferences.generation?.provider || ""}/${preferences.generation?.modelId || ""}`;
22605
+ const activeModelKey = gitWorkflowSetupModelKey(currentState?.model);
22606
+ const modelKeys = new Set(models.map(gitWorkflowSetupModelKey));
22607
+ const initialModelKey = modelKeys.has(configuredModelKey)
22608
+ ? configuredModelKey
22609
+ : modelKeys.has(activeModelKey)
22610
+ ? activeModelKey
22611
+ : gitWorkflowSetupModelKey(models[0]);
22612
+ const modelOptions = models.map((model) => ({
22613
+ value: gitWorkflowSetupModelKey(model),
22614
+ label: `${gitWorkflowSetupModelKey(model)}${model.name && model.name !== model.id ? ` · ${model.name}` : ""}`,
22615
+ }));
22616
+
22617
+ const controls = {
22618
+ model: nativeSettingSelect("Git-writing model", initialModelKey, modelOptions, "Exact authenticated provider/model used for commit messages, branch names, and PR descriptions.", { label: "required", tone: "safety" }),
22619
+ thinking: nativeSettingSelect("Reasoning effort", preferences.generation?.thinkingLevel || "low", SETTINGS_THINKING_OPTIONS, "Only levels supported by the selected model are shown. Low is recommended for routine commit messages.", { label: "required", tone: "safety" }),
22620
+ language: nativeSettingSelect("Generated language", preferences.commit?.language || "en", [
22621
+ { value: "en", label: "English" },
22622
+ { value: "de", label: "German" },
22623
+ ], "Language for generated commit and PR text.", { label: "saved", tone: "browser" }),
22624
+ defaultVariant: nativeSettingSelect("Default message", preferences.commit?.defaultVariant || "short", [
22625
+ { value: "short", label: "Short subject" },
22626
+ { value: "long", label: "Long subject + body" },
22627
+ ], "Highlights the preferred commit choice; committing always remains explicit.", { label: "saved", tone: "browser" }),
22628
+ scope: nativeSettingSelect("Conventional scope", preferences.commit?.scope || "auto", [
22629
+ { value: "auto", label: "Auto-detect when clear" },
22630
+ { value: "never", label: "Never include a scope" },
22631
+ { value: "required", label: "Always include a scope" },
22632
+ ], "Controls type(scope): subject generation.", { label: "saved", tone: "browser" }),
22633
+ staging: nativeSettingSelect("Staging behavior", preferences.stagingPolicy || "review", [
22634
+ { value: "review", label: "Review/select files" },
22635
+ { value: "preserve", label: "Use current staged set" },
22636
+ { value: "all", label: "Stage all with git add ." },
22637
+ ], "Review/select is the safe default and opens Git Changes for per-file staging.", { label: "safety", tone: "safety" }),
22638
+ delivery: nativeSettingSelect("Delivery path", preferences.deliveryMode || "ask", [
22639
+ { value: "ask", label: "Ask each workflow" },
22640
+ { value: "current", label: "Prefer current branch" },
22641
+ { value: "pr-worktree", label: "Prefer PR worktree" },
22642
+ ], "Controls which explicit commit/PR action is highlighted.", { label: "saved", tone: "browser" }),
22643
+ verification: nativeSettingSelect("Pre-commit verification", preferences.verificationPolicy || "ask", [
22644
+ { value: "ask", label: "Show verification reminder" },
22645
+ { value: "none", label: "No reminder" },
22646
+ ], "The reminder never claims tests were run and does not bypass Git hooks.", { label: "safety", tone: "safety" }),
22647
+ };
22648
+
22649
+ const thinkingLevelsForModel = (modelKey) => {
22650
+ const levels = data.modelThinkingLevels?.[modelKey];
22651
+ return Array.isArray(levels) && levels.length ? levels : ["off"];
22652
+ };
22653
+ const syncThinkingLevels = () => {
22654
+ const current = controls.thinking.select.value || preferences.generation?.thinkingLevel || "low";
22655
+ const levels = thinkingLevelsForModel(controls.model.select.value);
22656
+ replaceNativeSettingSelectOptions(controls.thinking.select, levels, current);
22657
+ };
22658
+ controls.model.select.addEventListener("change", syncThinkingLevels);
22659
+ syncThinkingLevels();
22660
+
22661
+ const body = make("div", "native-settings-panel");
22662
+ body.append(
22663
+ nativeSettingsNote("Persistence", `Saved globally in ${data.path || "the Pi Web UI settings file"}. Credentials are never stored here.`),
22664
+ nativeSettingsSection("Generation profile", "Required model and effort for generated Git text.", [controls.model, controls.thinking], { open: true }),
22665
+ nativeSettingsSection("Commit style", "Conventional Commit output preferences.", [controls.language, controls.defaultVariant, controls.scope], { open: true }),
22666
+ nativeSettingsSection("Workflow safety", "Staging, delivery, and verification defaults; push and PR confirmation remain mandatory.", [controls.staging, controls.delivery, controls.verification], { open: true }),
22667
+ );
22668
+ elements.nativeCommandBody.replaceChildren(body);
22669
+ elements.nativeCommandActions.replaceChildren();
22670
+ addNativeCommandAction("Cancel", closeNativeCommandDialog);
22671
+
22672
+ const save = addNativeCommandAction("Save setup", async () => {
22673
+ setNativeActionBusy(save, true, "Saving…");
22674
+ setNativeCommandError("");
22675
+ try {
22676
+ const selectedModel = models.find((model) => gitWorkflowSetupModelKey(model) === controls.model.select.value);
22677
+ if (!selectedModel) throw new Error("Select an available Git-writing model.");
22678
+ const response = await nativeCommandApi("/api/git-workflow/preferences", {
22679
+ method: "POST",
22680
+ body: {
22681
+ preferences: {
22682
+ generation: {
22683
+ provider: selectedModel.provider,
22684
+ modelId: selectedModel.id,
22685
+ thinkingLevel: controls.thinking.select.value,
22686
+ unavailablePolicy: "ask",
22687
+ },
22688
+ commit: {
22689
+ language: controls.language.select.value,
22690
+ defaultVariant: controls.defaultVariant.select.value,
22691
+ scope: controls.scope.select.value,
22692
+ },
22693
+ stagingPolicy: controls.staging.select.value,
22694
+ deliveryMode: controls.delivery.select.value,
22695
+ verificationPolicy: controls.verification.select.value,
22696
+ },
22697
+ },
22698
+ });
22699
+ gitWorkflowPreferences = response.data?.preferences || null;
22700
+ addTransientMessage({
22701
+ role: "native",
22702
+ title: "/git-workflow-setup",
22703
+ content: `Guided Git setup saved for ${gitWorkflowSetupModelKey(selectedModel)} at ${controls.thinking.select.value} effort.`,
22704
+ level: "info",
22705
+ });
22706
+ closeNativeCommandDialog();
22707
+ if (typeof onSaved === "function") await onSaved(gitWorkflowPreferences);
22708
+ } catch (error) {
22709
+ setNativeCommandError(error.message || String(error));
22710
+ } finally {
22711
+ setNativeActionBusy(save, false);
22712
+ }
22713
+ }, "primary");
22714
+ }
22715
+
20095
22716
  async function openNativeForkSelector() {
20096
22717
  openNativeCommandDialog({ title: "/fork", message: "Choose a previous user message to fork before.", searchPlaceholder: "Filter fork points…" });
20097
22718
  renderNativeLoading("Loading fork points…");
@@ -20604,6 +23225,9 @@ async function handleNativeSlashSelectorCommand(message, { usesPromptInput = fal
20604
23225
  case "settings":
20605
23226
  await openNativeSettingsDialog();
20606
23227
  return true;
23228
+ case "git-workflow-setup":
23229
+ await openNativeGitWorkflowSetupDialog();
23230
+ return true;
20607
23231
  case "theme":
20608
23232
  openNativeThemeSelector();
20609
23233
  return true;
@@ -20844,7 +23468,8 @@ function ensureStreamingThinkingBubble() {
20844
23468
  if (streamThinkingBubble?.parentElement === elements.chat) return true;
20845
23469
  const created = appendMessage({ role: "thinking", title: "thinking", timestamp: Date.now(), content: "" }, { streaming: true });
20846
23470
  streamThinkingBubble = created.bubble;
20847
- streamThinking = appendText(created.body, "", "thinking-text");
23471
+ streamThinking = make("div", "markdown-body thinking-text");
23472
+ created.body.append(streamThinking);
20848
23473
  renderRunIndicator({ scroll: false });
20849
23474
  scrollChatToBottom();
20850
23475
  return true;
@@ -20852,7 +23477,7 @@ function ensureStreamingThinkingBubble() {
20852
23477
 
20853
23478
  function showStreamingThinking(initialText = "") {
20854
23479
  if (!ensureStreamingThinkingBubble()) return;
20855
- if (initialText && !streamThinking.textContent) streamThinking.textContent = initialText;
23480
+ if (initialText && !streamThinking.textContent) renderThinkingMarkdown(streamThinking, initialText);
20856
23481
  }
20857
23482
 
20858
23483
  function resetStreamBubble() {
@@ -20882,7 +23507,7 @@ function liveStreamRenderActive() {
20882
23507
  * re-append the live thinking/text bubbles so no partial output is lost.
20883
23508
  */
20884
23509
  function restoreStreamRenderAfterChatRebuild() {
20885
- const thinkingText = streamThinking?.textContent || "";
23510
+ const thinkingText = streamThinking?._rawThinkingText || streamThinking?.textContent || "";
20886
23511
  const thinkingComplete = streamThinkingBubble?.classList.contains("complete") === true;
20887
23512
  const toolCallWasVisible = !!(streamToolCallBubble?.parentElement === elements.chat || streamToolCallRawArguments || streamToolCallName);
20888
23513
  streamBubble = null;
@@ -20999,7 +23624,7 @@ function setStreamingThinkingText(text) {
20999
23624
  const thinking = visibleThinkingText(text);
21000
23625
  if (!thinkingOutputVisible || !thinking) return false;
21001
23626
  showStreamingThinking("");
21002
- if (streamThinking) streamThinking.textContent = thinking;
23627
+ if (streamThinking) renderThinkingMarkdown(streamThinking, thinking);
21003
23628
  return true;
21004
23629
  }
21005
23630
 
@@ -21058,8 +23683,7 @@ function handleMessageUpdate(event) {
21058
23683
  const synced = syncStreamingThinkingFromUpdate(event, update);
21059
23684
  if (thinkingOutputVisible && delta && (!synced || !streamThinking?.textContent)) {
21060
23685
  showStreamingThinking("");
21061
- if (streamThinking?.textContent === "Thinking…") streamThinking.textContent = "";
21062
- if (streamThinking) streamThinking.textContent += delta;
23686
+ if (streamThinking) renderThinkingMarkdown(streamThinking, `${streamThinking._rawThinkingText || ""}${delta}`);
21063
23687
  }
21064
23688
  scheduleChatFollowScroll();
21065
23689
  } else if (update.type === "thinking_end") {
@@ -23644,10 +26268,22 @@ elements.optionsRemoteButton.addEventListener("click", () => runNativeCommandMen
23644
26268
  elements.optionsNameButton.addEventListener("click", () => runNativeCommandMenu("/name"));
23645
26269
  elements.optionsCloneButton.addEventListener("click", () => runNativeCommandMenu("/clone"));
23646
26270
  elements.optionsSettingsButton.addEventListener("click", () => runNativeCommandMenu("/settings"));
26271
+ elements.optionsGitWorkflowSetupButton?.addEventListener("click", () => runNativeCommandMenu("/git-workflow-setup"));
23647
26272
  elements.optionsExportButton.addEventListener("click", () => runNativeCommandMenu("/export"));
23648
26273
  elements.optionsForkButton.addEventListener("click", () => runNativeCommandMenu("/fork"));
23649
26274
  elements.optionsTreeButton.addEventListener("click", () => runNativeCommandMenu("/tree"));
23650
26275
  elements.optionsStatsButton?.addEventListener("click", () => openStatsOverlay({ refresh: true }));
26276
+ elements.optionsFooterVisibilityButton?.addEventListener("click", openGitFooterVisibilityDialog);
26277
+ elements.gitFooterVisibilitySelectAllButton?.addEventListener("click", () => setGitFooterVisibilitySelection(true));
26278
+ elements.gitFooterVisibilitySelectNoneButton?.addEventListener("click", () => setGitFooterVisibilitySelection(false));
26279
+ elements.gitFooterVisibilityCloseButton?.addEventListener("click", closeGitFooterVisibilityDialog);
26280
+ elements.gitFooterVisibilityResetButton?.addEventListener("click", () => resetGitFooterVisibilityDialog());
26281
+ elements.gitFooterVisibilityApplyButton?.addEventListener("click", () => applyGitFooterVisibilityDialog());
26282
+ elements.gitFooterVisibilityDialog?.querySelector("form")?.addEventListener("submit", (event) => event.preventDefault());
26283
+ elements.gitFooterVisibilityDialog?.addEventListener("close", () => {
26284
+ gitFooterVisibilityDirty = false;
26285
+ gitFooterVisibilityApplyInFlight = false;
26286
+ });
23651
26287
  elements.statsOverlayRefreshButton?.addEventListener("click", () => requestStatsOverlayRefresh());
23652
26288
  elements.statsOverlayScope?.addEventListener("change", () => {
23653
26289
  const custom = elements.statsOverlayScope?.value === "custom";
@@ -24344,8 +26980,13 @@ window.addEventListener("keydown", (event) => {
24344
26980
 
24345
26981
  window.addEventListener("keydown", handleNativeAppShortcut, { capture: true });
24346
26982
  document.addEventListener("visibilitychange", () => {
24347
- if (document.visibilityState === "visible") scheduleForegroundReconcile("visibility resume", 0);
24348
- else resetAbortLongPressAffordance();
26983
+ if (document.visibilityState === "visible") {
26984
+ scheduleForegroundReconcile("visibility resume", 0);
26985
+ refreshSubagents().finally(() => scheduleRefreshSubagents());
26986
+ } else {
26987
+ resetAbortLongPressAffordance();
26988
+ scheduleRefreshSubagents();
26989
+ }
24349
26990
  });
24350
26991
  window.addEventListener("pageshow", () => scheduleForegroundReconcile("page show", 0));
24351
26992
  window.addEventListener("focus", () => scheduleForegroundReconcile("window focus"));
@@ -24447,6 +27088,7 @@ window.addEventListener("blur", () => {
24447
27088
  });
24448
27089
 
24449
27090
  elements.gitChangesRefreshButton?.addEventListener("click", refreshGitChangesDialog);
27091
+ elements.gitChangesFetchButton?.addEventListener("click", () => fetchGitChangesDialog().catch((error) => addEvent(error.message || String(error), "error")));
24450
27092
  elements.gitChangesPullButton?.addEventListener("click", () => pullGitChangesDialog().catch((error) => addEvent(error.message || String(error), "error")));
24451
27093
  elements.gitChangesCloseButton?.addEventListener("click", closeGitChangesDialog);
24452
27094
  elements.gitChangesBody?.addEventListener("scroll", updateGitChangesCurrentFileHeader, { passive: true });
@@ -24485,6 +27127,9 @@ elements.refreshClaudeUsageButton?.addEventListener("click", () => {
24485
27127
  refreshClaudeUsage().finally(() => scheduleRefreshClaudeUsage());
24486
27128
  });
24487
27129
  elements.fileTreeRefreshButton?.addEventListener("click", () => refreshFileTreeRoot().catch((error) => addEvent(error.message || String(error), "error")));
27130
+ elements.fileTreeRoot?.addEventListener("dragover", handleFileTreeRootDragOver);
27131
+ elements.fileTreeRoot?.addEventListener("dragleave", handleFileTreeRootDragLeave);
27132
+ elements.fileTreeRoot?.addEventListener("drop", (event) => handleFileTreeRootDrop(event).catch((error) => addEvent(error.message || String(error), "error")));
24488
27133
  elements.fileTreeSearchInput?.addEventListener("input", () => scheduleFileTreeSearch());
24489
27134
  elements.fileTreeSearchInput?.addEventListener("keydown", (event) => {
24490
27135
  if (event.key === "Enter") {
@@ -24505,6 +27150,8 @@ elements.fileContextMenu?.addEventListener("click", (event) => {
24505
27150
  const action = button.dataset.fileMenuAction || "";
24506
27151
  if (action === "open-default") openPathInDefaultEditor(entry.path).catch((error) => addEvent(error.message || String(error), "error"));
24507
27152
  else if (action === "open-webui") openFileTreeEntryInWebui(entry).catch((error) => addEvent(error.message || String(error), "error"));
27153
+ else if (action === "move") moveFileTreeEntry(entry).catch((error) => addEvent(error.message || String(error), "error"));
27154
+ else if (action === "delete") deleteFileTreeEntry(entry).catch((error) => addEvent(error.message || String(error), "error"));
24508
27155
  });
24509
27156
  elements.fileViewerOpenDefaultButton?.addEventListener("click", () => openPathInDefaultEditor(currentFileViewerPath()));
24510
27157
  elements.fileViewerResizeHandle?.addEventListener("pointerdown", beginFileViewerResize);
@@ -24677,6 +27324,7 @@ bindSidePanelSectionToggles();
24677
27324
  restoreSidePanelState();
24678
27325
  initializeCodexUsage();
24679
27326
  initializeClaudeUsage();
27327
+ initializeSubagents();
24680
27328
  initializeUpdateNotifications();
24681
27329
  bindMobileViewChanges();
24682
27330
  bindSidePanelOverlayViewChanges();