@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/bin/pi-webui.mjs CHANGED
@@ -21,6 +21,23 @@ import {
21
21
  validateSessionDelete,
22
22
  } from "../lib/session-actions.mjs";
23
23
  import { sweepStaleTempEntries } from "../lib/temp-artifacts.mjs";
24
+ import {
25
+ GIT_WORKFLOW_DEFAULT_VARIANTS,
26
+ GIT_WORKFLOW_DELIVERY_MODES,
27
+ GIT_WORKFLOW_LANGUAGES,
28
+ GIT_WORKFLOW_SCOPE_POLICIES,
29
+ GIT_WORKFLOW_STAGING_POLICIES,
30
+ GIT_WORKFLOW_THINKING_LEVELS,
31
+ GIT_WORKFLOW_VERIFICATION_POLICIES,
32
+ isGitWorkflowSetupComplete,
33
+ mergeGitWorkflowPreferences,
34
+ readGitWorkflowPreferences,
35
+ readWebuiSettings,
36
+ supportedGitWorkflowThinkingLevels,
37
+ webuiSettingsFile,
38
+ writeGitWorkflowPreferences,
39
+ writeWebuiSettings,
40
+ } from "../lib/git-workflow-preferences.mjs";
24
41
  import {
25
42
  evaluateDispatchTrustGuards,
26
43
  guardsForNativeCommand,
@@ -40,9 +57,11 @@ import {
40
57
  WORKTREE_ERROR_CODES,
41
58
  createGitWorktree,
42
59
  gitWorktreeErrorPayload,
60
+ isGitLockFailure,
43
61
  listGitWorktrees,
44
62
  openGitWorktree,
45
63
  pathInside,
64
+ pruneGitWorktrees,
46
65
  removeGitWorktree,
47
66
  } from "../lib/git-worktrees.mjs";
48
67
 
@@ -53,7 +72,6 @@ const publicDir = path.join(packageRoot, "public");
53
72
  const webuiHelperExtensionPath = path.join(packageRoot, "webui-rpc-helper.mjs");
54
73
  const agentDir = process.env.PI_CODING_AGENT_DIR || path.join(homedir(), ".pi", "agent");
55
74
  const OPTIONAL_FEATURE_INSTALL_ROOT_ENV = "PI_WEBUI_OPTIONAL_FEATURE_INSTALL_ROOT";
56
- const WEBUI_SETTINGS_FILE_ENV = "PI_WEBUI_SETTINGS_FILE";
57
75
  const packageJson = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
58
76
  let piPackageJson = {};
59
77
  try {
@@ -73,6 +91,12 @@ const PROMPT_REQUEST_TIMEOUT_MS = Math.max(REQUEST_TIMEOUT_MS, Number.parseInt(p
73
91
  const WEBUI_HELPER_TIMEOUT_MS = 8 * 1000;
74
92
  const WEBUI_HELPER_COMMAND = "webui-helper";
75
93
  const WEBUI_HELPER_RESPONSE_PREFIX = "__PI_WEBUI_HELPER_RESPONSE__:";
94
+ const WEBUI_SUBAGENTS_STATUS_KEY = "webui-subagents";
95
+ const WEBUI_SUBAGENTS_PAYLOAD_PREFIX = "PI_WEBUI_SUBAGENTS_V1 ";
96
+ const WEBUI_SUBAGENT_RUN_LIMIT = 128;
97
+ const WEBUI_SUBAGENT_AGENT_LIMIT = 256;
98
+ const WEBUI_SUBAGENT_OUTPUT_LINE_LIMIT = 120;
99
+ const WEBUI_SUBAGENT_OUTPUT_LINE_LENGTH = 1000;
76
100
  const PI_CODING_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
77
101
  const WEBUI_PACKAGE = packageJson.name || "@firstpick/pi-package-webui";
78
102
  const PI_LATEST_VERSION_URL = process.env.PI_WEBUI_PI_LATEST_VERSION_URL || "https://pi.dev/api/latest-version";
@@ -114,7 +138,7 @@ const ATTACHMENT_UPLOAD_MAX_TOTAL_BYTES = 64 * 1024 * 1024;
114
138
  const INLINE_IMAGE_MAX_BYTES = 8 * 1024 * 1024;
115
139
  const INLINE_IMAGE_TOTAL_MAX_BYTES = 16 * 1024 * 1024;
116
140
  const RPC_IMAGE_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
117
- const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"];
141
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
118
142
  const SETTINGS_TRANSPORT_CHOICES = ["sse", "websocket", "websocket-cached", "auto"];
119
143
  const SETTINGS_HTTP_IDLE_TIMEOUT_CHOICES = [
120
144
  { label: "30 sec", timeoutMs: 30_000 },
@@ -446,16 +470,44 @@ function formatUrlHost(host) {
446
470
  return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
447
471
  }
448
472
 
473
+ function makeUserFacingError(message, props = {}) {
474
+ const text = String(message || "Unknown error").trim() || "Unknown error";
475
+ const error = new Error(text);
476
+ error.userMessage = text;
477
+ Object.assign(error, props);
478
+ return error;
479
+ }
480
+
449
481
  function sanitizeError(error) {
450
482
  if (!error) return "Unknown error";
451
483
  if (typeof error === "string") return error;
484
+ if (error.userMessage) return error.userMessage;
452
485
  return error.stack || error.message || String(error);
453
486
  }
454
487
 
455
488
  function formatCliError(error) {
456
489
  if (!error) return "Unknown error";
457
490
  if (typeof error === "string") return error;
458
- return error.message || String(error);
491
+ return error.userMessage || error.message || String(error);
492
+ }
493
+
494
+ function formatCommandSpawnError(command, error) {
495
+ const commandText = String(command || "command");
496
+ const executable = commandText.split(/[\\/]/).pop() || commandText;
497
+ const isGit = /^git(?:\.exe)?$/i.test(executable);
498
+ if (error?.code === "ENOENT") {
499
+ if (isGit) {
500
+ const windowsHint = process.platform === "win32"
501
+ ? " On Windows, install Git for Windows and choose 'Git from the command line and also from 3rd-party software', or add Git's cmd/bin directory to PATH."
502
+ : "";
503
+ return `Git executable not found on PATH (spawn ${executable} ENOENT). Install Git and ensure the 'git' command is available to the Pi Web UI process, then restart Pi Web UI.${windowsHint}`;
504
+ }
505
+ return `${executable} executable not found on PATH (spawn ${executable} ENOENT). Install it or add it to PATH, then restart Pi Web UI.`;
506
+ }
507
+ if (error?.code === "EACCES" || error?.code === "EPERM") {
508
+ return `Cannot start ${executable}: permission denied. Check executable permissions and PATH.`;
509
+ }
510
+ return formatCliError(error);
459
511
  }
460
512
 
461
513
  function delay(ms) {
@@ -1116,17 +1168,21 @@ function runCommand(command, args, { cwd, timeoutMs = 2000, maxOutputLength = 20
1116
1168
  return new Promise((resolve) => {
1117
1169
  const child = spawn(command, args, {
1118
1170
  cwd,
1171
+ // LC_ALL=C keeps tool output in English so error classification works
1172
+ // regardless of locale.
1173
+ env: { ...process.env, LC_ALL: "C" },
1119
1174
  stdio: ["ignore", "pipe", "pipe"],
1120
1175
  windowsHide: true,
1121
1176
  });
1122
1177
  let stdout = "";
1123
1178
  let stderr = "";
1179
+ let stdoutTruncated = false;
1124
1180
  let settled = false;
1125
1181
  const finish = (result) => {
1126
1182
  if (settled) return;
1127
1183
  settled = true;
1128
1184
  clearTimeout(timeout);
1129
- resolve(result);
1185
+ resolve({ stdoutTruncated, ...result });
1130
1186
  };
1131
1187
  const timeout = setTimeout(() => {
1132
1188
  child.kill("SIGKILL");
@@ -1134,13 +1190,19 @@ function runCommand(command, args, { cwd, timeoutMs = 2000, maxOutputLength = 20
1134
1190
  }, timeoutMs);
1135
1191
  child.stdout.on("data", (chunk) => {
1136
1192
  stdout += String(chunk);
1137
- if (stdout.length > maxOutputLength) stdout = stdout.slice(-maxOutputLength);
1193
+ if (stdout.length > maxOutputLength) {
1194
+ stdout = stdout.slice(-maxOutputLength);
1195
+ stdoutTruncated = true;
1196
+ }
1138
1197
  });
1139
1198
  child.stderr.on("data", (chunk) => {
1140
1199
  stderr += String(chunk);
1141
1200
  if (stderr.length > maxOutputLength) stderr = stderr.slice(-maxOutputLength);
1142
1201
  });
1143
- child.on("error", (error) => finish({ exitCode: undefined, stdout, stderr: sanitizeError(error), error: sanitizeError(error) }));
1202
+ child.on("error", (error) => {
1203
+ const message = formatCommandSpawnError(command, error);
1204
+ finish({ exitCode: undefined, stdout, stderr: message, error: message, errorCode: error?.code });
1205
+ });
1144
1206
  // "close", not "exit": exit can fire before the stdio pipes flush, which
1145
1207
  // intermittently truncates stdout (empty `git rev-parse --show-toplevel`
1146
1208
  // output resolves to process.cwd() and reads the wrong repository).
@@ -1541,48 +1603,168 @@ async function writePathFastPicks(picks) {
1541
1603
  return normalized;
1542
1604
  }
1543
1605
 
1544
- function webuiSettingsFile() {
1545
- if (process.env[WEBUI_SETTINGS_FILE_ENV]) return path.resolve(expandUserPath(process.env[WEBUI_SETTINGS_FILE_ENV]));
1546
- const configRoot = process.env.XDG_CONFIG_HOME || path.join(homedir(), ".config");
1547
- return path.join(configRoot, "pi-webui", "settings.json");
1606
+ async function readPersistedRemoteAuthEnabled() {
1607
+ return (await readWebuiSettings()).remoteAuthEnabled === true;
1608
+ }
1609
+
1610
+ async function saveRemoteAuthPreference(enabled) {
1611
+ const nextEnabled = enabled === true;
1612
+ await writeWebuiSettings({ remoteAuthEnabled: nextEnabled });
1613
+ persistedRemoteAuthEnabled = nextEnabled;
1614
+ return persistedRemoteAuthEnabled;
1615
+ }
1616
+
1617
+ function gitWorkflowModelKey(model) {
1618
+ return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
1619
+ }
1620
+
1621
+ async function availableGitWorkflowModels(tab) {
1622
+ const response = await safeRpcData(tab, { type: "get_available_models" });
1623
+ if (!response.ok) throw makeHttpError(400, response.error || "Failed to load available models");
1624
+ return (Array.isArray(response.data?.models) ? response.data.models : [])
1625
+ .filter((model) => model?.provider && model?.id)
1626
+ .sort((left, right) => gitWorkflowModelKey(left).localeCompare(gitWorkflowModelKey(right)));
1548
1627
  }
1549
1628
 
1550
- function normalizeWebuiSettings(value) {
1629
+ function gitWorkflowPreferenceOptions() {
1551
1630
  return {
1552
- version: 1,
1553
- remoteAuthEnabled: value?.remoteAuthEnabled === true,
1631
+ thinkingLevels: GIT_WORKFLOW_THINKING_LEVELS,
1632
+ languages: GIT_WORKFLOW_LANGUAGES,
1633
+ defaultVariants: GIT_WORKFLOW_DEFAULT_VARIANTS,
1634
+ scopePolicies: GIT_WORKFLOW_SCOPE_POLICIES,
1635
+ stagingPolicies: GIT_WORKFLOW_STAGING_POLICIES,
1636
+ deliveryModes: GIT_WORKFLOW_DELIVERY_MODES,
1637
+ verificationPolicies: GIT_WORKFLOW_VERIFICATION_POLICIES,
1554
1638
  };
1555
1639
  }
1556
1640
 
1557
- let webuiSettingsCache = null;
1641
+ async function gitWorkflowPreferencesData(tab) {
1642
+ const [preferences, models] = await Promise.all([
1643
+ readGitWorkflowPreferences(),
1644
+ availableGitWorkflowModels(tab),
1645
+ ]);
1646
+ return {
1647
+ preferences,
1648
+ configured: isGitWorkflowSetupComplete(preferences),
1649
+ models,
1650
+ modelThinkingLevels: Object.fromEntries(models.map((model) => [gitWorkflowModelKey(model), supportedGitWorkflowThinkingLevels(model)])),
1651
+ options: gitWorkflowPreferenceOptions(),
1652
+ path: webuiSettingsFile(),
1653
+ };
1654
+ }
1558
1655
 
1559
- async function readWebuiSettings() {
1560
- if (webuiSettingsCache) return webuiSettingsCache;
1561
- webuiSettingsCache = normalizeWebuiSettings(await readJsonFileIfExists(webuiSettingsFile()));
1562
- return webuiSettingsCache;
1656
+ function requireGitWorkflowChoice(value, key, choices) {
1657
+ const text = String(value ?? "").trim();
1658
+ if (!choices.includes(text)) throw makeHttpError(400, `${key} must be one of: ${choices.join(", ")}`);
1659
+ return text;
1563
1660
  }
1564
1661
 
1565
- async function writeWebuiSettings(patch) {
1566
- const current = await readWebuiSettings();
1567
- const next = normalizeWebuiSettings({ ...current, ...(patch || {}) });
1568
- const storageFile = webuiSettingsFile();
1569
- await mkdir(path.dirname(storageFile), { recursive: true });
1570
- const tmpFile = `${storageFile}.${process.pid}.${Date.now()}.tmp`;
1571
- await writeFile(tmpFile, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
1572
- await rename(tmpFile, storageFile);
1573
- webuiSettingsCache = next;
1574
- return next;
1662
+ async function saveGitWorkflowPreferencesData(tab, body = {}) {
1663
+ const submitted = body.preferences && typeof body.preferences === "object" ? body.preferences : body;
1664
+ if (submitted.generation?.thinkingLevel !== undefined) requireGitWorkflowChoice(submitted.generation.thinkingLevel, "generation.thinkingLevel", GIT_WORKFLOW_THINKING_LEVELS);
1665
+ if (submitted.commit?.language !== undefined) requireGitWorkflowChoice(submitted.commit.language, "commit.language", GIT_WORKFLOW_LANGUAGES);
1666
+ if (submitted.commit?.defaultVariant !== undefined) requireGitWorkflowChoice(submitted.commit.defaultVariant, "commit.defaultVariant", GIT_WORKFLOW_DEFAULT_VARIANTS);
1667
+ if (submitted.commit?.scope !== undefined) requireGitWorkflowChoice(submitted.commit.scope, "commit.scope", GIT_WORKFLOW_SCOPE_POLICIES);
1668
+ if (submitted.stagingPolicy !== undefined) requireGitWorkflowChoice(submitted.stagingPolicy, "stagingPolicy", GIT_WORKFLOW_STAGING_POLICIES);
1669
+ if (submitted.deliveryMode !== undefined) requireGitWorkflowChoice(submitted.deliveryMode, "deliveryMode", GIT_WORKFLOW_DELIVERY_MODES);
1670
+ if (submitted.verificationPolicy !== undefined) requireGitWorkflowChoice(submitted.verificationPolicy, "verificationPolicy", GIT_WORKFLOW_VERIFICATION_POLICIES);
1671
+
1672
+ const current = await readGitWorkflowPreferences();
1673
+ const next = mergeGitWorkflowPreferences(current, submitted);
1674
+ const provider = String(next.generation.provider || "").trim();
1675
+ const modelId = String(next.generation.modelId || "").trim();
1676
+ if (!provider || !modelId) throw makeHttpError(400, "Select a Git-writing model before saving setup");
1677
+
1678
+ const models = await availableGitWorkflowModels(tab);
1679
+ const model = models.find((candidate) => candidate.provider === provider && candidate.id === modelId);
1680
+ if (!model) throw makeHttpError(400, `Selected model is not currently available: ${provider}/${modelId}`);
1681
+ const supportedLevels = supportedGitWorkflowThinkingLevels(model);
1682
+ if (!supportedLevels.includes(next.generation.thinkingLevel)) {
1683
+ throw makeHttpError(400, `${provider}/${modelId} does not support thinking level ${next.generation.thinkingLevel}`);
1684
+ }
1685
+
1686
+ await writeGitWorkflowPreferences(next);
1687
+ return gitWorkflowPreferencesData(tab);
1575
1688
  }
1576
1689
 
1577
- async function readPersistedRemoteAuthEnabled() {
1578
- return (await readWebuiSettings()).remoteAuthEnabled === true;
1690
+ function gitWorkflowGenerationPrompt(kind, preferences) {
1691
+ switch (kind) {
1692
+ case "commit":
1693
+ return `/git-staged-msg ${preferences.commit.language} ${preferences.commit.scope}`;
1694
+ case "branch":
1695
+ return "/git-branch-name";
1696
+ case "pr":
1697
+ return `/pr ${preferences.commit.language}`;
1698
+ default:
1699
+ throw makeHttpError(400, "generation kind must be commit, branch, or pr");
1700
+ }
1579
1701
  }
1580
1702
 
1581
- async function saveRemoteAuthPreference(enabled) {
1582
- const nextEnabled = enabled === true;
1583
- await writeWebuiSettings({ remoteAuthEnabled: nextEnabled });
1584
- persistedRemoteAuthEnabled = nextEnabled;
1585
- return persistedRemoteAuthEnabled;
1703
+ async function restoreGitWorkflowGenerationProfile(tab) {
1704
+ const restore = tab?.gitWorkflowGenerationRestore;
1705
+ if (!restore) return;
1706
+ tab.gitWorkflowGenerationRestore = null;
1707
+ try {
1708
+ if (!tab.rpc?.isRunning?.()) return;
1709
+ if (restore.model?.provider && restore.model?.id) {
1710
+ const modelResponse = await tab.rpc.send({ type: "set_model", provider: restore.model.provider, modelId: restore.model.id });
1711
+ if (modelResponse.success === false) throw new Error(modelResponse.error || "Failed to restore model");
1712
+ }
1713
+ if (restore.thinkingLevel) {
1714
+ const thinkingResponse = await setThinkingLevelForTab(tab, restore.thinkingLevel, { allowPending: false });
1715
+ if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || "Failed to restore thinking level");
1716
+ }
1717
+ recordEvent({ type: "git_workflow_generation_profile_restored", tabId: tab.id, tabTitle: tab.title });
1718
+ } catch (error) {
1719
+ recordEvent({ type: "git_workflow_generation_profile_restore_failed", tabId: tab.id, tabTitle: tab.title, error: sanitizeError(error) });
1720
+ }
1721
+ }
1722
+
1723
+ async function startGitWorkflowGeneration(tab, body = {}) {
1724
+ if (tab.gitWorkflowGenerationRestore) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
1725
+ const preferences = await readGitWorkflowPreferences();
1726
+ if (!isGitWorkflowSetupComplete(preferences)) throw makeHttpError(409, "Run /git-workflow-setup or open Guided Git Setup before generating Git text");
1727
+
1728
+ const state = await currentSessionState(tab);
1729
+ if (stateIsBusyForSettings(state)) throw makeHttpError(409, "Wait for the current agent run to finish before generating Git text");
1730
+ const models = await availableGitWorkflowModels(tab);
1731
+ const selectedModel = models.find((model) => model.provider === preferences.generation.provider && model.id === preferences.generation.modelId);
1732
+ if (!selectedModel) throw makeHttpError(409, `Configured Git-writing model is unavailable: ${preferences.generation.provider}/${preferences.generation.modelId}. Open Guided Git Setup to choose another model.`);
1733
+ const supportedLevels = supportedGitWorkflowThinkingLevels(selectedModel);
1734
+ if (!supportedLevels.includes(preferences.generation.thinkingLevel)) {
1735
+ throw makeHttpError(409, `Configured thinking level ${preferences.generation.thinkingLevel} is unavailable for ${gitWorkflowModelKey(selectedModel)}. Open Guided Git Setup to update it.`);
1736
+ }
1737
+
1738
+ const restore = { model: state.model || null, thinkingLevel: state.thinkingLevel || "off" };
1739
+ tab.gitWorkflowGenerationRestore = restore;
1740
+ try {
1741
+ if (gitWorkflowModelKey(state.model) !== gitWorkflowModelKey(selectedModel)) {
1742
+ const modelResponse = await tab.rpc.send({ type: "set_model", provider: selectedModel.provider, modelId: selectedModel.id });
1743
+ if (modelResponse.success === false) throw new Error(modelResponse.error || `Failed to select ${gitWorkflowModelKey(selectedModel)}`);
1744
+ }
1745
+ const thinkingResponse = await setThinkingLevelForTab(tab, preferences.generation.thinkingLevel, { allowPending: false });
1746
+ if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || `Failed to select thinking level ${preferences.generation.thinkingLevel}`);
1747
+
1748
+ const kind = String(body.kind || "").trim();
1749
+ const message = gitWorkflowGenerationPrompt(kind, preferences);
1750
+ markTabWorking(tab);
1751
+ const response = await tab.rpc.send({ type: "prompt", message });
1752
+ if (response.success === false) throw new Error(response.error || "Guided Git generation prompt was rejected");
1753
+ return {
1754
+ accepted: true,
1755
+ kind,
1756
+ message,
1757
+ generation: {
1758
+ provider: selectedModel.provider,
1759
+ modelId: selectedModel.id,
1760
+ thinkingLevel: preferences.generation.thinkingLevel,
1761
+ },
1762
+ };
1763
+ } catch (error) {
1764
+ markTabIdle(tab);
1765
+ await restoreGitWorkflowGenerationProfile(tab);
1766
+ throw error;
1767
+ }
1586
1768
  }
1587
1769
 
1588
1770
  function parseCliScopedModelPatterns() {
@@ -3943,23 +4125,30 @@ let activeGitWorkflowProcess = null;
3943
4125
  const GIT_CHANGES_COMMAND_TIMEOUT_MS = 5000;
3944
4126
  const GIT_CHANGES_DIFF_MAX_OUTPUT = 500_000;
3945
4127
  const GIT_PULL_TIMEOUT_MS = 15 * 60 * 1000;
4128
+ const GIT_STATUS_KIND_RANK = Object.freeze({ changed: 0, untracked: 1, modified: 2, staged: 3, conflicted: 4 });
3946
4129
 
3947
4130
  async function getGitRoot(cwd) {
3948
4131
  const result = await runCommand("git", ["rev-parse", "--show-toplevel"], { cwd, timeoutMs: 2000 });
3949
4132
  if (result.exitCode !== 0) {
3950
- throw new Error((result.stderr || result.stdout || "Not inside a git repository").trim());
4133
+ throw makeUserFacingError((result.stderr || result.stdout || "Not inside a git repository").trim());
3951
4134
  }
3952
4135
  return path.resolve(result.stdout.trim());
3953
4136
  }
3954
4137
 
3955
- async function runGitReadCommand(root, args, { timeoutMs = GIT_CHANGES_COMMAND_TIMEOUT_MS, maxOutputLength = GIT_CHANGES_DIFF_MAX_OUTPUT } = {}) {
4138
+ async function runGitReadCommandDetailed(root, args, { timeoutMs = GIT_CHANGES_COMMAND_TIMEOUT_MS, maxOutputLength = GIT_CHANGES_DIFF_MAX_OUTPUT } = {}) {
3956
4139
  const result = await runCommand("git", args, { cwd: root, timeoutMs, maxOutputLength });
3957
- if (result.exitCode === 0 && !result.timedOut && !result.error) return result.stdout;
4140
+ if (result.exitCode === 0 && !result.timedOut && !result.error) {
4141
+ return { output: result.stdout, truncated: result.stdoutTruncated === true, capBytes: maxOutputLength };
4142
+ }
3958
4143
  const command = formatGitCommand(args);
3959
4144
  const message = result.timedOut
3960
4145
  ? `${command} timed out`
3961
4146
  : (result.stderr || result.stdout || result.error || `${command} failed with exit code ${result.exitCode ?? "unknown"}`);
3962
- throw new Error(String(message).trim());
4147
+ throw makeUserFacingError(String(message).trim());
4148
+ }
4149
+
4150
+ async function runGitReadCommand(root, args, options = {}) {
4151
+ return (await runGitReadCommandDetailed(root, args, options)).output;
3963
4152
  }
3964
4153
 
3965
4154
  function gitBranchFromPorcelainStatus(statusText) {
@@ -4003,6 +4192,118 @@ function summarizeGitPorcelainStatus(statusText) {
4003
4192
  return summary;
4004
4193
  }
4005
4194
 
4195
+ function normalizeGitStatusPath(value = "") {
4196
+ return String(value || "").replace(/\\/g, "/").replace(/^\.\/+/, "").replace(/\/+$/g, "");
4197
+ }
4198
+
4199
+ function gitStatusKindFromPorcelainEntry(entry = {}) {
4200
+ const x = entry.x || " ";
4201
+ const y = entry.y || " ";
4202
+ if (x === "?" && y === "?") return "untracked";
4203
+ if (x === "U" || y === "U" || (x === "A" && y === "A") || (x === "D" && y === "D")) return "conflicted";
4204
+ if (x !== " " && x !== "?" && x !== ".") return "staged";
4205
+ if (y !== " " && y !== "?" && y !== ".") return "modified";
4206
+ return "changed";
4207
+ }
4208
+
4209
+ function gitStatusLabelFromPorcelainEntry(entry = {}) {
4210
+ const x = entry.x || " ";
4211
+ const y = entry.y || " ";
4212
+ if (x === "?" && y === "?") return "??";
4213
+ return `${x}${y}`.replace(/\s/g, "").trim() || "•";
4214
+ }
4215
+
4216
+ function mergeGitStatusIndexEntry(index, repoPath, patch = {}) {
4217
+ const key = normalizeGitStatusPath(repoPath);
4218
+ if (!key) return;
4219
+ const existing = index.get(key) || { changed: true, kind: "changed", status: "", direct: false, changedDescendants: 0 };
4220
+ const existingRank = GIT_STATUS_KIND_RANK[existing.kind] ?? 0;
4221
+ const nextRank = GIT_STATUS_KIND_RANK[patch.kind] ?? 0;
4222
+ index.set(key, {
4223
+ changed: true,
4224
+ kind: nextRank > existingRank ? patch.kind : existing.kind,
4225
+ status: patch.direct === true ? (patch.status || existing.status || "") : (existing.status || ""),
4226
+ direct: existing.direct === true || patch.direct === true,
4227
+ changedDescendants: (Number(existing.changedDescendants || 0) || 0) + (Number(patch.changedDescendants || 0) || 0),
4228
+ });
4229
+ }
4230
+
4231
+ function addGitStatusAncestorEntries(index, repoPath, kind) {
4232
+ const parts = normalizeGitStatusPath(repoPath).split("/").filter(Boolean);
4233
+ parts.pop();
4234
+ let current = "";
4235
+ for (const part of parts) {
4236
+ current = current ? `${current}/${part}` : part;
4237
+ mergeGitStatusIndexEntry(index, current, { kind, changedDescendants: 1 });
4238
+ }
4239
+ }
4240
+
4241
+ function buildGitStatusIndexFromPorcelain(statusText = "") {
4242
+ const index = new Map();
4243
+ for (const entry of parseGitPorcelainZEntries(statusText)) {
4244
+ const filePath = normalizeGitStatusPath(entry.path);
4245
+ if (!filePath) continue;
4246
+ const kind = gitStatusKindFromPorcelainEntry(entry);
4247
+ mergeGitStatusIndexEntry(index, filePath, { kind, status: gitStatusLabelFromPorcelainEntry(entry), direct: true });
4248
+ addGitStatusAncestorEntries(index, filePath, kind);
4249
+ if (entry.oldPath) addGitStatusAncestorEntries(index, entry.oldPath, kind);
4250
+ }
4251
+ return index;
4252
+ }
4253
+
4254
+ async function readWorkspaceGitStatusIndex(workspaceRoot) {
4255
+ try {
4256
+ const root = await getGitRoot(workspaceRoot);
4257
+ const statusText = await runGitReadCommand(root, ["status", "--porcelain=v1", "-z", "--untracked-files=all"], { maxOutputLength: 120_000 });
4258
+ return { root, entries: buildGitStatusIndexFromPorcelain(statusText) };
4259
+ } catch {
4260
+ return null;
4261
+ }
4262
+ }
4263
+
4264
+ function gitStatusForWorkspaceEntry(workspaceRoot, entry, gitStatus) {
4265
+ if (!gitStatus?.root || !gitStatus.entries?.size || !entry?.path) return null;
4266
+ const absolute = path.resolve(workspaceRoot, entry.path);
4267
+ if (absolute !== gitStatus.root && !pathInside(gitStatus.root, absolute)) return null;
4268
+ const repoPath = normalizeGitStatusPath(path.relative(gitStatus.root, absolute).split(path.sep).join("/"));
4269
+ const status = gitStatus.entries.get(repoPath);
4270
+ if (!status?.changed) return null;
4271
+ return {
4272
+ changed: true,
4273
+ kind: status.kind || "changed",
4274
+ status: status.status || "",
4275
+ direct: status.direct === true,
4276
+ changedDescendants: Number(status.changedDescendants || 0) || 0,
4277
+ };
4278
+ }
4279
+
4280
+ function withFileTreeGitStatus(entries = [], workspaceRoot, gitStatus) {
4281
+ if (!gitStatus?.entries?.size) return entries;
4282
+ return entries.map((entry) => {
4283
+ const status = gitStatusForWorkspaceEntry(workspaceRoot, entry, gitStatus);
4284
+ return status ? { ...entry, gitStatus: status } : entry;
4285
+ });
4286
+ }
4287
+
4288
+ function fileTreeGitStatusPayload(workspaceRoot, gitStatus) {
4289
+ if (!gitStatus?.root || !gitStatus.entries?.size) return null;
4290
+ const root = path.resolve(workspaceRoot);
4291
+ const entries = [];
4292
+ for (const [repoPath, status] of gitStatus.entries.entries()) {
4293
+ const absolute = path.resolve(gitStatus.root, repoPath);
4294
+ if (absolute !== root && !pathInside(root, absolute)) continue;
4295
+ entries.push({
4296
+ path: path.relative(root, absolute).split(path.sep).join("/"),
4297
+ changed: true,
4298
+ kind: status.kind || "changed",
4299
+ status: status.status || "",
4300
+ direct: status.direct === true,
4301
+ changedDescendants: Number(status.changedDescendants || 0) || 0,
4302
+ });
4303
+ }
4304
+ return { root: gitStatus.root, entries };
4305
+ }
4306
+
4006
4307
  function resolveGitRelativePath(root, relativePath) {
4007
4308
  const normalized = String(relativePath || "").trim();
4008
4309
  if (!normalized || normalized.includes("\0")) throw new Error("Invalid git path");
@@ -4067,23 +4368,31 @@ async function gitUpstreamRef(root) {
4067
4368
 
4068
4369
  async function readGitIncomingChanges(root, summary) {
4069
4370
  const upstream = await gitUpstreamRef(root);
4371
+ const ahead = Number(summary?.ahead || 0) || 0;
4372
+ const behind = Number(summary?.behind || 0) || 0;
4373
+ const diverged = ahead > 0 && behind > 0;
4070
4374
  const remote = {
4071
4375
  upstream,
4072
- behind: Number(summary?.behind || 0) || 0,
4073
- canPull: !!upstream && (Number(summary?.behind || 0) || 0) > 0,
4376
+ ahead,
4377
+ behind,
4378
+ diverged,
4379
+ // Fast-forward pull is only possible when we are strictly behind.
4380
+ canPull: !!upstream && behind > 0 && !diverged,
4074
4381
  };
4075
- if (!remote.canPull) return { remote, section: null };
4382
+ if (!upstream || behind <= 0) return { remote, section: null };
4076
4383
 
4077
4384
  const diffArgs = ["diff", "--no-ext-diff", "--no-color", "--find-renames", "--unified=0", "--src-prefix=a/", "--dst-prefix=b/", "HEAD..@{upstream}"];
4078
4385
  try {
4079
- const diff = await runGitReadCommand(root, diffArgs);
4386
+ const diff = await runGitReadCommandDetailed(root, diffArgs);
4080
4387
  return {
4081
4388
  remote,
4082
4389
  section: {
4083
4390
  key: "incoming",
4084
4391
  label: `Incoming from ${upstream}`,
4085
4392
  command: `git diff --unified=0 HEAD..${upstream}`,
4086
- diff: diff.trimEnd(),
4393
+ diff: diff.output.trimEnd(),
4394
+ truncated: diff.truncated,
4395
+ capBytes: diff.capBytes,
4087
4396
  },
4088
4397
  };
4089
4398
  } catch (error) {
@@ -4093,10 +4402,13 @@ async function readGitIncomingChanges(root, summary) {
4093
4402
 
4094
4403
  async function pullGitChanges(cwd) {
4095
4404
  const root = await getGitRoot(cwd);
4096
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(["pull", "--ff-only"], { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS }));
4405
+ const payload = await runGuardedGitMutation(["pull", "--ff-only"], { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS });
4097
4406
  if (payload.data) payload.data.root = root;
4098
4407
  if (payload.ok) payload.data.changes = await readGitChanges(root);
4099
- else payload.error = (payload.data?.stderr || payload.data?.stdout || payload.error || "git pull --ff-only failed").trim();
4408
+ else {
4409
+ payload.error = (payload.data?.stderr || payload.data?.stdout || payload.error || "git pull --ff-only failed").trim();
4410
+ applyGitSyncFailure(payload);
4411
+ }
4100
4412
  return payload;
4101
4413
  }
4102
4414
 
@@ -4106,8 +4418,8 @@ async function readGitChanges(cwd) {
4106
4418
  const [statusText, porcelainStatusText, unstagedDiff, stagedDiff, untrackedText] = await Promise.all([
4107
4419
  runGitReadCommand(root, ["status", "--short", "--branch", "--untracked-files=all"], { maxOutputLength: 120_000 }),
4108
4420
  runGitReadCommand(root, ["status", "--porcelain=2", "--branch", "--untracked-files=all"], { maxOutputLength: 120_000 }),
4109
- runGitReadCommand(root, diffArgs),
4110
- runGitReadCommand(root, ["diff", "--cached", "--no-ext-diff", "--no-color", "--find-renames", "--unified=0", "--src-prefix=a/", "--dst-prefix=b/"]),
4421
+ runGitReadCommandDetailed(root, diffArgs),
4422
+ runGitReadCommandDetailed(root, ["diff", "--cached", "--no-ext-diff", "--no-color", "--find-renames", "--unified=0", "--src-prefix=a/", "--dst-prefix=b/"]),
4111
4423
  runGitReadCommand(root, ["ls-files", "--others", "--exclude-standard"], { maxOutputLength: 120_000 }),
4112
4424
  ]);
4113
4425
  const summary = summarizeGitPorcelainStatus(porcelainStatusText);
@@ -4124,13 +4436,670 @@ async function readGitChanges(cwd) {
4124
4436
  status: statusText.trimEnd(),
4125
4437
  sections: [
4126
4438
  incoming.section,
4127
- { key: "staged", label: "Staged", command: "git diff --cached --unified=0", diff: stagedDiff.trimEnd() },
4128
- { key: "unstaged", label: "Unstaged", command: "git diff --unified=0", diff: unstagedDiff.trimEnd() },
4439
+ { key: "staged", label: "Staged", command: "git diff --cached --unified=0", diff: stagedDiff.output.trimEnd(), truncated: stagedDiff.truncated, capBytes: stagedDiff.capBytes },
4440
+ { key: "unstaged", label: "Unstaged", command: "git diff --unified=0", diff: unstagedDiff.output.trimEnd(), truncated: unstagedDiff.truncated, capBytes: unstagedDiff.capBytes },
4129
4441
  ].filter(Boolean),
4130
4442
  untracked,
4131
4443
  };
4132
4444
  }
4133
4445
 
4446
+ const GIT_LOCK_RETRY_ATTEMPTS = 3;
4447
+ const GIT_LOCK_RETRY_DELAY_MS = 250;
4448
+ const GIT_FETCH_TIMEOUT_MS = 2 * 60 * 1000;
4449
+ const GIT_CONFLICT_PREVIEW_MAX_BYTES = 200_000;
4450
+ const GIT_STASH_PATCH_MAX_OUTPUT = 200_000;
4451
+ const PROTECTED_GIT_BRANCHES = new Set(["main", "master"]);
4452
+
4453
+ const sleepMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4454
+
4455
+ function requireConfirmed(body, action) {
4456
+ if (body?.confirmed !== true) throw makeHttpError(409, `${action} requires confirmed: true.`);
4457
+ }
4458
+
4459
+ // Retry transient index.lock contention before reporting failure; the shared
4460
+ // isGitLockFailure classifier keeps this consistent with worktree mutations.
4461
+ async function runGitMutationCommand(args, options = {}) {
4462
+ let result;
4463
+ for (let attempt = 0; attempt < GIT_LOCK_RETRY_ATTEMPTS; attempt++) {
4464
+ result = await runGitWorkflowCommand(args, options);
4465
+ const ok = result.exitCode === 0 && !result.timedOut && !result.cancelled && !result.error;
4466
+ if (ok || !isGitLockFailure(result)) return result;
4467
+ if (attempt < GIT_LOCK_RETRY_ATTEMPTS - 1) await sleepMs(GIT_LOCK_RETRY_DELAY_MS * (attempt + 1));
4468
+ }
4469
+ return result;
4470
+ }
4471
+
4472
+ function gitMutationPayload(result) {
4473
+ const payload = gitWorkflowCommandPayload(result);
4474
+ if (!payload.ok) {
4475
+ if (isGitLockFailure(result)) {
4476
+ payload.code = "REPO_BUSY";
4477
+ payload.hint = "Another git process is using this repository. Retry once it finishes.";
4478
+ }
4479
+ payload.error = String(result?.stderr || result?.stdout || payload.error || "git command failed").trim();
4480
+ }
4481
+ return payload;
4482
+ }
4483
+
4484
+ async function runGuardedGitMutation(args, options = {}) {
4485
+ try {
4486
+ return gitMutationPayload(await runGitMutationCommand(args, options));
4487
+ } catch (error) {
4488
+ if (/already running/i.test(error?.message || "")) {
4489
+ return { ok: false, code: "REPO_BUSY", error: sanitizeError(error), hint: "Another git workflow command is already running in the Web UI." };
4490
+ }
4491
+ throw error;
4492
+ }
4493
+ }
4494
+
4495
+ // Turn raw git remote-operation stderr into an actionable state. Returns null
4496
+ // when no known pattern matches (caller keeps the raw error).
4497
+ function classifyGitSyncFailure(result, { push = false } = {}) {
4498
+ const text = `${result?.stderr || ""}\n${result?.stdout || ""}`.toLowerCase();
4499
+ if (result?.timedOut) return { code: "NETWORK", hint: "The remote did not respond before the timeout. Check connectivity and retry." };
4500
+ if (isGitLockFailure(result)) return { code: "REPO_BUSY", hint: "Another git process is using this repository. Retry once it finishes." };
4501
+ if (/terminal prompts disabled|authentication failed|permission denied|access denied|could not read username|could not read password|publickey|invalid credentials/.test(text)) {
4502
+ return { code: "AUTH", hint: "Authentication failed and interactive prompts are disabled in the Web UI. Refresh your credentials or SSH agent in a terminal, then retry." };
4503
+ }
4504
+ if (/could not resolve host|failed to connect|connection (?:refused|reset|timed out)|network is unreachable|operation timed out/.test(text)) {
4505
+ return { code: "NETWORK", hint: "The remote could not be reached. Check connectivity and retry." };
4506
+ }
4507
+ if (push && /protected branch|gh006/.test(text)) {
4508
+ return { code: "PROTECTED_BRANCH", hint: "The remote refused the push because the branch is protected. Push to a feature branch and open a PR instead." };
4509
+ }
4510
+ if (push && /\[rejected\]|non-fast-forward|fetch first|updates were rejected/.test(text)) {
4511
+ return { code: "NON_FAST_FORWARD", hint: "The remote has commits you don't have. Fetch and review the incoming diff, then integrate before pushing." };
4512
+ }
4513
+ if (push && /has no upstream branch/.test(text)) {
4514
+ return { code: "NO_UPSTREAM", hint: "The current branch has no upstream. Push with 'set upstream' to publish it." };
4515
+ }
4516
+ if (!push && /not possible to fast-forward|divergent branches|need to specify how to reconcile/.test(text)) {
4517
+ return { code: "DIVERGED", hint: "Local and remote branches have diverged. Fetch, review the incoming diff, then merge or rebase explicitly — or integrate in a worktree." };
4518
+ }
4519
+ if (!push && /no tracking information/.test(text)) {
4520
+ return { code: "NO_UPSTREAM", hint: "The current branch has no upstream to pull from. Set one or pull with an explicit remote/branch." };
4521
+ }
4522
+ if (/would be overwritten/.test(text)) {
4523
+ return { code: "DIRTY_WORKTREE", hint: "Local changes would be overwritten. Stash or commit them first." };
4524
+ }
4525
+ if (/conflict/.test(text)) {
4526
+ return { code: "CONFLICTS", hint: "Conflicts were created. Resolve them in the conflicts panel, then continue or abort the operation." };
4527
+ }
4528
+ return null;
4529
+ }
4530
+
4531
+ function applyGitSyncFailure(payload, { push = false } = {}) {
4532
+ if (payload.ok || payload.code) return payload;
4533
+ const classified = classifyGitSyncFailure(payload.data, { push });
4534
+ if (classified) {
4535
+ payload.code = classified.code;
4536
+ payload.hint = classified.hint;
4537
+ }
4538
+ return payload;
4539
+ }
4540
+
4541
+ async function fetchGitChanges(cwd) {
4542
+ const root = await getGitRoot(cwd);
4543
+ const payload = await runGuardedGitMutation(
4544
+ ["-c", "credential.interactive=false", "fetch", "--prune"],
4545
+ { cwd: root, timeoutMs: GIT_FETCH_TIMEOUT_MS, label: "git fetch --prune" },
4546
+ );
4547
+ if (payload.data) payload.data.root = root;
4548
+ if (payload.ok) {
4549
+ // git fetch reports ref updates on stderr.
4550
+ payload.data.summary = `${payload.data.stderr || ""}\n${payload.data.stdout || ""}`.trim();
4551
+ payload.data.changes = await readGitChanges(root);
4552
+ } else {
4553
+ applyGitSyncFailure(payload);
4554
+ }
4555
+ return payload;
4556
+ }
4557
+
4558
+ async function integrateGitUpstream(cwd, body = {}) {
4559
+ const mode = String(body.mode || "").trim();
4560
+ if (!["merge", "rebase"].includes(mode)) throw makeHttpError(400, "mode must be 'merge' or 'rebase'");
4561
+ requireConfirmed(body, `Running git ${mode} against the upstream`);
4562
+ const root = await getGitRoot(cwd);
4563
+ const upstream = await gitUpstreamRef(root);
4564
+ if (!upstream) throw makeHttpError(409, "No upstream is configured for the current branch");
4565
+ const args = mode === "merge" ? ["merge", "--no-edit", "@{upstream}"] : ["-c", "core.editor=true", "rebase", "@{upstream}"];
4566
+ const payload = await runGuardedGitMutation(args, { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS, label: `git ${mode} ${upstream}` });
4567
+ if (payload.data) {
4568
+ payload.data.root = root;
4569
+ payload.data.upstream = upstream;
4570
+ payload.data.mode = mode;
4571
+ }
4572
+ if (payload.ok) payload.data.changes = await readGitChanges(root);
4573
+ else applyGitSyncFailure(payload);
4574
+ return payload;
4575
+ }
4576
+
4577
+ // ---- Git operation (merge/rebase/cherry-pick/revert/bisect) lifecycle ----
4578
+
4579
+ async function pathEntryExists(target) {
4580
+ try {
4581
+ await stat(target);
4582
+ return true;
4583
+ } catch {
4584
+ return false;
4585
+ }
4586
+ }
4587
+
4588
+ async function gitDirPath(root) {
4589
+ const out = await runGitReadCommand(root, ["rev-parse", "--git-dir"], { maxOutputLength: 10_000 });
4590
+ const dir = out.trim();
4591
+ return path.isAbsolute(dir) ? dir : path.resolve(root, dir);
4592
+ }
4593
+
4594
+ async function detectGitOperationKind(root) {
4595
+ const gitDir = await gitDirPath(root);
4596
+ if ((await pathEntryExists(path.join(gitDir, "rebase-merge"))) || (await pathEntryExists(path.join(gitDir, "rebase-apply")))) return "rebase";
4597
+ if (await pathEntryExists(path.join(gitDir, "MERGE_HEAD"))) return "merge";
4598
+ if (await pathEntryExists(path.join(gitDir, "CHERRY_PICK_HEAD"))) return "cherry-pick";
4599
+ if (await pathEntryExists(path.join(gitDir, "REVERT_HEAD"))) return "revert";
4600
+ if (await pathEntryExists(path.join(gitDir, "BISECT_LOG"))) return "bisect";
4601
+ return null;
4602
+ }
4603
+
4604
+ function gitOperationCommands(kind) {
4605
+ switch (kind) {
4606
+ case "merge":
4607
+ return { continue: ["commit", "--no-edit"], abort: ["merge", "--abort"], skip: null };
4608
+ case "rebase":
4609
+ return { continue: ["-c", "core.editor=true", "rebase", "--continue"], abort: ["rebase", "--abort"], skip: ["-c", "core.editor=true", "rebase", "--skip"] };
4610
+ case "cherry-pick":
4611
+ return { continue: ["-c", "core.editor=true", "cherry-pick", "--continue"], abort: ["cherry-pick", "--abort"], skip: ["-c", "core.editor=true", "cherry-pick", "--skip"] };
4612
+ case "revert":
4613
+ return { continue: ["-c", "core.editor=true", "revert", "--continue"], abort: ["revert", "--abort"], skip: ["-c", "core.editor=true", "revert", "--skip"] };
4614
+ default:
4615
+ return null;
4616
+ }
4617
+ }
4618
+
4619
+ function parseGitConflictEntries(porcelainText) {
4620
+ const entries = [];
4621
+ for (const line of String(porcelainText || "").split(/\r?\n/)) {
4622
+ if (!line.startsWith("u ")) continue;
4623
+ // u XY sub m1 m2 m3 mW h1 h2 h3 path — 10 space-separated fields, then path.
4624
+ const fields = [];
4625
+ let start = 0;
4626
+ for (let index = 0; index < 10; index++) {
4627
+ const next = line.indexOf(" ", start);
4628
+ if (next === -1) break;
4629
+ fields.push(line.slice(start, next));
4630
+ start = next + 1;
4631
+ }
4632
+ fields.push(line.slice(start));
4633
+ const entryPath = fields[10] || "";
4634
+ if (entryPath) entries.push({ path: entryPath, status: fields[1] || "UU" });
4635
+ }
4636
+ return entries;
4637
+ }
4638
+
4639
+ function extractConflictMarkerHunks(content, { contextLines = 2, maxHunks = 8, maxLinesPerHunk = 80 } = {}) {
4640
+ const lines = content.split(/\r?\n/);
4641
+ const hunks = [];
4642
+ for (let index = 0; index < lines.length && hunks.length < maxHunks; index++) {
4643
+ if (!lines[index].startsWith("<<<<<<<")) continue;
4644
+ let end = index;
4645
+ while (end < lines.length - 1 && !lines[end].startsWith(">>>>>>>")) end++;
4646
+ const start = Math.max(0, index - contextLines);
4647
+ const stop = Math.min(lines.length - 1, end + contextLines);
4648
+ hunks.push({
4649
+ startLine: start + 1,
4650
+ truncated: stop - start + 1 > maxLinesPerHunk,
4651
+ lines: lines.slice(start, Math.min(stop + 1, start + maxLinesPerHunk)),
4652
+ });
4653
+ index = end;
4654
+ }
4655
+ return hunks;
4656
+ }
4657
+
4658
+ async function readGitConflictPreview(root, relPath) {
4659
+ try {
4660
+ const filePath = resolveGitRelativePath(root, relPath);
4661
+ const info = await stat(filePath).catch(() => null);
4662
+ if (!info) return { kind: "missing" };
4663
+ if (!info.isFile()) return { kind: "unsupported", size: info.size };
4664
+ if (info.size > GIT_CONFLICT_PREVIEW_MAX_BYTES) return { kind: "large", size: info.size };
4665
+ const buffer = await readFile(filePath);
4666
+ if (isLikelyBinaryBuffer(buffer)) return { kind: "binary", size: info.size };
4667
+ const content = buffer.toString("utf8");
4668
+ return {
4669
+ kind: "text",
4670
+ size: info.size,
4671
+ hasMarkers: /^<{7}(?: |$)/m.test(content),
4672
+ hunks: extractConflictMarkerHunks(content),
4673
+ };
4674
+ } catch (error) {
4675
+ return { kind: "error", error: sanitizeError(error) };
4676
+ }
4677
+ }
4678
+
4679
+ async function readGitOperationSnapshot(cwd) {
4680
+ const root = await getGitRoot(cwd);
4681
+ const porcelainText = await runGitReadCommand(root, ["status", "--porcelain=2", "--branch", "--untracked-files=all"], { maxOutputLength: 120_000 });
4682
+ const summary = summarizeGitPorcelainStatus(porcelainText);
4683
+ const kind = await detectGitOperationKind(root);
4684
+ const conflictEntries = parseGitConflictEntries(porcelainText);
4685
+ const conflicts = [];
4686
+ for (const entry of conflictEntries) {
4687
+ conflicts.push({ ...entry, preview: await readGitConflictPreview(root, entry.path) });
4688
+ }
4689
+ const commands = gitOperationCommands(kind);
4690
+ let bisect = null;
4691
+ if (kind === "bisect") {
4692
+ const log = await runGitReadCommand(root, ["bisect", "log"], { maxOutputLength: 60_000 }).catch(() => "");
4693
+ bisect = { log: log.trimEnd().split(/\r?\n/).slice(-20).join("\n") };
4694
+ }
4695
+ return {
4696
+ root,
4697
+ branch: gitBranchFromPorcelainStatus(porcelainText),
4698
+ operation: kind,
4699
+ summary,
4700
+ conflicts,
4701
+ canContinue: Boolean(kind) && kind !== "bisect" && conflictEntries.length === 0,
4702
+ canSkip: Boolean(commands?.skip),
4703
+ commands: commands
4704
+ ? {
4705
+ continue: formatGitCommand(commands.continue.filter((arg) => arg !== "-c" && arg !== "core.editor=true")),
4706
+ abort: formatGitCommand(commands.abort),
4707
+ ...(commands.skip ? { skip: formatGitCommand(commands.skip.filter((arg) => arg !== "-c" && arg !== "core.editor=true")) } : {}),
4708
+ }
4709
+ : null,
4710
+ bisect,
4711
+ generatedAt: new Date().toISOString(),
4712
+ };
4713
+ }
4714
+
4715
+ async function gitOperationStageFile(cwd, body = {}) {
4716
+ const root = await getGitRoot(cwd);
4717
+ const kind = await detectGitOperationKind(root);
4718
+ if (!kind) throw makeHttpError(409, "No git operation is in progress");
4719
+ const rel = normalizeGitRelativePath(root, body.path);
4720
+ const payload = await runGuardedGitMutation(["add", "--", rel], { cwd: root, label: `git add -- ${rel}` });
4721
+ if (payload.data) payload.data.root = root;
4722
+ if (payload.ok) payload.data.operation = await readGitOperationSnapshot(root);
4723
+ return payload;
4724
+ }
4725
+
4726
+ async function gitOperationAction(cwd, action, body = {}) {
4727
+ const root = await getGitRoot(cwd);
4728
+ const kind = await detectGitOperationKind(root);
4729
+ if (!kind) throw makeHttpError(409, "No git operation is in progress");
4730
+ if (kind === "bisect") throw makeHttpError(409, "Bisect is controlled through /api/git-operation/bisect");
4731
+ const commands = gitOperationCommands(kind);
4732
+
4733
+ let args;
4734
+ if (action === "continue") {
4735
+ const porcelainText = await runGitReadCommand(root, ["status", "--porcelain=2"], { maxOutputLength: 120_000 });
4736
+ if (parseGitConflictEntries(porcelainText).length > 0) {
4737
+ return { ok: false, code: "UNMERGED_PATHS", error: "Unmerged paths remain. Resolve and stage every conflicted file before continuing." };
4738
+ }
4739
+ args = commands.continue;
4740
+ } else if (action === "skip") {
4741
+ if (!commands.skip) throw makeHttpError(409, `git ${kind} does not support skip`);
4742
+ args = commands.skip;
4743
+ } else if (action === "abort") {
4744
+ requireConfirmed(body, `Aborting the ${kind} operation discards its in-progress state and`);
4745
+ args = commands.abort;
4746
+ } else {
4747
+ throw makeHttpError(400, "Unknown git operation action");
4748
+ }
4749
+
4750
+ const payload = await runGuardedGitMutation(args, { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS });
4751
+ if (payload.data) {
4752
+ payload.data.root = root;
4753
+ payload.data.kind = kind;
4754
+ }
4755
+ if (payload.ok) payload.data.operation = await readGitOperationSnapshot(root);
4756
+ else applyGitSyncFailure(payload);
4757
+ return payload;
4758
+ }
4759
+
4760
+ const GIT_BISECT_VERDICTS = new Set(["good", "bad", "old", "new", "skip", "reset"]);
4761
+
4762
+ async function gitBisectAction(cwd, body = {}) {
4763
+ const verdict = String(body.verdict || "").trim().toLowerCase();
4764
+ if (!GIT_BISECT_VERDICTS.has(verdict)) throw makeHttpError(400, "verdict must be one of good, bad, old, new, skip, reset");
4765
+ const root = await getGitRoot(cwd);
4766
+ const kind = await detectGitOperationKind(root);
4767
+ if (kind !== "bisect") throw makeHttpError(409, "No git bisect is in progress");
4768
+ if (verdict === "reset") requireConfirmed(body, "Resetting the bisect session");
4769
+ const payload = await runGuardedGitMutation(["bisect", verdict], { cwd: root });
4770
+ if (payload.data) payload.data.root = root;
4771
+ if (payload.ok) payload.data.operation = await readGitOperationSnapshot(root);
4772
+ return payload;
4773
+ }
4774
+
4775
+ // ---- Stash ----
4776
+
4777
+ function cleanGitStashRef(value) {
4778
+ const ref = String(value || "").trim();
4779
+ if (!/^stash@\{\d{1,4}\}$/.test(ref)) throw makeHttpError(400, "stash ref must look like stash@{0}");
4780
+ return ref;
4781
+ }
4782
+
4783
+ async function readGitStashes(cwd) {
4784
+ const root = await getGitRoot(cwd);
4785
+ const out = await runGitReadCommand(root, ["stash", "list", "--format=%gd%x09%at%x09%gs"], { maxOutputLength: 120_000 });
4786
+ const stashes = out
4787
+ .split(/\r?\n/)
4788
+ .filter(Boolean)
4789
+ .map((line) => {
4790
+ const [ref, epoch, ...subject] = line.split("\t");
4791
+ return { ref: ref || "", epochSeconds: Number.parseInt(epoch || "0", 10) || 0, subject: subject.join("\t") };
4792
+ })
4793
+ .filter((entry) => entry.ref);
4794
+ return { root, stashes, generatedAt: new Date().toISOString() };
4795
+ }
4796
+
4797
+ async function readGitStashPreview(cwd, requestedRef) {
4798
+ const root = await getGitRoot(cwd);
4799
+ const ref = cleanGitStashRef(requestedRef);
4800
+ const [statText, patchText] = await Promise.all([
4801
+ runGitReadCommand(root, ["stash", "show", "--include-untracked", "--stat", ref], { maxOutputLength: 120_000 }).catch((error) => `(${sanitizeError(error)})`),
4802
+ runGitReadCommand(root, ["stash", "show", "--include-untracked", "-p", ref], { maxOutputLength: GIT_STASH_PATCH_MAX_OUTPUT }).catch(() => ""),
4803
+ ]);
4804
+ return { root, ref, stat: statText.trimEnd(), patch: patchText.trimEnd() };
4805
+ }
4806
+
4807
+ async function saveGitStash(cwd, body = {}) {
4808
+ const root = await getGitRoot(cwd);
4809
+ const args = ["stash", "push"];
4810
+ if (body.includeUntracked === true) args.push("--include-untracked");
4811
+ if (body.message) args.push("-m", cleanGitCommitMessageInput(body.message));
4812
+ const payload = await runGuardedGitMutation(args, { cwd: root });
4813
+ if (payload.data) payload.data.root = root;
4814
+ if (payload.ok) payload.data.stashes = (await readGitStashes(root)).stashes;
4815
+ return payload;
4816
+ }
4817
+
4818
+ async function applyGitStash(cwd, body = {}, { pop = false } = {}) {
4819
+ const root = await getGitRoot(cwd);
4820
+ const ref = cleanGitStashRef(body.ref);
4821
+ const payload = await runGuardedGitMutation(["stash", pop ? "pop" : "apply", ref], { cwd: root });
4822
+ if (payload.data) {
4823
+ payload.data.root = root;
4824
+ payload.data.ref = ref;
4825
+ }
4826
+ if (payload.ok) payload.data.stashes = (await readGitStashes(root)).stashes;
4827
+ else if (!payload.code && /conflict/i.test(payload.error || "")) {
4828
+ payload.code = "CONFLICTS";
4829
+ payload.hint = pop
4830
+ ? "The stash conflicts with the working tree; git kept the stash entry. Resolve the conflicts, then drop the stash manually."
4831
+ : "The stash conflicts with the working tree. Resolve the conflicts or reset the working tree.";
4832
+ }
4833
+ return payload;
4834
+ }
4835
+
4836
+ async function dropGitStash(cwd, body = {}) {
4837
+ requireConfirmed(body, "Dropping a stash permanently deletes it and");
4838
+ const root = await getGitRoot(cwd);
4839
+ const ref = cleanGitStashRef(body.ref);
4840
+ const payload = await runGuardedGitMutation(["stash", "drop", ref], { cwd: root });
4841
+ if (payload.data) {
4842
+ payload.data.root = root;
4843
+ payload.data.ref = ref;
4844
+ }
4845
+ if (payload.ok) payload.data.stashes = (await readGitStashes(root)).stashes;
4846
+ return payload;
4847
+ }
4848
+
4849
+ // ---- File-level staging ----
4850
+
4851
+ async function stageGitFile(cwd, body = {}) {
4852
+ const root = await getGitRoot(cwd);
4853
+ const rel = normalizeGitRelativePath(root, body.path);
4854
+ const payload = await runGuardedGitMutation(["add", "--", rel], { cwd: root, label: `git add -- ${rel}` });
4855
+ if (payload.data) payload.data.root = root;
4856
+ if (payload.ok) payload.data.changes = await readGitChanges(root);
4857
+ return payload;
4858
+ }
4859
+
4860
+ async function unstageGitFile(cwd, body = {}) {
4861
+ const root = await getGitRoot(cwd);
4862
+ const rel = normalizeGitRelativePath(root, body.path);
4863
+ let payload = await runGuardedGitMutation(["restore", "--staged", "--", rel], { cwd: root, label: `git restore --staged -- ${rel}` });
4864
+ if (!payload.ok && /HEAD/.test(payload.error || "")) {
4865
+ // Unborn branch (no commit yet): restore --staged has no HEAD to restore from.
4866
+ payload = await runGuardedGitMutation(["rm", "--cached", "-r", "--", rel], { cwd: root, label: `git rm --cached -- ${rel}` });
4867
+ }
4868
+ if (payload.data) payload.data.root = root;
4869
+ if (payload.ok) payload.data.changes = await readGitChanges(root);
4870
+ return payload;
4871
+ }
4872
+
4873
+ async function discardGitFile(cwd, body = {}) {
4874
+ requireConfirmed(body, "Discarding file changes is destructive and");
4875
+ const root = await getGitRoot(cwd);
4876
+ const rel = normalizeGitRelativePath(root, body.path);
4877
+ const payload = await runGuardedGitMutation(["restore", "--", rel], { cwd: root, label: `git restore -- ${rel}` });
4878
+ if (payload.data) payload.data.root = root;
4879
+ if (payload.ok) payload.data.changes = await readGitChanges(root);
4880
+ return payload;
4881
+ }
4882
+
4883
+ async function deleteGitUntrackedFile(cwd, body = {}) {
4884
+ requireConfirmed(body, "Deleting an untracked file is destructive and");
4885
+ const root = await getGitRoot(cwd);
4886
+ const rel = normalizeGitRelativePath(root, body.path);
4887
+ const listed = await runGitReadCommand(root, ["ls-files", "--others", "--exclude-standard", "--", rel], { maxOutputLength: 120_000 });
4888
+ const files = listed.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
4889
+ if (!files.includes(rel)) throw makeHttpError(409, `Not an untracked file: ${rel}`);
4890
+ await rm(resolveGitRelativePath(root, rel));
4891
+ return { ok: true, data: { root, path: rel, deleted: true, changes: await readGitChanges(root) } };
4892
+ }
4893
+
4894
+ // ---- Undo / recovery ----
4895
+
4896
+ async function readGitUndoState(cwd) {
4897
+ const root = await getGitRoot(cwd);
4898
+ const [parentProbe, porcelainText, upstream, operation, lastLog] = await Promise.all([
4899
+ runCommand("git", ["rev-parse", "--verify", "--quiet", "HEAD~1"], { cwd: root, timeoutMs: 2000 }),
4900
+ runGitReadCommand(root, ["status", "--porcelain=2", "--branch"], { maxOutputLength: 120_000 }),
4901
+ gitUpstreamRef(root),
4902
+ detectGitOperationKind(root),
4903
+ runGitReadCommand(root, ["log", "-1", "--format=%h%x09%s"], { maxOutputLength: 10_000 }).catch(() => ""),
4904
+ ]);
4905
+ const summary = summarizeGitPorcelainStatus(porcelainText);
4906
+ const hasParent = parentProbe.exitCode === 0;
4907
+ const [lastHash = "", ...subjectParts] = lastLog.trim().split("\t");
4908
+ const lastSubject = subjectParts.join("\t");
4909
+ // With an upstream, "unpushed" means ahead > 0; without one nothing has been
4910
+ // published through this branch's tracking ref.
4911
+ const unpushed = upstream ? summary.ahead > 0 : true;
4912
+ return {
4913
+ root,
4914
+ hasParent,
4915
+ upstream,
4916
+ operation,
4917
+ summary,
4918
+ lastCommit: lastHash ? { hash: lastHash, subject: lastSubject } : null,
4919
+ canUndoLastCommit: hasParent && unpushed && !operation,
4920
+ canAmendMessage: Boolean(lastHash) && unpushed && !operation && summary.staged === 0,
4921
+ };
4922
+ }
4923
+
4924
+ async function undoLastGitCommit(cwd, body = {}) {
4925
+ requireConfirmed(body, "Undoing the last commit rewrites HEAD and");
4926
+ const state = await readGitUndoState(cwd);
4927
+ if (!state.hasParent) throw makeHttpError(409, "HEAD has no parent commit to undo to");
4928
+ if (state.operation) throw makeHttpError(409, `Cannot undo during a ${state.operation} operation`);
4929
+ if (!state.canUndoLastCommit) throw makeHttpError(409, "The last commit is already pushed to the upstream; undoing it would rewrite published history");
4930
+ const payload = await runGuardedGitMutation(["reset", "--soft", "HEAD~1"], { cwd: state.root });
4931
+ if (payload.data) {
4932
+ payload.data.root = state.root;
4933
+ payload.data.undoneCommit = state.lastCommit;
4934
+ payload.data.restoreCommand = "git reset --soft ORIG_HEAD";
4935
+ }
4936
+ if (payload.ok) payload.data.changes = await readGitChanges(state.root);
4937
+ return payload;
4938
+ }
4939
+
4940
+ async function amendLastGitCommitMessage(cwd, body = {}) {
4941
+ requireConfirmed(body, "Amending the last commit rewrites HEAD and");
4942
+ const message = cleanGitCommitMessageInput(body.message);
4943
+ const state = await readGitUndoState(cwd);
4944
+ if (!state.lastCommit) throw makeHttpError(409, "There is no commit to amend");
4945
+ if (state.operation) throw makeHttpError(409, `Cannot amend during a ${state.operation} operation`);
4946
+ if (state.summary.staged > 0) throw makeHttpError(409, "Staged changes present; amending now would silently add them to the last commit. Unstage or commit them first.");
4947
+ if (!state.canAmendMessage) throw makeHttpError(409, "The last commit is already pushed to the upstream; amending it would rewrite published history");
4948
+ const payload = await runGuardedGitMutation(["commit", "--amend", "-m", message], { cwd: state.root, label: "git commit --amend -m <message>" });
4949
+ if (payload.data) {
4950
+ payload.data.root = state.root;
4951
+ payload.data.previousCommit = state.lastCommit;
4952
+ payload.data.restoreCommand = "git reset --soft ORIG_HEAD";
4953
+ }
4954
+ return payload;
4955
+ }
4956
+
4957
+ async function readGitReflog(cwd) {
4958
+ const root = await getGitRoot(cwd);
4959
+ const out = await runGitReadCommand(root, ["reflog", "-n", "20", "--format=%h%x09%gd%x09%cI%x09%gs"], { maxOutputLength: 120_000 });
4960
+ const entries = out
4961
+ .split(/\r?\n/)
4962
+ .filter(Boolean)
4963
+ .map((line) => {
4964
+ const [hash, selector, date, ...subject] = line.split("\t");
4965
+ return { hash: hash || "", selector: selector || "", date: date || "", subject: subject.join("\t") };
4966
+ });
4967
+ return { root, entries, generatedAt: new Date().toISOString() };
4968
+ }
4969
+
4970
+ // ---- Submodules ----
4971
+
4972
+ async function readGitSubmodules(cwd) {
4973
+ const root = await getGitRoot(cwd);
4974
+ if (!(await regularFileExists(path.join(root, ".gitmodules")))) {
4975
+ return { root, hasSubmodules: false, submodules: [], dirty: 0 };
4976
+ }
4977
+ const out = await runGitReadCommand(root, ["submodule", "status", "--recursive"], { timeoutMs: 30_000, maxOutputLength: 200_000 });
4978
+ const submodules = out
4979
+ .split(/\r?\n/)
4980
+ .filter(Boolean)
4981
+ .map((line) => {
4982
+ const flag = line[0] || " ";
4983
+ const rest = line.slice(1).trim();
4984
+ const firstSpace = rest.indexOf(" ");
4985
+ const sha = firstSpace === -1 ? rest : rest.slice(0, firstSpace);
4986
+ const remainder = firstSpace === -1 ? "" : rest.slice(firstSpace + 1);
4987
+ const describeMatch = remainder.match(/^(.*?)( \([^)]*\))?$/);
4988
+ return {
4989
+ sha,
4990
+ path: (describeMatch?.[1] ?? remainder).trim(),
4991
+ describe: describeMatch?.[2] ? describeMatch[2].trim().replace(/^\(|\)$/g, "") : "",
4992
+ state: flag === "-" ? "uninitialized" : flag === "+" ? "out-of-sync" : flag === "U" ? "conflicts" : "clean",
4993
+ };
4994
+ });
4995
+ return { root, hasSubmodules: true, submodules, dirty: submodules.filter((item) => item.state !== "clean").length };
4996
+ }
4997
+
4998
+ async function updateGitSubmodules(cwd, body = {}) {
4999
+ requireConfirmed(body, "Recursively updating submodules can check out new commits and");
5000
+ const root = await getGitRoot(cwd);
5001
+ const payload = await runGuardedGitMutation(["submodule", "update", "--init", "--recursive"], { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS });
5002
+ if (payload.data) payload.data.root = root;
5003
+ if (payload.ok) payload.data.submodules = (await readGitSubmodules(root)).submodules;
5004
+ return payload;
5005
+ }
5006
+
5007
+ // ---- Tags ----
5008
+
5009
+ function cleanGitTagName(value) {
5010
+ const name = String(value || "").trim();
5011
+ if (!name || name.includes("\0") || name.includes("@{") || name.startsWith("-") || name.startsWith("/") || /\s/.test(name)) {
5012
+ throw makeHttpError(400, "Invalid tag name");
5013
+ }
5014
+ return name;
5015
+ }
5016
+
5017
+ async function validateGitTagName(root, name) {
5018
+ const result = await runCommand("git", ["check-ref-format", `refs/tags/${name}`], { cwd: root, timeoutMs: 5000 });
5019
+ if (result.exitCode !== 0) throw makeHttpError(400, `Invalid tag name: ${name}`);
5020
+ }
5021
+
5022
+ async function readGitTags(cwd) {
5023
+ const root = await getGitRoot(cwd);
5024
+ const [headOut, recentOut] = await Promise.all([
5025
+ runGitReadCommand(root, ["tag", "--points-at", "HEAD", "--sort=-creatordate"], { maxOutputLength: 60_000 }).catch(() => ""),
5026
+ runGitReadCommand(
5027
+ root,
5028
+ ["for-each-ref", "refs/tags", "--sort=-creatordate", "--count=30", "--format=%(refname:short)%09%(objecttype)%09%(objectname:short)%09%(*objectname:short)%09%(creatordate:iso8601)%09%(subject)"],
5029
+ { maxOutputLength: 120_000 },
5030
+ ).catch(() => ""),
5031
+ ]);
5032
+ const headTags = headOut.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
5033
+ const tags = recentOut
5034
+ .split(/\r?\n/)
5035
+ .filter(Boolean)
5036
+ .map((line) => {
5037
+ const [name, objectType, objectName, target, date, ...subject] = line.split("\t");
5038
+ return {
5039
+ name: name || "",
5040
+ annotated: objectType === "tag",
5041
+ target: (objectType === "tag" ? target : objectName) || "",
5042
+ date: date || "",
5043
+ subject: subject.join("\t"),
5044
+ atHead: headTags.includes(name || ""),
5045
+ };
5046
+ });
5047
+ return { root, headTags, tags, generatedAt: new Date().toISOString() };
5048
+ }
5049
+
5050
+ async function createGitTag(cwd, body = {}) {
5051
+ requireConfirmed(body, "Creating a tag");
5052
+ const root = await getGitRoot(cwd);
5053
+ const name = cleanGitTagName(body.name);
5054
+ await validateGitTagName(root, name);
5055
+ const message = cleanGitCommitMessageInput(body.message || name);
5056
+ const payload = await runGuardedGitMutation(["tag", "-a", name, "-m", message], { cwd: root, label: `git tag -a ${name} -m <message>` });
5057
+ if (payload.data) {
5058
+ payload.data.root = root;
5059
+ payload.data.tag = name;
5060
+ // Tags never leave the machine implicitly; pushing stays a separate,
5061
+ // explicit action.
5062
+ payload.data.pushCommand = `git push ${"origin"} ${name}`;
5063
+ }
5064
+ if (payload.ok) payload.data.tags = (await readGitTags(root)).tags;
5065
+ return payload;
5066
+ }
5067
+
5068
+ // ---- Signing diagnostics ----
5069
+
5070
+ async function readGitSigningDiagnostics(cwd) {
5071
+ const root = await getGitRoot(cwd);
5072
+ const readConfig = async (args) => {
5073
+ const result = await runCommand("git", ["config", ...args], { cwd: root, timeoutMs: 2000 });
5074
+ return result.exitCode === 0 ? result.stdout.trim() : "";
5075
+ };
5076
+ const [gpgSign, gpgFormat, signingKey, lastLog] = await Promise.all([
5077
+ readConfig(["--bool", "--get", "commit.gpgsign"]),
5078
+ readConfig(["--get", "gpg.format"]),
5079
+ readConfig(["--get", "user.signingkey"]),
5080
+ runGitReadCommand(root, ["log", "-1", "--format=%h%x09%G?%x09%GS"], { maxOutputLength: 10_000 }).catch(() => ""),
5081
+ ]);
5082
+ const [lastHash = "", signState = "", signer = ""] = lastLog.trim().split("\t");
5083
+ const commitSignRequired = gpgSign.toLowerCase() === "true";
5084
+ const normalizedState = signState.trim().toUpperCase();
5085
+ const mismatch = commitSignRequired && (!normalizedState || normalizedState === "N" || normalizedState === "E");
5086
+ const suggestions = [];
5087
+ if (mismatch) {
5088
+ if (!signingKey) suggestions.push({ label: "Set your signing key (repo only)", command: "git config user.signingkey <KEY-ID>" });
5089
+ suggestions.push({ label: "Re-sign the last commit", command: "git commit --amend --no-edit -S" });
5090
+ suggestions.push({ label: "Disable signing for this repository", command: "git config commit.gpgsign false" });
5091
+ }
5092
+ return {
5093
+ root,
5094
+ commitSignRequired,
5095
+ gpgFormat: gpgFormat || "(default: gpg)",
5096
+ signingKey: signingKey || "(not set)",
5097
+ lastCommit: lastHash ? { hash: lastHash, signState: normalizedState || "N", signer } : null,
5098
+ mismatch,
5099
+ suggestions,
5100
+ };
5101
+ }
5102
+
4134
5103
  function gitWorkflowMessageCwd(root, cwd) {
4135
5104
  const messageCwd = path.resolve(String(cwd || root));
4136
5105
  if (!pathInside(root, messageCwd)) throw new Error(`Git workflow cwd must stay inside repository root: ${messageCwd}`);
@@ -4404,7 +5373,7 @@ async function prepareInitialRepositoryFiles(cwd, { repoName: repoNameInput, sta
4404
5373
  await writeFile(before.gitignorePath, gitignoreLinesForStack(stack, before.detectedStack), "utf8");
4405
5374
  gitignoreCreated = true;
4406
5375
  }
4407
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(["add", "--", "README.md", ".gitignore"], { cwd: before.root, label: "git add README.md .gitignore" }));
5376
+ const payload = gitMutationPayload(await runGitMutationCommand(["add", "--", "README.md", ".gitignore"], { cwd: before.root, label: "git add README.md .gitignore" }));
4408
5377
  if (payload.data) {
4409
5378
  payload.data.root = before.root;
4410
5379
  payload.data.readme = { path: before.readmePath, exists: true, created: !before.readmeExists };
@@ -4508,7 +5477,7 @@ async function switchGitBranch(cwd, branch, { create = false } = {}) {
4508
5477
  return { ok: true, data: { command: `git switch ${targetBranch}`, stdout: "", stderr: "", exitCode: 0, branch: targetBranch, root, switched: false, created: false } };
4509
5478
  }
4510
5479
  const args = create ? ["switch", "-c", targetBranch] : ["switch", targetBranch];
4511
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(args, { cwd: root, timeoutMs: 10 * 60 * 1000 }));
5480
+ const payload = gitMutationPayload(await runGitMutationCommand(args, { cwd: root, timeoutMs: 10 * 60 * 1000 }));
4512
5481
  if (payload.ok) {
4513
5482
  payload.data.branch = targetBranch;
4514
5483
  payload.data.root = root;
@@ -4835,7 +5804,9 @@ function runWorkflowCommand(command, args, { cwd, label = formatWorkflowCommand(
4835
5804
  return new Promise((resolve) => {
4836
5805
  const child = spawn(command, args, {
4837
5806
  cwd,
4838
- env: { ...process.env, GIT_TERMINAL_PROMPT: process.env.GIT_TERMINAL_PROMPT || "0", GH_PROMPT_DISABLED: process.env.GH_PROMPT_DISABLED || "1" },
5807
+ // LC_ALL=C keeps git/gh output in English so failure classification
5808
+ // (classifyGitSyncFailure, isGitLockFailure) works regardless of locale.
5809
+ env: { ...process.env, GIT_TERMINAL_PROMPT: process.env.GIT_TERMINAL_PROMPT || "0", GH_PROMPT_DISABLED: process.env.GH_PROMPT_DISABLED || "1", LC_ALL: "C" },
4839
5810
  stdio: ["ignore", "pipe", "pipe"],
4840
5811
  windowsHide: true,
4841
5812
  });
@@ -4875,7 +5846,10 @@ function runWorkflowCommand(command, args, { cwd, label = formatWorkflowCommand(
4875
5846
  stderr += String(chunk);
4876
5847
  if (stderr.length > 100000) stderr = stderr.slice(-100000);
4877
5848
  });
4878
- child.on("error", (error) => finish({ exitCode: undefined, stderr: stderr || sanitizeError(error), error: sanitizeError(error) }));
5849
+ child.on("error", (error) => {
5850
+ const message = formatCommandSpawnError(command, error);
5851
+ finish({ exitCode: undefined, stderr: stderr || message, error: message, errorCode: error?.code });
5852
+ });
4879
5853
  // "close", not "exit": exit can fire before the stdio pipes flush,
4880
5854
  // intermittently truncating collected stdout/stderr.
4881
5855
  child.on("close", (exitCode, signal) => finish({ exitCode, signal }));
@@ -4899,6 +5873,33 @@ function gitWorkflowCommandPayload(result) {
4899
5873
  };
4900
5874
  }
4901
5875
 
5876
+ // Read-only workflow lookups are safe over GET; everything else mutates the
5877
+ // repository (or process state, for cancel) and must be POST. Method + access
5878
+ // guard are enforced at the router before dispatch — never dispatch on path
5879
+ // alone, or cross-origin GETs (image/script tags) could drive git mutations.
5880
+ const GIT_WORKFLOW_READONLY_PATHS = new Set([
5881
+ "/api/git-workflow/message",
5882
+ "/api/git-workflow/default-commit-message",
5883
+ "/api/git-workflow/branch-name",
5884
+ "/api/git-workflow/pr-description",
5885
+ "/api/git-workflow/init-files-status",
5886
+ ]);
5887
+
5888
+ const GIT_WORKFLOW_MUTATING_PATHS = new Set([
5889
+ "/api/git-workflow/init",
5890
+ "/api/git-workflow/readme",
5891
+ "/api/git-workflow/initial-commit",
5892
+ "/api/git-workflow/main-branch",
5893
+ "/api/git-workflow/remote",
5894
+ "/api/git-workflow/init-push",
5895
+ "/api/git-workflow/add",
5896
+ "/api/git-workflow/branch",
5897
+ "/api/git-workflow/commit",
5898
+ "/api/git-workflow/push",
5899
+ "/api/git-workflow/create-pr",
5900
+ "/api/git-workflow/cancel",
5901
+ ]);
5902
+
4902
5903
  async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.cwd) {
4903
5904
  const tab = tabOrCwd && typeof tabOrCwd === "object" ? tabOrCwd : null;
4904
5905
  const cwd = tab?.cwd || tabOrCwd || options.cwd;
@@ -4914,25 +5915,25 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
4914
5915
  return { ok: true, data: await readGitWorkflowPrDescription(cwd) };
4915
5916
  case "/api/git-workflow/init":
4916
5917
  await ensureOutsideGitRepository(cwd);
4917
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["init"], { cwd }));
5918
+ return gitMutationPayload(await runGitMutationCommand(["init"], { cwd }));
4918
5919
  case "/api/git-workflow/init-files-status":
4919
5920
  return { ok: true, data: await initialRepositoryFilesStatus(cwd) };
4920
5921
  case "/api/git-workflow/readme":
4921
5922
  return prepareInitialRepositoryFiles(cwd, { repoName: body.repoName, stack: body.stack });
4922
5923
  case "/api/git-workflow/initial-commit": {
4923
5924
  const root = await getGitRoot(cwd);
4924
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["commit", "-m", "Initial commit"], { cwd: root, label: "git commit -m \"Initial commit\"" }));
5925
+ return gitMutationPayload(await runGitMutationCommand(["commit", "-m", "Initial commit"], { cwd: root, label: "git commit -m \"Initial commit\"" }));
4925
5926
  }
4926
5927
  case "/api/git-workflow/main-branch": {
4927
5928
  const root = await getGitRoot(cwd);
4928
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["branch", "-M", "main"], { cwd: root }));
5929
+ return gitMutationPayload(await runGitMutationCommand(["branch", "-M", "main"], { cwd: root }));
4929
5930
  }
4930
5931
  case "/api/git-workflow/remote": {
4931
5932
  const root = await getGitRoot(cwd);
4932
5933
  const username = cleanGitHubUsername(body.username);
4933
5934
  const repoName = cleanGitHubRepoName(body.repoName);
4934
5935
  const remoteUrl = gitHubOriginUrl(username, repoName);
4935
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(["remote", "add", "origin", remoteUrl], { cwd: root }));
5936
+ const payload = gitMutationPayload(await runGitMutationCommand(["remote", "add", "origin", remoteUrl], { cwd: root }));
4936
5937
  if (payload.data) {
4937
5938
  payload.data.root = root;
4938
5939
  payload.data.remote = "origin";
@@ -4944,11 +5945,11 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
4944
5945
  }
4945
5946
  case "/api/git-workflow/init-push": {
4946
5947
  const root = await getGitRoot(cwd);
4947
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["push", "-u", "origin", "main"], { cwd: root, timeoutMs: 15 * 60 * 1000 }));
5948
+ return applyGitSyncFailure(gitMutationPayload(await runGitMutationCommand(["push", "-u", "origin", "main"], { cwd: root, timeoutMs: 15 * 60 * 1000 })), { push: true });
4948
5949
  }
4949
5950
  case "/api/git-workflow/add":
4950
5951
  await getGitRoot(cwd);
4951
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["add", "."], { cwd }));
5952
+ return gitMutationPayload(await runGitMutationCommand(["add", "."], { cwd }));
4952
5953
  case "/api/git-workflow/branch": {
4953
5954
  if (!tab) throw new Error("Git workflow branch worktree requires a Web UI tab");
4954
5955
  return { ok: true, data: await createGitWorkflowBranchWorktree(tab, body) };
@@ -4959,32 +5960,45 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
4959
5960
  if (variant === "input") {
4960
5961
  const root = await getGitRoot(cwd);
4961
5962
  const message = cleanGitCommitMessageInput(body.message);
4962
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["commit", "-m", message], { cwd: root, label: "git commit -m <input message>" }));
5963
+ return gitMutationPayload(await runGitMutationCommand(["commit", "-m", message], { cwd: root, label: "git commit -m <input message>" }));
4963
5964
  }
4964
5965
  const messages = await readGitWorkflowMessages(cwd);
4965
5966
  if (variant === "short") {
4966
5967
  const message = messages.short.trim();
4967
5968
  if (!message) throw new Error(`${messages.shortPath} is empty`);
4968
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["commit", "-m", message], { cwd: messages.root, label: "git commit -m <dev/COMMIT/staged-commit-short.txt>" }));
5969
+ return gitMutationPayload(await runGitMutationCommand(["commit", "-m", message], { cwd: messages.root, label: "git commit -m <dev/COMMIT/staged-commit-short.txt>" }));
4969
5970
  }
4970
5971
  if (!messages.long.trim()) throw new Error(`${messages.longPath} is empty`);
4971
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["commit", "-F", messages.longPath], { cwd: messages.root, label: "git commit -F dev/COMMIT/staged-commit-long.txt" }));
5972
+ return gitMutationPayload(await runGitMutationCommand(["commit", "-F", messages.longPath], { cwd: messages.root, label: "git commit -F dev/COMMIT/staged-commit-long.txt" }));
4972
5973
  }
4973
5974
  case "/api/git-workflow/push": {
4974
5975
  const root = await getGitRoot(cwd);
5976
+ const currentBranch = await currentGitBranch(root);
5977
+ const protectedBranch = PROTECTED_GIT_BRANCHES.has(currentBranch);
4975
5978
  if (body.setUpstream) {
4976
- const currentBranch = await currentGitBranch(root);
4977
5979
  const requestedBranch = body.branch ? cleanGitBranchName(body.branch) : currentBranch;
4978
5980
  if (requestedBranch !== currentBranch) throw new Error(`Current branch is ${currentBranch}, not ${requestedBranch}`);
4979
5981
  const remote = await defaultGitRemote(root);
4980
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(["push", "-u", remote, currentBranch], { cwd: root, label: `git push -u ${remote} ${currentBranch}`, timeoutMs: 15 * 60 * 1000 }));
4981
- if (payload.ok) {
5982
+ const payload = await runGuardedGitMutation(["push", "-u", remote, currentBranch], { cwd: root, label: `git push -u ${remote} ${currentBranch}`, timeoutMs: 15 * 60 * 1000 });
5983
+ if (payload.data) {
4982
5984
  payload.data.branch = currentBranch;
4983
- payload.data.remote = remote;
5985
+ payload.data.protectedBranch = protectedBranch;
5986
+ if (payload.ok) payload.data.remote = remote;
4984
5987
  }
4985
- return payload;
5988
+ return applyGitSyncFailure(payload, { push: true });
5989
+ }
5990
+ // Plain --force is never offered; --force-with-lease still refuses to
5991
+ // clobber remote commits we have not seen, and requires confirmation.
5992
+ const forceWithLease = body.forceWithLease === true;
5993
+ if (forceWithLease) requireConfirmed(body, `Force-pushing ${currentBranch} (--force-with-lease) rewrites the remote branch and`);
5994
+ const args = forceWithLease ? ["push", "--force-with-lease"] : ["push"];
5995
+ const payload = await runGuardedGitMutation(args, { cwd: root, timeoutMs: 15 * 60 * 1000 });
5996
+ if (payload.data) {
5997
+ payload.data.branch = currentBranch;
5998
+ payload.data.protectedBranch = protectedBranch;
5999
+ payload.data.forceWithLease = forceWithLease;
4986
6000
  }
4987
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["push"], { cwd: root, timeoutMs: 15 * 60 * 1000 }));
6001
+ return applyGitSyncFailure(payload, { push: true });
4988
6002
  }
4989
6003
  case "/api/git-workflow/create-pr": {
4990
6004
  const root = await getGitRoot(cwd);
@@ -5789,6 +6803,71 @@ function clearExtensionWidgets(tab) {
5789
6803
  tab?.extensionWidgets?.clear();
5790
6804
  }
5791
6805
 
6806
+ function clearWebuiSubagents(tab) {
6807
+ if (tab) tab.webuiSubagents = null;
6808
+ }
6809
+
6810
+ function normalizeWebuiSubagentText(value, maxLength = 240) {
6811
+ const text = String(value || "").trim();
6812
+ return text ? text.slice(0, maxLength) : "";
6813
+ }
6814
+
6815
+ function normalizeWebuiSubagentPayload(value) {
6816
+ if (!value || typeof value !== "object" || value.version !== 1) return null;
6817
+ const runs = [];
6818
+ for (const rawRun of Array.isArray(value.runs) ? value.runs.slice(0, WEBUI_SUBAGENT_RUN_LIMIT) : []) {
6819
+ if (!rawRun || typeof rawRun !== "object") continue;
6820
+ const id = normalizeWebuiSubagentText(rawRun.id, 160);
6821
+ if (!id) continue;
6822
+ const agents = [];
6823
+ for (const rawAgent of Array.isArray(rawRun.agents) ? rawRun.agents.slice(0, WEBUI_SUBAGENT_AGENT_LIMIT) : []) {
6824
+ const name = normalizeWebuiSubagentText(rawAgent?.name, 160);
6825
+ if (!name || rawAgent?.status !== "running") continue;
6826
+ agents.push({
6827
+ id: normalizeWebuiSubagentText(rawAgent.id || `${id}:${agents.length}`, 240),
6828
+ name,
6829
+ status: "running",
6830
+ index: Number.isInteger(rawAgent.index) ? rawAgent.index : agents.length,
6831
+ currentTool: normalizeWebuiSubagentText(rawAgent.currentTool, 120) || undefined,
6832
+ activityState: normalizeWebuiSubagentText(rawAgent.activityState, 80) || undefined,
6833
+ nested: rawAgent.nested === true,
6834
+ });
6835
+ }
6836
+ if (!agents.length) continue;
6837
+ runs.push({
6838
+ id,
6839
+ source: rawRun.source === "foreground" ? "foreground" : "async",
6840
+ mode: ["single", "parallel", "chain"].includes(rawRun.mode) ? rawRun.mode : "single",
6841
+ status: "running",
6842
+ startedAt: Number.isFinite(rawRun.startedAt) ? rawRun.startedAt : Date.now(),
6843
+ agents: agents.sort((a, b) => a.index - b.index || a.name.localeCompare(b.name)),
6844
+ });
6845
+ }
6846
+ return {
6847
+ version: 1,
6848
+ available: value.available === true,
6849
+ updatedAt: Number.isFinite(value.updatedAt) ? value.updatedAt : Date.now(),
6850
+ receivedAt: Date.now(),
6851
+ runs: runs.sort((a, b) => a.startedAt - b.startedAt || a.id.localeCompare(b.id)),
6852
+ };
6853
+ }
6854
+
6855
+ function rememberWebuiSubagentsStatusEvent(tab, event) {
6856
+ if (event?.type !== "extension_ui_request" || event.method !== "setStatus" || event.statusKey !== WEBUI_SUBAGENTS_STATUS_KEY) return false;
6857
+ const statusText = String(event.statusText || "");
6858
+ if (!statusText) {
6859
+ clearWebuiSubagents(tab);
6860
+ return true;
6861
+ }
6862
+ if (!statusText.startsWith(WEBUI_SUBAGENTS_PAYLOAD_PREFIX)) return true;
6863
+ try {
6864
+ tab.webuiSubagents = normalizeWebuiSubagentPayload(JSON.parse(statusText.slice(WEBUI_SUBAGENTS_PAYLOAD_PREFIX.length)));
6865
+ } catch {
6866
+ tab.webuiSubagents = null;
6867
+ }
6868
+ return true;
6869
+ }
6870
+
5792
6871
  function naturalConversationStatusState(statusText) {
5793
6872
  const text = stripAnsi(statusText).replace(/\s+/g, " ").trim();
5794
6873
  if (!text) return { enabled: false, uiState: "off", statusText: "" };
@@ -6369,13 +7448,15 @@ function attachRpcToTab(tab, rpc) {
6369
7448
  tab.rpcUnsubscribe?.();
6370
7449
  tab.rpc = rpc;
6371
7450
  tab.rpcUnsubscribe = rpc.onEvent((event) => {
6372
- if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event)) return;
7451
+ if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event) || rememberWebuiSubagentsStatusEvent(tab, event)) return;
6373
7452
  updateTabActivityFromEvent(tab, event);
6374
7453
  let scopedEvent = eventForTabClients(tab, event);
6375
7454
  if (event?.type === "pi_process_exit" || event?.type === "pi_process_error") {
7455
+ tab.gitWorkflowGenerationRestore = null;
6376
7456
  clearPendingExtensionUiRequests(tab);
6377
7457
  clearExtensionStatuses(tab);
6378
7458
  clearExtensionWidgets(tab);
7459
+ clearWebuiSubagents(tab);
6379
7460
  resetNaturalConversationMode(tab);
6380
7461
  } else {
6381
7462
  rememberExtensionStatusEvent(tab, scopedEvent);
@@ -6387,6 +7468,7 @@ function attachRpcToTab(tab, rpc) {
6387
7468
  recordEvent(scopedEvent);
6388
7469
  for (const client of tab.sseClients) sendSse(client, scopedEvent);
6389
7470
  if (event?.type === "compaction_end" && event.aborted !== true) void flushCompactionQueue(tab, event);
7471
+ if (event?.type === "agent_settled") void restoreGitWorkflowGenerationProfile(tab);
6390
7472
  });
6391
7473
  }
6392
7474
 
@@ -6416,10 +7498,12 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
6416
7498
  gitWorkspace: gitWorkspace || null,
6417
7499
  lastState: null,
6418
7500
  pendingThinkingLevel: undefined,
7501
+ gitWorkflowGenerationRestore: null,
6419
7502
  activity: createTabActivity(createdAt),
6420
7503
  pendingExtensionUiRequests: new Map(),
6421
7504
  extensionStatuses: new Map(),
6422
7505
  extensionWidgets: new Map(),
7506
+ webuiSubagents: null,
6423
7507
  webuiHelperRequests: new Map(),
6424
7508
  webuiHelperResponseIds: new Set(),
6425
7509
  bashQueue: [],
@@ -6482,6 +7566,84 @@ function listTabs() {
6482
7566
  return [...tabs.values()].map(tabMeta);
6483
7567
  }
6484
7568
 
7569
+ function webuiSubagentsData() {
7570
+ const sortedTabs = [...tabs.values()].sort((a, b) => a.index - b.index || a.title.localeCompare(b.title));
7571
+ const tabSummaries = sortedTabs.map((tab) => {
7572
+ const status = tab.webuiSubagents || { version: 1, available: false, updatedAt: null, receivedAt: null, runs: [] };
7573
+ const runs = Array.isArray(status.runs) ? status.runs : [];
7574
+ return {
7575
+ tabId: tab.id,
7576
+ tabIndex: tab.index,
7577
+ tabTitle: tab.title,
7578
+ cwd: tab.cwd,
7579
+ sessionName: normalizeWebuiSubagentText(tab.lastState?.sessionName || tab.title, 160),
7580
+ sessionFile: tabRestorableSessionFile(tab) || null,
7581
+ running: tab.rpc.isRunning(),
7582
+ available: status.available === true,
7583
+ updatedAt: status.updatedAt || null,
7584
+ receivedAt: status.receivedAt || null,
7585
+ runs,
7586
+ agentCount: runs.reduce((count, run) => count + run.agents.length, 0),
7587
+ };
7588
+ });
7589
+ return {
7590
+ version: 1,
7591
+ updatedAt: Date.now(),
7592
+ available: tabSummaries.some((tab) => tab.available),
7593
+ totalRuns: tabSummaries.reduce((count, tab) => count + tab.runs.length, 0),
7594
+ totalAgents: tabSummaries.reduce((count, tab) => count + tab.agentCount, 0),
7595
+ tabs: tabSummaries,
7596
+ };
7597
+ }
7598
+
7599
+ function normalizeWebuiSubagentOutput(value, selection) {
7600
+ if (!value || typeof value !== "object" || value.version !== 1) throw makeHttpError(502, "Invalid subagent output response from Web UI helper");
7601
+ const rawAgent = value.agent && typeof value.agent === "object" ? value.agent : {};
7602
+ const recentOutput = (Array.isArray(rawAgent.recentOutput) ? rawAgent.recentOutput : [])
7603
+ .slice(-WEBUI_SUBAGENT_OUTPUT_LINE_LIMIT)
7604
+ .map((line) => String(line ?? "").replace(/\r/g, "").slice(0, WEBUI_SUBAGENT_OUTPUT_LINE_LENGTH));
7605
+ const recentTools = (Array.isArray(rawAgent.recentTools) ? rawAgent.recentTools : []).slice(-20).map((entry) => ({
7606
+ tool: normalizeWebuiSubagentText(entry?.tool, 120),
7607
+ args: normalizeWebuiSubagentText(entry?.args, 500),
7608
+ endMs: Number.isFinite(entry?.endMs) ? entry.endMs : undefined,
7609
+ })).filter((entry) => entry.tool);
7610
+ return {
7611
+ version: 1,
7612
+ runId: normalizeWebuiSubagentText(value.runId, 160) || selection.run.id,
7613
+ source: value.source === "foreground" ? "foreground" : "async",
7614
+ mode: ["single", "parallel", "chain"].includes(value.mode) ? value.mode : selection.run.mode,
7615
+ startedAt: Number.isFinite(value.startedAt) ? value.startedAt : selection.run.startedAt,
7616
+ updatedAt: Number.isFinite(value.updatedAt) ? value.updatedAt : Date.now(),
7617
+ agent: {
7618
+ id: selection.agent.id,
7619
+ name: normalizeWebuiSubagentText(rawAgent.name, 160) || selection.agent.name,
7620
+ index: Number.isInteger(rawAgent.index) ? rawAgent.index : selection.agent.index,
7621
+ nested: rawAgent.nested === true,
7622
+ status: normalizeWebuiSubagentText(rawAgent.status, 40) || "running",
7623
+ activityState: normalizeWebuiSubagentText(rawAgent.activityState, 80) || undefined,
7624
+ currentTool: normalizeWebuiSubagentText(rawAgent.currentTool, 120) || undefined,
7625
+ currentToolArgs: normalizeWebuiSubagentText(rawAgent.currentToolArgs, 500) || undefined,
7626
+ currentPath: normalizeWebuiSubagentText(rawAgent.currentPath, 1000) || undefined,
7627
+ turnCount: Number.isFinite(rawAgent.turnCount) ? rawAgent.turnCount : undefined,
7628
+ toolCount: Number.isFinite(rawAgent.toolCount) ? rawAgent.toolCount : undefined,
7629
+ tokens: Number.isFinite(rawAgent.tokens) ? rawAgent.tokens : undefined,
7630
+ recentTools,
7631
+ recentOutput,
7632
+ error: normalizeWebuiSubagentText(rawAgent.error, 1000) || undefined,
7633
+ },
7634
+ };
7635
+ }
7636
+
7637
+ async function webuiSubagentOutputData(tab, runId, agentId) {
7638
+ const runs = Array.isArray(tab.webuiSubagents?.runs) ? tab.webuiSubagents.runs : [];
7639
+ const run = runs.find((candidate) => candidate.id === runId);
7640
+ if (!run) throw makeHttpError(404, `Running subagent run not found: ${runId}`);
7641
+ const agent = (Array.isArray(run.agents) ? run.agents : []).find((candidate) => candidate.id === agentId);
7642
+ if (!agent) throw makeHttpError(404, `Running subagent not found: ${agentId}`);
7643
+ const data = await sendWebuiHelperCommand(tab, "subagent-output", { runId, agentId });
7644
+ return normalizeWebuiSubagentOutput(data, { run, agent });
7645
+ }
7646
+
6485
7647
  function restorableTabDescriptor(tab, state = null) {
6486
7648
  return normalizeRestoreTabDescriptor({
6487
7649
  id: tab.id,
@@ -7071,6 +8233,7 @@ async function updateTabCwd(id, cwd) {
7071
8233
  clearPendingExtensionUiRequests(tab);
7072
8234
  clearExtensionStatuses(tab);
7073
8235
  clearExtensionWidgets(tab);
8236
+ clearWebuiSubagents(tab);
7074
8237
  resetNaturalConversationMode(tab);
7075
8238
  const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd });
7076
8239
  attachRpcToTab(tab, rpc);
@@ -7110,6 +8273,7 @@ async function restartTabRpc(tab, reason = "reload") {
7110
8273
  clearPendingExtensionUiRequests(tab);
7111
8274
  clearExtensionStatuses(tab);
7112
8275
  clearExtensionWidgets(tab);
8276
+ clearWebuiSubagents(tab);
7113
8277
  resetNaturalConversationMode(tab);
7114
8278
  const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd });
7115
8279
  attachRpcToTab(tab, rpc);
@@ -8189,13 +9353,17 @@ async function getFileTreeData(tab, requestedPath = "") {
8189
9353
  const resolved = await resolveWorkspacePath(tab, requestedPath);
8190
9354
  if (!resolved.info?.isDirectory()) throw makeHttpError(400, "Path is not a directory");
8191
9355
  const dirents = await readdir(resolved.targetPath, { withFileTypes: true });
8192
- const listed = await statFileTreeEntries(resolved.targetPath, dirents, resolved.root, resolved.realRoot);
9356
+ const [listed, gitStatus] = await Promise.all([
9357
+ statFileTreeEntries(resolved.targetPath, dirents, resolved.root, resolved.realRoot),
9358
+ readWorkspaceGitStatusIndex(resolved.root),
9359
+ ]);
8193
9360
  return {
8194
9361
  root: resolved.root,
8195
9362
  displayRoot: displayPath(resolved.root),
8196
9363
  path: resolved.relative,
8197
9364
  displayPath: displayPath(resolved.targetPath),
8198
- entries: listed.entries,
9365
+ entries: withFileTreeGitStatus(listed.entries, resolved.root, gitStatus),
9366
+ gitStatus: fileTreeGitStatusPayload(resolved.root, gitStatus),
8199
9367
  truncated: listed.truncated,
8200
9368
  total: listed.total,
8201
9369
  };
@@ -8222,6 +9390,7 @@ async function getFileSearchData(tab, rawQuery = "") {
8222
9390
  }
8223
9391
  const resolved = await resolveWorkspacePath(tab, "");
8224
9392
  if (!resolved.info?.isDirectory()) throw makeHttpError(400, "Workspace root is not a directory");
9393
+ const gitStatus = await readWorkspaceGitStatusIndex(resolved.root);
8225
9394
  const queryLower = query.toLowerCase();
8226
9395
  const entries = [];
8227
9396
  const queue = [{ dirPath: resolved.root, relative: "", depth: 0 }];
@@ -8283,7 +9452,8 @@ async function getFileSearchData(tab, rawQuery = "") {
8283
9452
  root: resolved.root,
8284
9453
  displayRoot: displayPath(resolved.root),
8285
9454
  query,
8286
- entries,
9455
+ entries: withFileTreeGitStatus(entries, resolved.root, gitStatus),
9456
+ gitStatus: fileTreeGitStatusPayload(resolved.root, gitStatus),
8287
9457
  truncated,
8288
9458
  total: entries.length,
8289
9459
  scanned,
@@ -8345,6 +9515,103 @@ async function saveFileContentData(tab, body = {}) {
8345
9515
  };
8346
9516
  }
8347
9517
 
9518
+ function workspaceRelativePath(root, targetPath) {
9519
+ return path.relative(root, targetPath).split(path.sep).join("/");
9520
+ }
9521
+
9522
+ function fileOperationEntryType(info) {
9523
+ if (info?.isDirectory?.()) return "directory";
9524
+ if (info?.isFile?.()) return "file";
9525
+ return "other";
9526
+ }
9527
+
9528
+ function assertWorkspaceEntryMutable(resolved, action) {
9529
+ if (!resolved.relative) throw makeHttpError(400, `Workspace root cannot be ${action}`);
9530
+ const type = fileOperationEntryType(resolved.info);
9531
+ if (type !== "file" && type !== "directory") throw makeHttpError(400, "Only regular files and directories can be modified from WebUI");
9532
+ return type;
9533
+ }
9534
+
9535
+ async function existingDestinationStats(targetPath) {
9536
+ try {
9537
+ return await stat(targetPath);
9538
+ } catch (error) {
9539
+ if (error?.code === "ENOENT") return null;
9540
+ throw makeHttpError(400, `Cannot access destination: ${displayPath(targetPath)}`);
9541
+ }
9542
+ }
9543
+
9544
+ async function resolveWorkspaceMoveDestination(tab, source, rawDestination = "") {
9545
+ const destinationText = String(rawDestination || "").trim();
9546
+ if (!destinationText) throw makeHttpError(400, "Destination path is required");
9547
+ if (destinationText.includes("\0")) throw makeHttpError(400, "Destination path cannot contain null bytes");
9548
+
9549
+ const candidatePath = path.isAbsolute(destinationText) ? path.resolve(destinationText) : path.resolve(source.root, destinationText);
9550
+ if (candidatePath !== source.root && !pathInside(source.root, candidatePath)) throw makeHttpError(403, "Destination path must stay inside the active tab working directory");
9551
+
9552
+ const candidateInfo = await existingDestinationStats(candidatePath);
9553
+ let targetPath = candidatePath;
9554
+ let targetInfo = candidateInfo;
9555
+ if (candidateInfo?.isDirectory?.()) {
9556
+ targetPath = path.join(candidatePath, path.basename(source.targetPath));
9557
+ targetInfo = await existingDestinationStats(targetPath);
9558
+ }
9559
+
9560
+ if (path.resolve(targetPath) === path.resolve(source.targetPath)) throw makeHttpError(400, "Source and destination are the same path");
9561
+ if (targetInfo) throw makeHttpError(409, `Destination already exists: ${workspaceRelativePath(source.root, targetPath)}`);
9562
+ if (source.info?.isDirectory?.() && pathInside(source.targetPath, targetPath)) throw makeHttpError(400, "A directory cannot be moved into itself or one of its descendants");
9563
+
9564
+ const parentPath = path.dirname(targetPath);
9565
+ if (parentPath !== source.root && !pathInside(source.root, parentPath)) throw makeHttpError(403, "Destination parent must stay inside the active tab working directory");
9566
+ const parentInfo = await stat(parentPath).catch((error) => {
9567
+ if (error?.code === "ENOENT") throw makeHttpError(404, `Destination parent not found: ${displayPath(parentPath)}`);
9568
+ throw makeHttpError(400, `Cannot access destination parent: ${displayPath(parentPath)}`);
9569
+ });
9570
+ if (!parentInfo?.isDirectory?.()) throw makeHttpError(400, "Destination parent is not a directory");
9571
+ const realParent = await realpath(parentPath).catch(() => parentPath);
9572
+ if (realParent !== source.realRoot && !pathInside(source.realRoot, realParent)) throw makeHttpError(403, "Destination parent escapes the active tab working directory");
9573
+
9574
+ return {
9575
+ targetPath,
9576
+ relative: workspaceRelativePath(source.root, targetPath),
9577
+ parentPath: workspaceRelativePath(source.root, parentPath),
9578
+ };
9579
+ }
9580
+
9581
+ async function deleteFileSystemEntryData(tab, body = {}) {
9582
+ if (body.confirmed !== true) throw makeHttpError(409, "Deleting files or directories requires confirmed: true");
9583
+ const resolved = await resolveWorkspacePath(tab, body.path || body.filePath || "");
9584
+ const type = assertWorkspaceEntryMutable(resolved, "deleted");
9585
+ await rm(resolved.targetPath, { recursive: type === "directory" });
9586
+ return {
9587
+ path: resolved.relative,
9588
+ name: path.basename(resolved.targetPath),
9589
+ type,
9590
+ parentPath: workspaceRelativePath(resolved.root, path.dirname(resolved.targetPath)),
9591
+ deleted: true,
9592
+ };
9593
+ }
9594
+
9595
+ async function moveFileSystemEntryData(tab, body = {}) {
9596
+ if (body.confirmed !== true) throw makeHttpError(409, "Moving files or directories requires confirmed: true");
9597
+ const source = await resolveWorkspacePath(tab, body.path || body.filePath || body.sourcePath || "");
9598
+ const type = assertWorkspaceEntryMutable(source, "moved");
9599
+ const destination = await resolveWorkspaceMoveDestination(tab, source, body.toPath || body.destinationPath || body.destination || "");
9600
+ await rename(source.targetPath, destination.targetPath);
9601
+ const nextStats = await stat(destination.targetPath).catch(() => null);
9602
+ return {
9603
+ path: source.relative,
9604
+ destination: destination.relative,
9605
+ name: path.basename(destination.targetPath),
9606
+ type,
9607
+ parentPath: workspaceRelativePath(source.root, path.dirname(source.targetPath)),
9608
+ destinationParentPath: destination.parentPath,
9609
+ moved: true,
9610
+ size: nextStats?.size,
9611
+ mtimeMs: nextStats?.mtimeMs,
9612
+ };
9613
+ }
9614
+
8348
9615
  function defaultEditorCommand(targetPath) {
8349
9616
  if (platform() === "win32") return { command: "cmd", args: ["/c", "start", "", targetPath] };
8350
9617
  if (platform() === "darwin") return { command: "open", args: [targetPath] };
@@ -8936,6 +10203,7 @@ async function handleNativeSlashCommand(tab, body, req) {
8936
10203
  clearPendingExtensionUiRequests(tab);
8937
10204
  clearExtensionStatuses(tab);
8938
10205
  clearExtensionWidgets(tab);
10206
+ clearWebuiSubagents(tab);
8939
10207
  resetNaturalConversationMode(tab);
8940
10208
  return respondNative("new", {
8941
10209
  status: "succeeded",
@@ -9530,6 +10798,20 @@ const server = createServer(async (req, res) => {
9530
10798
  return;
9531
10799
  }
9532
10800
 
10801
+ if (url.pathname === "/api/subagents" && req.method === "GET") {
10802
+ sendJson(res, 200, { ok: true, data: webuiSubagentsData() });
10803
+ return;
10804
+ }
10805
+
10806
+ if (url.pathname === "/api/subagents/output" && req.method === "GET") {
10807
+ const tab = getRequestedTab(req, url);
10808
+ const runId = normalizeWebuiSubagentText(url.searchParams.get("run"), 160);
10809
+ const agentId = normalizeWebuiSubagentText(url.searchParams.get("agent"), 240);
10810
+ if (!runId || !agentId) throw makeHttpError(400, "run and agent query parameters are required");
10811
+ sendJson(res, 200, { ok: true, data: await webuiSubagentOutputData(tab, runId, agentId) });
10812
+ return;
10813
+ }
10814
+
9533
10815
  if (url.pathname === "/api/tabs" && req.method === "POST") {
9534
10816
  const body = await readJsonBody(req);
9535
10817
  const tab = await createTab({ title: body.title, cwd: body.cwd });
@@ -9862,6 +11144,24 @@ const server = createServer(async (req, res) => {
9862
11144
  return;
9863
11145
  }
9864
11146
 
11147
+ if (url.pathname === "/api/files" && req.method === "DELETE") {
11148
+ requireLocalhostRoute(req, url.pathname);
11149
+ const body = await readJsonBody(req);
11150
+ const tab = getRequestedTab(req, url, body);
11151
+ ensureNaturalConversationRouteAllowed(tab, "file deletion is blocked");
11152
+ sendJson(res, 200, { ok: true, data: await deleteFileSystemEntryData(tab, body) });
11153
+ return;
11154
+ }
11155
+
11156
+ if (url.pathname === "/api/files/move" && req.method === "POST") {
11157
+ requireLocalhostRoute(req, url.pathname);
11158
+ const body = await readJsonBody(req);
11159
+ const tab = getRequestedTab(req, url, body);
11160
+ ensureNaturalConversationRouteAllowed(tab, "file moves are blocked");
11161
+ sendJson(res, 200, { ok: true, data: await moveFileSystemEntryData(tab, body) });
11162
+ return;
11163
+ }
11164
+
9865
11165
  if (url.pathname === "/api/files/search" && req.method === "GET") {
9866
11166
  const tab = getRequestedTab(req, url);
9867
11167
  sendJson(res, 200, { ok: true, data: await getFileSearchData(tab, url.searchParams.get("q") || url.searchParams.get("query") || "") });
@@ -10111,6 +11411,28 @@ const server = createServer(async (req, res) => {
10111
11411
  return;
10112
11412
  }
10113
11413
 
11414
+ if (url.pathname === "/api/git-workflow/preferences" && req.method === "GET") {
11415
+ const tab = getRequestedTab(req, url);
11416
+ sendJson(res, 200, { ok: true, data: await gitWorkflowPreferencesData(tab) });
11417
+ return;
11418
+ }
11419
+
11420
+ if (url.pathname === "/api/git-workflow/preferences" && req.method === "POST") {
11421
+ const body = await readJsonBody(req);
11422
+ const tab = getRequestedTab(req, url, body);
11423
+ ensureNaturalConversationRouteAllowed(tab, "guided Git setup changes are blocked");
11424
+ sendJson(res, 200, { ok: true, data: await saveGitWorkflowPreferencesData(tab, body) });
11425
+ return;
11426
+ }
11427
+
11428
+ if (url.pathname === "/api/git-workflow/generate" && req.method === "POST") {
11429
+ const body = await readJsonBody(req);
11430
+ const tab = getRequestedTab(req, url, body);
11431
+ ensureNaturalConversationRouteAllowed(tab, "guided Git generation is blocked");
11432
+ sendJson(res, 200, { ok: true, data: await startGitWorkflowGeneration(tab, body) });
11433
+ return;
11434
+ }
11435
+
10114
11436
  if (url.pathname === "/api/settings" && req.method === "GET") {
10115
11437
  const tab = getRequestedTab(req, url);
10116
11438
  sendJson(res, 200, { ok: true, data: nativeSettingsPayload(settingsManagerForTab(tab)) });
@@ -10292,15 +11614,89 @@ const server = createServer(async (req, res) => {
10292
11614
  return;
10293
11615
  }
10294
11616
 
10295
- if (url.pathname.startsWith("/api/git-workflow/")) {
10296
- const body = req.method === "POST" ? await readJsonBody(req) : {};
10297
- const tab = getRequestedTab(req, url, body);
10298
- if (req.method !== "GET") ensureNaturalConversationRouteAllowed(tab, "git workflow actions are blocked");
10299
- const response = await handleGitWorkflowRequest(url.pathname, body, tab);
10300
- if (response) {
10301
- sendJson(res, 200, response);
11617
+ {
11618
+ const gitActionError = (error) => {
11619
+ sendJson(res, error?.statusCode || 200, { ok: false, ...(error?.code ? { code: error.code } : {}), error: sanitizeError(error) });
11620
+ };
11621
+ const GIT_READ_ROUTES = {
11622
+ "/api/git-operation": (cwd) => readGitOperationSnapshot(cwd),
11623
+ "/api/git-stash": (cwd) => readGitStashes(cwd),
11624
+ "/api/git-stash/show": (cwd) => readGitStashPreview(cwd, url.searchParams.get("ref") || ""),
11625
+ "/api/git-undo": (cwd) => readGitUndoState(cwd),
11626
+ "/api/git-reflog": (cwd) => readGitReflog(cwd),
11627
+ "/api/git-submodules": (cwd) => readGitSubmodules(cwd),
11628
+ "/api/git-tags": (cwd) => readGitTags(cwd),
11629
+ "/api/git-signing": (cwd) => readGitSigningDiagnostics(cwd),
11630
+ "/api/git-worktrees/prune": (cwd) => pruneGitWorktrees(cwd, { dryRun: true }),
11631
+ };
11632
+ if (req.method === "GET" && GIT_READ_ROUTES[url.pathname]) {
11633
+ const tab = getRequestedTab(req, url);
11634
+ try {
11635
+ sendJson(res, 200, { ok: true, data: await GIT_READ_ROUTES[url.pathname](tab.cwd) });
11636
+ } catch (error) {
11637
+ gitActionError(error);
11638
+ }
10302
11639
  return;
10303
11640
  }
11641
+
11642
+ const GIT_MUTATION_ROUTES = {
11643
+ "/api/git-fetch": (cwd) => fetchGitChanges(cwd),
11644
+ "/api/git-changes/integrate": (cwd, body) => integrateGitUpstream(cwd, body),
11645
+ "/api/git-changes/stage-file": (cwd, body) => stageGitFile(cwd, body),
11646
+ "/api/git-changes/unstage-file": (cwd, body) => unstageGitFile(cwd, body),
11647
+ "/api/git-changes/discard-file": (cwd, body) => discardGitFile(cwd, body),
11648
+ "/api/git-changes/delete-untracked": (cwd, body) => deleteGitUntrackedFile(cwd, body),
11649
+ "/api/git-operation/continue": (cwd, body) => gitOperationAction(cwd, "continue", body),
11650
+ "/api/git-operation/skip": (cwd, body) => gitOperationAction(cwd, "skip", body),
11651
+ "/api/git-operation/abort": (cwd, body) => gitOperationAction(cwd, "abort", body),
11652
+ "/api/git-operation/stage-file": (cwd, body) => gitOperationStageFile(cwd, body),
11653
+ "/api/git-operation/bisect": (cwd, body) => gitBisectAction(cwd, body),
11654
+ "/api/git-stash/save": (cwd, body) => saveGitStash(cwd, body),
11655
+ "/api/git-stash/apply": (cwd, body) => applyGitStash(cwd, body),
11656
+ "/api/git-stash/pop": (cwd, body) => applyGitStash(cwd, body, { pop: true }),
11657
+ "/api/git-stash/drop": (cwd, body) => dropGitStash(cwd, body),
11658
+ "/api/git-undo/last-commit": (cwd, body) => undoLastGitCommit(cwd, body),
11659
+ "/api/git-undo/amend-message": (cwd, body) => amendLastGitCommitMessage(cwd, body),
11660
+ "/api/git-submodules/update": (cwd, body) => updateGitSubmodules(cwd, body),
11661
+ "/api/git-tags/create": (cwd, body) => createGitTag(cwd, body),
11662
+ "/api/git-worktrees/prune": (cwd, body) => {
11663
+ requireConfirmed(body, "Pruning stale worktree records");
11664
+ return pruneGitWorktrees(cwd, { dryRun: false });
11665
+ },
11666
+ };
11667
+ if (req.method === "POST" && GIT_MUTATION_ROUTES[url.pathname]) {
11668
+ const body = await readJsonBody(req);
11669
+ const tab = getRequestedTab(req, url, body);
11670
+ ensureNaturalConversationRouteAllowed(tab, "git actions are blocked");
11671
+ try {
11672
+ const payload = await GIT_MUTATION_ROUTES[url.pathname](tab.cwd, body);
11673
+ sendJson(res, 200, payload && typeof payload === "object" && "ok" in payload ? payload : { ok: true, data: payload });
11674
+ } catch (error) {
11675
+ gitActionError(error);
11676
+ }
11677
+ return;
11678
+ }
11679
+ }
11680
+
11681
+ if (url.pathname.startsWith("/api/git-workflow/")) {
11682
+ const readOnlyWorkflow = GIT_WORKFLOW_READONLY_PATHS.has(url.pathname);
11683
+ const mutatingWorkflow = GIT_WORKFLOW_MUTATING_PATHS.has(url.pathname);
11684
+ if (readOnlyWorkflow || mutatingWorkflow) {
11685
+ const requiredMethod = mutatingWorkflow ? "POST" : "GET";
11686
+ if (req.method !== requiredMethod) {
11687
+ res.setHeader("Allow", requiredMethod);
11688
+ sendJson(res, 405, { ok: false, error: `${url.pathname} requires ${requiredMethod}` });
11689
+ return;
11690
+ }
11691
+ const body = mutatingWorkflow ? await readJsonBody(req) : {};
11692
+ const tab = getRequestedTab(req, url, body);
11693
+ if (mutatingWorkflow) ensureNaturalConversationRouteAllowed(tab, "git workflow actions are blocked");
11694
+ const response = await handleGitWorkflowRequest(url.pathname, body, tab);
11695
+ if (response) {
11696
+ sendJson(res, 200, response);
11697
+ return;
11698
+ }
11699
+ }
10304
11700
  }
10305
11701
 
10306
11702
  const getCommand = req.method === "GET" ? commandFromGet(url.pathname) : undefined;
@@ -10373,6 +11769,7 @@ const server = createServer(async (req, res) => {
10373
11769
  clearPendingExtensionUiRequests(tab);
10374
11770
  clearExtensionStatuses(tab);
10375
11771
  clearExtensionWidgets(tab);
11772
+ clearWebuiSubagents(tab);
10376
11773
  resetNaturalConversationMode(tab);
10377
11774
  }
10378
11775
  sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));