@firstpick/pi-package-webui 0.6.3 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/pi-webui.mjs CHANGED
@@ -40,9 +40,11 @@ import {
40
40
  WORKTREE_ERROR_CODES,
41
41
  createGitWorktree,
42
42
  gitWorktreeErrorPayload,
43
+ isGitLockFailure,
43
44
  listGitWorktrees,
44
45
  openGitWorktree,
45
46
  pathInside,
47
+ pruneGitWorktrees,
46
48
  removeGitWorktree,
47
49
  } from "../lib/git-worktrees.mjs";
48
50
 
@@ -94,6 +96,14 @@ const CLAUDE_USAGE_COMMAND = process.env.PI_WEBUI_CLAUDE_BIN || "claude";
94
96
  const CLAUDE_USAGE_ARGS = ["--safe-mode", "--no-session-persistence", "-p", "/usage", "--output-format", "json"];
95
97
  const BODY_LIMIT_BYTES = 1024 * 1024;
96
98
  const SKILL_FILE_BODY_LIMIT_BYTES = 2 * 1024 * 1024;
99
+ const FILE_VIEWER_MAX_BYTES = 2 * 1024 * 1024;
100
+ const FILE_VIEWER_BODY_LIMIT_BYTES = FILE_VIEWER_MAX_BYTES + 64 * 1024;
101
+ const FILE_TREE_MAX_ENTRIES = 1200;
102
+ const FILE_TREE_ENTRY_STAT_CONCURRENCY = 32;
103
+ const FILE_SEARCH_MAX_RESULTS = 200;
104
+ const FILE_SEARCH_MAX_SCANNED = 12_000;
105
+ const FILE_SEARCH_MAX_DEPTH = 8;
106
+ const FILE_SEARCH_EXCLUDED_DIRS = new Set([".git", "node_modules"]);
97
107
  const PROMPT_BODY_LIMIT_BYTES = 24 * 1024 * 1024;
98
108
  const VOICE_AUDIO_BODY_LIMIT_BYTES = 24 * 1024 * 1024;
99
109
  const VOICE_AUDIO_JSON_BODY_LIMIT_BYTES = Math.ceil(VOICE_AUDIO_BODY_LIMIT_BYTES * 1.4) + 1024 * 1024;
@@ -1108,17 +1118,21 @@ function runCommand(command, args, { cwd, timeoutMs = 2000, maxOutputLength = 20
1108
1118
  return new Promise((resolve) => {
1109
1119
  const child = spawn(command, args, {
1110
1120
  cwd,
1121
+ // LC_ALL=C keeps tool output in English so error classification works
1122
+ // regardless of locale.
1123
+ env: { ...process.env, LC_ALL: "C" },
1111
1124
  stdio: ["ignore", "pipe", "pipe"],
1112
1125
  windowsHide: true,
1113
1126
  });
1114
1127
  let stdout = "";
1115
1128
  let stderr = "";
1129
+ let stdoutTruncated = false;
1116
1130
  let settled = false;
1117
1131
  const finish = (result) => {
1118
1132
  if (settled) return;
1119
1133
  settled = true;
1120
1134
  clearTimeout(timeout);
1121
- resolve(result);
1135
+ resolve({ stdoutTruncated, ...result });
1122
1136
  };
1123
1137
  const timeout = setTimeout(() => {
1124
1138
  child.kill("SIGKILL");
@@ -1126,7 +1140,10 @@ function runCommand(command, args, { cwd, timeoutMs = 2000, maxOutputLength = 20
1126
1140
  }, timeoutMs);
1127
1141
  child.stdout.on("data", (chunk) => {
1128
1142
  stdout += String(chunk);
1129
- if (stdout.length > maxOutputLength) stdout = stdout.slice(-maxOutputLength);
1143
+ if (stdout.length > maxOutputLength) {
1144
+ stdout = stdout.slice(-maxOutputLength);
1145
+ stdoutTruncated = true;
1146
+ }
1130
1147
  });
1131
1148
  child.stderr.on("data", (chunk) => {
1132
1149
  stderr += String(chunk);
@@ -3935,6 +3952,7 @@ let activeGitWorkflowProcess = null;
3935
3952
  const GIT_CHANGES_COMMAND_TIMEOUT_MS = 5000;
3936
3953
  const GIT_CHANGES_DIFF_MAX_OUTPUT = 500_000;
3937
3954
  const GIT_PULL_TIMEOUT_MS = 15 * 60 * 1000;
3955
+ const GIT_STATUS_KIND_RANK = Object.freeze({ changed: 0, untracked: 1, modified: 2, staged: 3, conflicted: 4 });
3938
3956
 
3939
3957
  async function getGitRoot(cwd) {
3940
3958
  const result = await runCommand("git", ["rev-parse", "--show-toplevel"], { cwd, timeoutMs: 2000 });
@@ -3944,9 +3962,11 @@ async function getGitRoot(cwd) {
3944
3962
  return path.resolve(result.stdout.trim());
3945
3963
  }
3946
3964
 
3947
- async function runGitReadCommand(root, args, { timeoutMs = GIT_CHANGES_COMMAND_TIMEOUT_MS, maxOutputLength = GIT_CHANGES_DIFF_MAX_OUTPUT } = {}) {
3965
+ async function runGitReadCommandDetailed(root, args, { timeoutMs = GIT_CHANGES_COMMAND_TIMEOUT_MS, maxOutputLength = GIT_CHANGES_DIFF_MAX_OUTPUT } = {}) {
3948
3966
  const result = await runCommand("git", args, { cwd: root, timeoutMs, maxOutputLength });
3949
- if (result.exitCode === 0 && !result.timedOut && !result.error) return result.stdout;
3967
+ if (result.exitCode === 0 && !result.timedOut && !result.error) {
3968
+ return { output: result.stdout, truncated: result.stdoutTruncated === true, capBytes: maxOutputLength };
3969
+ }
3950
3970
  const command = formatGitCommand(args);
3951
3971
  const message = result.timedOut
3952
3972
  ? `${command} timed out`
@@ -3954,6 +3974,10 @@ async function runGitReadCommand(root, args, { timeoutMs = GIT_CHANGES_COMMAND_T
3954
3974
  throw new Error(String(message).trim());
3955
3975
  }
3956
3976
 
3977
+ async function runGitReadCommand(root, args, options = {}) {
3978
+ return (await runGitReadCommandDetailed(root, args, options)).output;
3979
+ }
3980
+
3957
3981
  function gitBranchFromPorcelainStatus(statusText) {
3958
3982
  for (const line of String(statusText || "").split(/\r?\n/)) {
3959
3983
  if (!line.startsWith("# branch.head ")) continue;
@@ -3995,6 +4019,118 @@ function summarizeGitPorcelainStatus(statusText) {
3995
4019
  return summary;
3996
4020
  }
3997
4021
 
4022
+ function normalizeGitStatusPath(value = "") {
4023
+ return String(value || "").replace(/\\/g, "/").replace(/^\.\/+/, "").replace(/\/+$/g, "");
4024
+ }
4025
+
4026
+ function gitStatusKindFromPorcelainEntry(entry = {}) {
4027
+ const x = entry.x || " ";
4028
+ const y = entry.y || " ";
4029
+ if (x === "?" && y === "?") return "untracked";
4030
+ if (x === "U" || y === "U" || (x === "A" && y === "A") || (x === "D" && y === "D")) return "conflicted";
4031
+ if (x !== " " && x !== "?" && x !== ".") return "staged";
4032
+ if (y !== " " && y !== "?" && y !== ".") return "modified";
4033
+ return "changed";
4034
+ }
4035
+
4036
+ function gitStatusLabelFromPorcelainEntry(entry = {}) {
4037
+ const x = entry.x || " ";
4038
+ const y = entry.y || " ";
4039
+ if (x === "?" && y === "?") return "??";
4040
+ return `${x}${y}`.replace(/\s/g, "").trim() || "•";
4041
+ }
4042
+
4043
+ function mergeGitStatusIndexEntry(index, repoPath, patch = {}) {
4044
+ const key = normalizeGitStatusPath(repoPath);
4045
+ if (!key) return;
4046
+ const existing = index.get(key) || { changed: true, kind: "changed", status: "", direct: false, changedDescendants: 0 };
4047
+ const existingRank = GIT_STATUS_KIND_RANK[existing.kind] ?? 0;
4048
+ const nextRank = GIT_STATUS_KIND_RANK[patch.kind] ?? 0;
4049
+ index.set(key, {
4050
+ changed: true,
4051
+ kind: nextRank > existingRank ? patch.kind : existing.kind,
4052
+ status: patch.direct === true ? (patch.status || existing.status || "") : (existing.status || ""),
4053
+ direct: existing.direct === true || patch.direct === true,
4054
+ changedDescendants: (Number(existing.changedDescendants || 0) || 0) + (Number(patch.changedDescendants || 0) || 0),
4055
+ });
4056
+ }
4057
+
4058
+ function addGitStatusAncestorEntries(index, repoPath, kind) {
4059
+ const parts = normalizeGitStatusPath(repoPath).split("/").filter(Boolean);
4060
+ parts.pop();
4061
+ let current = "";
4062
+ for (const part of parts) {
4063
+ current = current ? `${current}/${part}` : part;
4064
+ mergeGitStatusIndexEntry(index, current, { kind, changedDescendants: 1 });
4065
+ }
4066
+ }
4067
+
4068
+ function buildGitStatusIndexFromPorcelain(statusText = "") {
4069
+ const index = new Map();
4070
+ for (const entry of parseGitPorcelainZEntries(statusText)) {
4071
+ const filePath = normalizeGitStatusPath(entry.path);
4072
+ if (!filePath) continue;
4073
+ const kind = gitStatusKindFromPorcelainEntry(entry);
4074
+ mergeGitStatusIndexEntry(index, filePath, { kind, status: gitStatusLabelFromPorcelainEntry(entry), direct: true });
4075
+ addGitStatusAncestorEntries(index, filePath, kind);
4076
+ if (entry.oldPath) addGitStatusAncestorEntries(index, entry.oldPath, kind);
4077
+ }
4078
+ return index;
4079
+ }
4080
+
4081
+ async function readWorkspaceGitStatusIndex(workspaceRoot) {
4082
+ try {
4083
+ const root = await getGitRoot(workspaceRoot);
4084
+ const statusText = await runGitReadCommand(root, ["status", "--porcelain=v1", "-z", "--untracked-files=all"], { maxOutputLength: 120_000 });
4085
+ return { root, entries: buildGitStatusIndexFromPorcelain(statusText) };
4086
+ } catch {
4087
+ return null;
4088
+ }
4089
+ }
4090
+
4091
+ function gitStatusForWorkspaceEntry(workspaceRoot, entry, gitStatus) {
4092
+ if (!gitStatus?.root || !gitStatus.entries?.size || !entry?.path) return null;
4093
+ const absolute = path.resolve(workspaceRoot, entry.path);
4094
+ if (absolute !== gitStatus.root && !pathInside(gitStatus.root, absolute)) return null;
4095
+ const repoPath = normalizeGitStatusPath(path.relative(gitStatus.root, absolute).split(path.sep).join("/"));
4096
+ const status = gitStatus.entries.get(repoPath);
4097
+ if (!status?.changed) return null;
4098
+ return {
4099
+ changed: true,
4100
+ kind: status.kind || "changed",
4101
+ status: status.status || "",
4102
+ direct: status.direct === true,
4103
+ changedDescendants: Number(status.changedDescendants || 0) || 0,
4104
+ };
4105
+ }
4106
+
4107
+ function withFileTreeGitStatus(entries = [], workspaceRoot, gitStatus) {
4108
+ if (!gitStatus?.entries?.size) return entries;
4109
+ return entries.map((entry) => {
4110
+ const status = gitStatusForWorkspaceEntry(workspaceRoot, entry, gitStatus);
4111
+ return status ? { ...entry, gitStatus: status } : entry;
4112
+ });
4113
+ }
4114
+
4115
+ function fileTreeGitStatusPayload(workspaceRoot, gitStatus) {
4116
+ if (!gitStatus?.root || !gitStatus.entries?.size) return null;
4117
+ const root = path.resolve(workspaceRoot);
4118
+ const entries = [];
4119
+ for (const [repoPath, status] of gitStatus.entries.entries()) {
4120
+ const absolute = path.resolve(gitStatus.root, repoPath);
4121
+ if (absolute !== root && !pathInside(root, absolute)) continue;
4122
+ entries.push({
4123
+ path: path.relative(root, absolute).split(path.sep).join("/"),
4124
+ changed: true,
4125
+ kind: status.kind || "changed",
4126
+ status: status.status || "",
4127
+ direct: status.direct === true,
4128
+ changedDescendants: Number(status.changedDescendants || 0) || 0,
4129
+ });
4130
+ }
4131
+ return { root: gitStatus.root, entries };
4132
+ }
4133
+
3998
4134
  function resolveGitRelativePath(root, relativePath) {
3999
4135
  const normalized = String(relativePath || "").trim();
4000
4136
  if (!normalized || normalized.includes("\0")) throw new Error("Invalid git path");
@@ -4059,23 +4195,31 @@ async function gitUpstreamRef(root) {
4059
4195
 
4060
4196
  async function readGitIncomingChanges(root, summary) {
4061
4197
  const upstream = await gitUpstreamRef(root);
4198
+ const ahead = Number(summary?.ahead || 0) || 0;
4199
+ const behind = Number(summary?.behind || 0) || 0;
4200
+ const diverged = ahead > 0 && behind > 0;
4062
4201
  const remote = {
4063
4202
  upstream,
4064
- behind: Number(summary?.behind || 0) || 0,
4065
- canPull: !!upstream && (Number(summary?.behind || 0) || 0) > 0,
4203
+ ahead,
4204
+ behind,
4205
+ diverged,
4206
+ // Fast-forward pull is only possible when we are strictly behind.
4207
+ canPull: !!upstream && behind > 0 && !diverged,
4066
4208
  };
4067
- if (!remote.canPull) return { remote, section: null };
4209
+ if (!upstream || behind <= 0) return { remote, section: null };
4068
4210
 
4069
4211
  const diffArgs = ["diff", "--no-ext-diff", "--no-color", "--find-renames", "--unified=0", "--src-prefix=a/", "--dst-prefix=b/", "HEAD..@{upstream}"];
4070
4212
  try {
4071
- const diff = await runGitReadCommand(root, diffArgs);
4213
+ const diff = await runGitReadCommandDetailed(root, diffArgs);
4072
4214
  return {
4073
4215
  remote,
4074
4216
  section: {
4075
4217
  key: "incoming",
4076
4218
  label: `Incoming from ${upstream}`,
4077
4219
  command: `git diff --unified=0 HEAD..${upstream}`,
4078
- diff: diff.trimEnd(),
4220
+ diff: diff.output.trimEnd(),
4221
+ truncated: diff.truncated,
4222
+ capBytes: diff.capBytes,
4079
4223
  },
4080
4224
  };
4081
4225
  } catch (error) {
@@ -4085,10 +4229,13 @@ async function readGitIncomingChanges(root, summary) {
4085
4229
 
4086
4230
  async function pullGitChanges(cwd) {
4087
4231
  const root = await getGitRoot(cwd);
4088
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(["pull", "--ff-only"], { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS }));
4232
+ const payload = await runGuardedGitMutation(["pull", "--ff-only"], { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS });
4089
4233
  if (payload.data) payload.data.root = root;
4090
4234
  if (payload.ok) payload.data.changes = await readGitChanges(root);
4091
- else payload.error = (payload.data?.stderr || payload.data?.stdout || payload.error || "git pull --ff-only failed").trim();
4235
+ else {
4236
+ payload.error = (payload.data?.stderr || payload.data?.stdout || payload.error || "git pull --ff-only failed").trim();
4237
+ applyGitSyncFailure(payload);
4238
+ }
4092
4239
  return payload;
4093
4240
  }
4094
4241
 
@@ -4098,8 +4245,8 @@ async function readGitChanges(cwd) {
4098
4245
  const [statusText, porcelainStatusText, unstagedDiff, stagedDiff, untrackedText] = await Promise.all([
4099
4246
  runGitReadCommand(root, ["status", "--short", "--branch", "--untracked-files=all"], { maxOutputLength: 120_000 }),
4100
4247
  runGitReadCommand(root, ["status", "--porcelain=2", "--branch", "--untracked-files=all"], { maxOutputLength: 120_000 }),
4101
- runGitReadCommand(root, diffArgs),
4102
- runGitReadCommand(root, ["diff", "--cached", "--no-ext-diff", "--no-color", "--find-renames", "--unified=0", "--src-prefix=a/", "--dst-prefix=b/"]),
4248
+ runGitReadCommandDetailed(root, diffArgs),
4249
+ runGitReadCommandDetailed(root, ["diff", "--cached", "--no-ext-diff", "--no-color", "--find-renames", "--unified=0", "--src-prefix=a/", "--dst-prefix=b/"]),
4103
4250
  runGitReadCommand(root, ["ls-files", "--others", "--exclude-standard"], { maxOutputLength: 120_000 }),
4104
4251
  ]);
4105
4252
  const summary = summarizeGitPorcelainStatus(porcelainStatusText);
@@ -4116,13 +4263,670 @@ async function readGitChanges(cwd) {
4116
4263
  status: statusText.trimEnd(),
4117
4264
  sections: [
4118
4265
  incoming.section,
4119
- { key: "staged", label: "Staged", command: "git diff --cached --unified=0", diff: stagedDiff.trimEnd() },
4120
- { key: "unstaged", label: "Unstaged", command: "git diff --unified=0", diff: unstagedDiff.trimEnd() },
4266
+ { key: "staged", label: "Staged", command: "git diff --cached --unified=0", diff: stagedDiff.output.trimEnd(), truncated: stagedDiff.truncated, capBytes: stagedDiff.capBytes },
4267
+ { key: "unstaged", label: "Unstaged", command: "git diff --unified=0", diff: unstagedDiff.output.trimEnd(), truncated: unstagedDiff.truncated, capBytes: unstagedDiff.capBytes },
4121
4268
  ].filter(Boolean),
4122
4269
  untracked,
4123
4270
  };
4124
4271
  }
4125
4272
 
4273
+ const GIT_LOCK_RETRY_ATTEMPTS = 3;
4274
+ const GIT_LOCK_RETRY_DELAY_MS = 250;
4275
+ const GIT_FETCH_TIMEOUT_MS = 2 * 60 * 1000;
4276
+ const GIT_CONFLICT_PREVIEW_MAX_BYTES = 200_000;
4277
+ const GIT_STASH_PATCH_MAX_OUTPUT = 200_000;
4278
+ const PROTECTED_GIT_BRANCHES = new Set(["main", "master"]);
4279
+
4280
+ const sleepMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4281
+
4282
+ function requireConfirmed(body, action) {
4283
+ if (body?.confirmed !== true) throw makeHttpError(409, `${action} requires confirmed: true.`);
4284
+ }
4285
+
4286
+ // Retry transient index.lock contention before reporting failure; the shared
4287
+ // isGitLockFailure classifier keeps this consistent with worktree mutations.
4288
+ async function runGitMutationCommand(args, options = {}) {
4289
+ let result;
4290
+ for (let attempt = 0; attempt < GIT_LOCK_RETRY_ATTEMPTS; attempt++) {
4291
+ result = await runGitWorkflowCommand(args, options);
4292
+ const ok = result.exitCode === 0 && !result.timedOut && !result.cancelled && !result.error;
4293
+ if (ok || !isGitLockFailure(result)) return result;
4294
+ if (attempt < GIT_LOCK_RETRY_ATTEMPTS - 1) await sleepMs(GIT_LOCK_RETRY_DELAY_MS * (attempt + 1));
4295
+ }
4296
+ return result;
4297
+ }
4298
+
4299
+ function gitMutationPayload(result) {
4300
+ const payload = gitWorkflowCommandPayload(result);
4301
+ if (!payload.ok) {
4302
+ if (isGitLockFailure(result)) {
4303
+ payload.code = "REPO_BUSY";
4304
+ payload.hint = "Another git process is using this repository. Retry once it finishes.";
4305
+ }
4306
+ payload.error = String(result?.stderr || result?.stdout || payload.error || "git command failed").trim();
4307
+ }
4308
+ return payload;
4309
+ }
4310
+
4311
+ async function runGuardedGitMutation(args, options = {}) {
4312
+ try {
4313
+ return gitMutationPayload(await runGitMutationCommand(args, options));
4314
+ } catch (error) {
4315
+ if (/already running/i.test(error?.message || "")) {
4316
+ return { ok: false, code: "REPO_BUSY", error: sanitizeError(error), hint: "Another git workflow command is already running in the Web UI." };
4317
+ }
4318
+ throw error;
4319
+ }
4320
+ }
4321
+
4322
+ // Turn raw git remote-operation stderr into an actionable state. Returns null
4323
+ // when no known pattern matches (caller keeps the raw error).
4324
+ function classifyGitSyncFailure(result, { push = false } = {}) {
4325
+ const text = `${result?.stderr || ""}\n${result?.stdout || ""}`.toLowerCase();
4326
+ if (result?.timedOut) return { code: "NETWORK", hint: "The remote did not respond before the timeout. Check connectivity and retry." };
4327
+ if (isGitLockFailure(result)) return { code: "REPO_BUSY", hint: "Another git process is using this repository. Retry once it finishes." };
4328
+ if (/terminal prompts disabled|authentication failed|permission denied|access denied|could not read username|could not read password|publickey|invalid credentials/.test(text)) {
4329
+ 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." };
4330
+ }
4331
+ if (/could not resolve host|failed to connect|connection (?:refused|reset|timed out)|network is unreachable|operation timed out/.test(text)) {
4332
+ return { code: "NETWORK", hint: "The remote could not be reached. Check connectivity and retry." };
4333
+ }
4334
+ if (push && /protected branch|gh006/.test(text)) {
4335
+ 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." };
4336
+ }
4337
+ if (push && /\[rejected\]|non-fast-forward|fetch first|updates were rejected/.test(text)) {
4338
+ return { code: "NON_FAST_FORWARD", hint: "The remote has commits you don't have. Fetch and review the incoming diff, then integrate before pushing." };
4339
+ }
4340
+ if (push && /has no upstream branch/.test(text)) {
4341
+ return { code: "NO_UPSTREAM", hint: "The current branch has no upstream. Push with 'set upstream' to publish it." };
4342
+ }
4343
+ if (!push && /not possible to fast-forward|divergent branches|need to specify how to reconcile/.test(text)) {
4344
+ 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." };
4345
+ }
4346
+ if (!push && /no tracking information/.test(text)) {
4347
+ return { code: "NO_UPSTREAM", hint: "The current branch has no upstream to pull from. Set one or pull with an explicit remote/branch." };
4348
+ }
4349
+ if (/would be overwritten/.test(text)) {
4350
+ return { code: "DIRTY_WORKTREE", hint: "Local changes would be overwritten. Stash or commit them first." };
4351
+ }
4352
+ if (/conflict/.test(text)) {
4353
+ return { code: "CONFLICTS", hint: "Conflicts were created. Resolve them in the conflicts panel, then continue or abort the operation." };
4354
+ }
4355
+ return null;
4356
+ }
4357
+
4358
+ function applyGitSyncFailure(payload, { push = false } = {}) {
4359
+ if (payload.ok || payload.code) return payload;
4360
+ const classified = classifyGitSyncFailure(payload.data, { push });
4361
+ if (classified) {
4362
+ payload.code = classified.code;
4363
+ payload.hint = classified.hint;
4364
+ }
4365
+ return payload;
4366
+ }
4367
+
4368
+ async function fetchGitChanges(cwd) {
4369
+ const root = await getGitRoot(cwd);
4370
+ const payload = await runGuardedGitMutation(
4371
+ ["-c", "credential.interactive=false", "fetch", "--prune"],
4372
+ { cwd: root, timeoutMs: GIT_FETCH_TIMEOUT_MS, label: "git fetch --prune" },
4373
+ );
4374
+ if (payload.data) payload.data.root = root;
4375
+ if (payload.ok) {
4376
+ // git fetch reports ref updates on stderr.
4377
+ payload.data.summary = `${payload.data.stderr || ""}\n${payload.data.stdout || ""}`.trim();
4378
+ payload.data.changes = await readGitChanges(root);
4379
+ } else {
4380
+ applyGitSyncFailure(payload);
4381
+ }
4382
+ return payload;
4383
+ }
4384
+
4385
+ async function integrateGitUpstream(cwd, body = {}) {
4386
+ const mode = String(body.mode || "").trim();
4387
+ if (!["merge", "rebase"].includes(mode)) throw makeHttpError(400, "mode must be 'merge' or 'rebase'");
4388
+ requireConfirmed(body, `Running git ${mode} against the upstream`);
4389
+ const root = await getGitRoot(cwd);
4390
+ const upstream = await gitUpstreamRef(root);
4391
+ if (!upstream) throw makeHttpError(409, "No upstream is configured for the current branch");
4392
+ const args = mode === "merge" ? ["merge", "--no-edit", "@{upstream}"] : ["-c", "core.editor=true", "rebase", "@{upstream}"];
4393
+ const payload = await runGuardedGitMutation(args, { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS, label: `git ${mode} ${upstream}` });
4394
+ if (payload.data) {
4395
+ payload.data.root = root;
4396
+ payload.data.upstream = upstream;
4397
+ payload.data.mode = mode;
4398
+ }
4399
+ if (payload.ok) payload.data.changes = await readGitChanges(root);
4400
+ else applyGitSyncFailure(payload);
4401
+ return payload;
4402
+ }
4403
+
4404
+ // ---- Git operation (merge/rebase/cherry-pick/revert/bisect) lifecycle ----
4405
+
4406
+ async function pathEntryExists(target) {
4407
+ try {
4408
+ await stat(target);
4409
+ return true;
4410
+ } catch {
4411
+ return false;
4412
+ }
4413
+ }
4414
+
4415
+ async function gitDirPath(root) {
4416
+ const out = await runGitReadCommand(root, ["rev-parse", "--git-dir"], { maxOutputLength: 10_000 });
4417
+ const dir = out.trim();
4418
+ return path.isAbsolute(dir) ? dir : path.resolve(root, dir);
4419
+ }
4420
+
4421
+ async function detectGitOperationKind(root) {
4422
+ const gitDir = await gitDirPath(root);
4423
+ if ((await pathEntryExists(path.join(gitDir, "rebase-merge"))) || (await pathEntryExists(path.join(gitDir, "rebase-apply")))) return "rebase";
4424
+ if (await pathEntryExists(path.join(gitDir, "MERGE_HEAD"))) return "merge";
4425
+ if (await pathEntryExists(path.join(gitDir, "CHERRY_PICK_HEAD"))) return "cherry-pick";
4426
+ if (await pathEntryExists(path.join(gitDir, "REVERT_HEAD"))) return "revert";
4427
+ if (await pathEntryExists(path.join(gitDir, "BISECT_LOG"))) return "bisect";
4428
+ return null;
4429
+ }
4430
+
4431
+ function gitOperationCommands(kind) {
4432
+ switch (kind) {
4433
+ case "merge":
4434
+ return { continue: ["commit", "--no-edit"], abort: ["merge", "--abort"], skip: null };
4435
+ case "rebase":
4436
+ return { continue: ["-c", "core.editor=true", "rebase", "--continue"], abort: ["rebase", "--abort"], skip: ["-c", "core.editor=true", "rebase", "--skip"] };
4437
+ case "cherry-pick":
4438
+ return { continue: ["-c", "core.editor=true", "cherry-pick", "--continue"], abort: ["cherry-pick", "--abort"], skip: ["-c", "core.editor=true", "cherry-pick", "--skip"] };
4439
+ case "revert":
4440
+ return { continue: ["-c", "core.editor=true", "revert", "--continue"], abort: ["revert", "--abort"], skip: ["-c", "core.editor=true", "revert", "--skip"] };
4441
+ default:
4442
+ return null;
4443
+ }
4444
+ }
4445
+
4446
+ function parseGitConflictEntries(porcelainText) {
4447
+ const entries = [];
4448
+ for (const line of String(porcelainText || "").split(/\r?\n/)) {
4449
+ if (!line.startsWith("u ")) continue;
4450
+ // u XY sub m1 m2 m3 mW h1 h2 h3 path — 10 space-separated fields, then path.
4451
+ const fields = [];
4452
+ let start = 0;
4453
+ for (let index = 0; index < 10; index++) {
4454
+ const next = line.indexOf(" ", start);
4455
+ if (next === -1) break;
4456
+ fields.push(line.slice(start, next));
4457
+ start = next + 1;
4458
+ }
4459
+ fields.push(line.slice(start));
4460
+ const entryPath = fields[10] || "";
4461
+ if (entryPath) entries.push({ path: entryPath, status: fields[1] || "UU" });
4462
+ }
4463
+ return entries;
4464
+ }
4465
+
4466
+ function extractConflictMarkerHunks(content, { contextLines = 2, maxHunks = 8, maxLinesPerHunk = 80 } = {}) {
4467
+ const lines = content.split(/\r?\n/);
4468
+ const hunks = [];
4469
+ for (let index = 0; index < lines.length && hunks.length < maxHunks; index++) {
4470
+ if (!lines[index].startsWith("<<<<<<<")) continue;
4471
+ let end = index;
4472
+ while (end < lines.length - 1 && !lines[end].startsWith(">>>>>>>")) end++;
4473
+ const start = Math.max(0, index - contextLines);
4474
+ const stop = Math.min(lines.length - 1, end + contextLines);
4475
+ hunks.push({
4476
+ startLine: start + 1,
4477
+ truncated: stop - start + 1 > maxLinesPerHunk,
4478
+ lines: lines.slice(start, Math.min(stop + 1, start + maxLinesPerHunk)),
4479
+ });
4480
+ index = end;
4481
+ }
4482
+ return hunks;
4483
+ }
4484
+
4485
+ async function readGitConflictPreview(root, relPath) {
4486
+ try {
4487
+ const filePath = resolveGitRelativePath(root, relPath);
4488
+ const info = await stat(filePath).catch(() => null);
4489
+ if (!info) return { kind: "missing" };
4490
+ if (!info.isFile()) return { kind: "unsupported", size: info.size };
4491
+ if (info.size > GIT_CONFLICT_PREVIEW_MAX_BYTES) return { kind: "large", size: info.size };
4492
+ const buffer = await readFile(filePath);
4493
+ if (isLikelyBinaryBuffer(buffer)) return { kind: "binary", size: info.size };
4494
+ const content = buffer.toString("utf8");
4495
+ return {
4496
+ kind: "text",
4497
+ size: info.size,
4498
+ hasMarkers: /^<{7}(?: |$)/m.test(content),
4499
+ hunks: extractConflictMarkerHunks(content),
4500
+ };
4501
+ } catch (error) {
4502
+ return { kind: "error", error: sanitizeError(error) };
4503
+ }
4504
+ }
4505
+
4506
+ async function readGitOperationSnapshot(cwd) {
4507
+ const root = await getGitRoot(cwd);
4508
+ const porcelainText = await runGitReadCommand(root, ["status", "--porcelain=2", "--branch", "--untracked-files=all"], { maxOutputLength: 120_000 });
4509
+ const summary = summarizeGitPorcelainStatus(porcelainText);
4510
+ const kind = await detectGitOperationKind(root);
4511
+ const conflictEntries = parseGitConflictEntries(porcelainText);
4512
+ const conflicts = [];
4513
+ for (const entry of conflictEntries) {
4514
+ conflicts.push({ ...entry, preview: await readGitConflictPreview(root, entry.path) });
4515
+ }
4516
+ const commands = gitOperationCommands(kind);
4517
+ let bisect = null;
4518
+ if (kind === "bisect") {
4519
+ const log = await runGitReadCommand(root, ["bisect", "log"], { maxOutputLength: 60_000 }).catch(() => "");
4520
+ bisect = { log: log.trimEnd().split(/\r?\n/).slice(-20).join("\n") };
4521
+ }
4522
+ return {
4523
+ root,
4524
+ branch: gitBranchFromPorcelainStatus(porcelainText),
4525
+ operation: kind,
4526
+ summary,
4527
+ conflicts,
4528
+ canContinue: Boolean(kind) && kind !== "bisect" && conflictEntries.length === 0,
4529
+ canSkip: Boolean(commands?.skip),
4530
+ commands: commands
4531
+ ? {
4532
+ continue: formatGitCommand(commands.continue.filter((arg) => arg !== "-c" && arg !== "core.editor=true")),
4533
+ abort: formatGitCommand(commands.abort),
4534
+ ...(commands.skip ? { skip: formatGitCommand(commands.skip.filter((arg) => arg !== "-c" && arg !== "core.editor=true")) } : {}),
4535
+ }
4536
+ : null,
4537
+ bisect,
4538
+ generatedAt: new Date().toISOString(),
4539
+ };
4540
+ }
4541
+
4542
+ async function gitOperationStageFile(cwd, body = {}) {
4543
+ const root = await getGitRoot(cwd);
4544
+ const kind = await detectGitOperationKind(root);
4545
+ if (!kind) throw makeHttpError(409, "No git operation is in progress");
4546
+ const rel = normalizeGitRelativePath(root, body.path);
4547
+ const payload = await runGuardedGitMutation(["add", "--", rel], { cwd: root, label: `git add -- ${rel}` });
4548
+ if (payload.data) payload.data.root = root;
4549
+ if (payload.ok) payload.data.operation = await readGitOperationSnapshot(root);
4550
+ return payload;
4551
+ }
4552
+
4553
+ async function gitOperationAction(cwd, action, body = {}) {
4554
+ const root = await getGitRoot(cwd);
4555
+ const kind = await detectGitOperationKind(root);
4556
+ if (!kind) throw makeHttpError(409, "No git operation is in progress");
4557
+ if (kind === "bisect") throw makeHttpError(409, "Bisect is controlled through /api/git-operation/bisect");
4558
+ const commands = gitOperationCommands(kind);
4559
+
4560
+ let args;
4561
+ if (action === "continue") {
4562
+ const porcelainText = await runGitReadCommand(root, ["status", "--porcelain=2"], { maxOutputLength: 120_000 });
4563
+ if (parseGitConflictEntries(porcelainText).length > 0) {
4564
+ return { ok: false, code: "UNMERGED_PATHS", error: "Unmerged paths remain. Resolve and stage every conflicted file before continuing." };
4565
+ }
4566
+ args = commands.continue;
4567
+ } else if (action === "skip") {
4568
+ if (!commands.skip) throw makeHttpError(409, `git ${kind} does not support skip`);
4569
+ args = commands.skip;
4570
+ } else if (action === "abort") {
4571
+ requireConfirmed(body, `Aborting the ${kind} operation discards its in-progress state and`);
4572
+ args = commands.abort;
4573
+ } else {
4574
+ throw makeHttpError(400, "Unknown git operation action");
4575
+ }
4576
+
4577
+ const payload = await runGuardedGitMutation(args, { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS });
4578
+ if (payload.data) {
4579
+ payload.data.root = root;
4580
+ payload.data.kind = kind;
4581
+ }
4582
+ if (payload.ok) payload.data.operation = await readGitOperationSnapshot(root);
4583
+ else applyGitSyncFailure(payload);
4584
+ return payload;
4585
+ }
4586
+
4587
+ const GIT_BISECT_VERDICTS = new Set(["good", "bad", "old", "new", "skip", "reset"]);
4588
+
4589
+ async function gitBisectAction(cwd, body = {}) {
4590
+ const verdict = String(body.verdict || "").trim().toLowerCase();
4591
+ if (!GIT_BISECT_VERDICTS.has(verdict)) throw makeHttpError(400, "verdict must be one of good, bad, old, new, skip, reset");
4592
+ const root = await getGitRoot(cwd);
4593
+ const kind = await detectGitOperationKind(root);
4594
+ if (kind !== "bisect") throw makeHttpError(409, "No git bisect is in progress");
4595
+ if (verdict === "reset") requireConfirmed(body, "Resetting the bisect session");
4596
+ const payload = await runGuardedGitMutation(["bisect", verdict], { cwd: root });
4597
+ if (payload.data) payload.data.root = root;
4598
+ if (payload.ok) payload.data.operation = await readGitOperationSnapshot(root);
4599
+ return payload;
4600
+ }
4601
+
4602
+ // ---- Stash ----
4603
+
4604
+ function cleanGitStashRef(value) {
4605
+ const ref = String(value || "").trim();
4606
+ if (!/^stash@\{\d{1,4}\}$/.test(ref)) throw makeHttpError(400, "stash ref must look like stash@{0}");
4607
+ return ref;
4608
+ }
4609
+
4610
+ async function readGitStashes(cwd) {
4611
+ const root = await getGitRoot(cwd);
4612
+ const out = await runGitReadCommand(root, ["stash", "list", "--format=%gd%x09%at%x09%gs"], { maxOutputLength: 120_000 });
4613
+ const stashes = out
4614
+ .split(/\r?\n/)
4615
+ .filter(Boolean)
4616
+ .map((line) => {
4617
+ const [ref, epoch, ...subject] = line.split("\t");
4618
+ return { ref: ref || "", epochSeconds: Number.parseInt(epoch || "0", 10) || 0, subject: subject.join("\t") };
4619
+ })
4620
+ .filter((entry) => entry.ref);
4621
+ return { root, stashes, generatedAt: new Date().toISOString() };
4622
+ }
4623
+
4624
+ async function readGitStashPreview(cwd, requestedRef) {
4625
+ const root = await getGitRoot(cwd);
4626
+ const ref = cleanGitStashRef(requestedRef);
4627
+ const [statText, patchText] = await Promise.all([
4628
+ runGitReadCommand(root, ["stash", "show", "--include-untracked", "--stat", ref], { maxOutputLength: 120_000 }).catch((error) => `(${sanitizeError(error)})`),
4629
+ runGitReadCommand(root, ["stash", "show", "--include-untracked", "-p", ref], { maxOutputLength: GIT_STASH_PATCH_MAX_OUTPUT }).catch(() => ""),
4630
+ ]);
4631
+ return { root, ref, stat: statText.trimEnd(), patch: patchText.trimEnd() };
4632
+ }
4633
+
4634
+ async function saveGitStash(cwd, body = {}) {
4635
+ const root = await getGitRoot(cwd);
4636
+ const args = ["stash", "push"];
4637
+ if (body.includeUntracked === true) args.push("--include-untracked");
4638
+ if (body.message) args.push("-m", cleanGitCommitMessageInput(body.message));
4639
+ const payload = await runGuardedGitMutation(args, { cwd: root });
4640
+ if (payload.data) payload.data.root = root;
4641
+ if (payload.ok) payload.data.stashes = (await readGitStashes(root)).stashes;
4642
+ return payload;
4643
+ }
4644
+
4645
+ async function applyGitStash(cwd, body = {}, { pop = false } = {}) {
4646
+ const root = await getGitRoot(cwd);
4647
+ const ref = cleanGitStashRef(body.ref);
4648
+ const payload = await runGuardedGitMutation(["stash", pop ? "pop" : "apply", ref], { cwd: root });
4649
+ if (payload.data) {
4650
+ payload.data.root = root;
4651
+ payload.data.ref = ref;
4652
+ }
4653
+ if (payload.ok) payload.data.stashes = (await readGitStashes(root)).stashes;
4654
+ else if (!payload.code && /conflict/i.test(payload.error || "")) {
4655
+ payload.code = "CONFLICTS";
4656
+ payload.hint = pop
4657
+ ? "The stash conflicts with the working tree; git kept the stash entry. Resolve the conflicts, then drop the stash manually."
4658
+ : "The stash conflicts with the working tree. Resolve the conflicts or reset the working tree.";
4659
+ }
4660
+ return payload;
4661
+ }
4662
+
4663
+ async function dropGitStash(cwd, body = {}) {
4664
+ requireConfirmed(body, "Dropping a stash permanently deletes it and");
4665
+ const root = await getGitRoot(cwd);
4666
+ const ref = cleanGitStashRef(body.ref);
4667
+ const payload = await runGuardedGitMutation(["stash", "drop", ref], { cwd: root });
4668
+ if (payload.data) {
4669
+ payload.data.root = root;
4670
+ payload.data.ref = ref;
4671
+ }
4672
+ if (payload.ok) payload.data.stashes = (await readGitStashes(root)).stashes;
4673
+ return payload;
4674
+ }
4675
+
4676
+ // ---- File-level staging ----
4677
+
4678
+ async function stageGitFile(cwd, body = {}) {
4679
+ const root = await getGitRoot(cwd);
4680
+ const rel = normalizeGitRelativePath(root, body.path);
4681
+ const payload = await runGuardedGitMutation(["add", "--", rel], { cwd: root, label: `git add -- ${rel}` });
4682
+ if (payload.data) payload.data.root = root;
4683
+ if (payload.ok) payload.data.changes = await readGitChanges(root);
4684
+ return payload;
4685
+ }
4686
+
4687
+ async function unstageGitFile(cwd, body = {}) {
4688
+ const root = await getGitRoot(cwd);
4689
+ const rel = normalizeGitRelativePath(root, body.path);
4690
+ let payload = await runGuardedGitMutation(["restore", "--staged", "--", rel], { cwd: root, label: `git restore --staged -- ${rel}` });
4691
+ if (!payload.ok && /HEAD/.test(payload.error || "")) {
4692
+ // Unborn branch (no commit yet): restore --staged has no HEAD to restore from.
4693
+ payload = await runGuardedGitMutation(["rm", "--cached", "-r", "--", rel], { cwd: root, label: `git rm --cached -- ${rel}` });
4694
+ }
4695
+ if (payload.data) payload.data.root = root;
4696
+ if (payload.ok) payload.data.changes = await readGitChanges(root);
4697
+ return payload;
4698
+ }
4699
+
4700
+ async function discardGitFile(cwd, body = {}) {
4701
+ requireConfirmed(body, "Discarding file changes is destructive and");
4702
+ const root = await getGitRoot(cwd);
4703
+ const rel = normalizeGitRelativePath(root, body.path);
4704
+ const payload = await runGuardedGitMutation(["restore", "--", rel], { cwd: root, label: `git restore -- ${rel}` });
4705
+ if (payload.data) payload.data.root = root;
4706
+ if (payload.ok) payload.data.changes = await readGitChanges(root);
4707
+ return payload;
4708
+ }
4709
+
4710
+ async function deleteGitUntrackedFile(cwd, body = {}) {
4711
+ requireConfirmed(body, "Deleting an untracked file is destructive and");
4712
+ const root = await getGitRoot(cwd);
4713
+ const rel = normalizeGitRelativePath(root, body.path);
4714
+ const listed = await runGitReadCommand(root, ["ls-files", "--others", "--exclude-standard", "--", rel], { maxOutputLength: 120_000 });
4715
+ const files = listed.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
4716
+ if (!files.includes(rel)) throw makeHttpError(409, `Not an untracked file: ${rel}`);
4717
+ await rm(resolveGitRelativePath(root, rel));
4718
+ return { ok: true, data: { root, path: rel, deleted: true, changes: await readGitChanges(root) } };
4719
+ }
4720
+
4721
+ // ---- Undo / recovery ----
4722
+
4723
+ async function readGitUndoState(cwd) {
4724
+ const root = await getGitRoot(cwd);
4725
+ const [parentProbe, porcelainText, upstream, operation, lastLog] = await Promise.all([
4726
+ runCommand("git", ["rev-parse", "--verify", "--quiet", "HEAD~1"], { cwd: root, timeoutMs: 2000 }),
4727
+ runGitReadCommand(root, ["status", "--porcelain=2", "--branch"], { maxOutputLength: 120_000 }),
4728
+ gitUpstreamRef(root),
4729
+ detectGitOperationKind(root),
4730
+ runGitReadCommand(root, ["log", "-1", "--format=%h%x09%s"], { maxOutputLength: 10_000 }).catch(() => ""),
4731
+ ]);
4732
+ const summary = summarizeGitPorcelainStatus(porcelainText);
4733
+ const hasParent = parentProbe.exitCode === 0;
4734
+ const [lastHash = "", ...subjectParts] = lastLog.trim().split("\t");
4735
+ const lastSubject = subjectParts.join("\t");
4736
+ // With an upstream, "unpushed" means ahead > 0; without one nothing has been
4737
+ // published through this branch's tracking ref.
4738
+ const unpushed = upstream ? summary.ahead > 0 : true;
4739
+ return {
4740
+ root,
4741
+ hasParent,
4742
+ upstream,
4743
+ operation,
4744
+ summary,
4745
+ lastCommit: lastHash ? { hash: lastHash, subject: lastSubject } : null,
4746
+ canUndoLastCommit: hasParent && unpushed && !operation,
4747
+ canAmendMessage: Boolean(lastHash) && unpushed && !operation && summary.staged === 0,
4748
+ };
4749
+ }
4750
+
4751
+ async function undoLastGitCommit(cwd, body = {}) {
4752
+ requireConfirmed(body, "Undoing the last commit rewrites HEAD and");
4753
+ const state = await readGitUndoState(cwd);
4754
+ if (!state.hasParent) throw makeHttpError(409, "HEAD has no parent commit to undo to");
4755
+ if (state.operation) throw makeHttpError(409, `Cannot undo during a ${state.operation} operation`);
4756
+ if (!state.canUndoLastCommit) throw makeHttpError(409, "The last commit is already pushed to the upstream; undoing it would rewrite published history");
4757
+ const payload = await runGuardedGitMutation(["reset", "--soft", "HEAD~1"], { cwd: state.root });
4758
+ if (payload.data) {
4759
+ payload.data.root = state.root;
4760
+ payload.data.undoneCommit = state.lastCommit;
4761
+ payload.data.restoreCommand = "git reset --soft ORIG_HEAD";
4762
+ }
4763
+ if (payload.ok) payload.data.changes = await readGitChanges(state.root);
4764
+ return payload;
4765
+ }
4766
+
4767
+ async function amendLastGitCommitMessage(cwd, body = {}) {
4768
+ requireConfirmed(body, "Amending the last commit rewrites HEAD and");
4769
+ const message = cleanGitCommitMessageInput(body.message);
4770
+ const state = await readGitUndoState(cwd);
4771
+ if (!state.lastCommit) throw makeHttpError(409, "There is no commit to amend");
4772
+ if (state.operation) throw makeHttpError(409, `Cannot amend during a ${state.operation} operation`);
4773
+ 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.");
4774
+ if (!state.canAmendMessage) throw makeHttpError(409, "The last commit is already pushed to the upstream; amending it would rewrite published history");
4775
+ const payload = await runGuardedGitMutation(["commit", "--amend", "-m", message], { cwd: state.root, label: "git commit --amend -m <message>" });
4776
+ if (payload.data) {
4777
+ payload.data.root = state.root;
4778
+ payload.data.previousCommit = state.lastCommit;
4779
+ payload.data.restoreCommand = "git reset --soft ORIG_HEAD";
4780
+ }
4781
+ return payload;
4782
+ }
4783
+
4784
+ async function readGitReflog(cwd) {
4785
+ const root = await getGitRoot(cwd);
4786
+ const out = await runGitReadCommand(root, ["reflog", "-n", "20", "--format=%h%x09%gd%x09%cI%x09%gs"], { maxOutputLength: 120_000 });
4787
+ const entries = out
4788
+ .split(/\r?\n/)
4789
+ .filter(Boolean)
4790
+ .map((line) => {
4791
+ const [hash, selector, date, ...subject] = line.split("\t");
4792
+ return { hash: hash || "", selector: selector || "", date: date || "", subject: subject.join("\t") };
4793
+ });
4794
+ return { root, entries, generatedAt: new Date().toISOString() };
4795
+ }
4796
+
4797
+ // ---- Submodules ----
4798
+
4799
+ async function readGitSubmodules(cwd) {
4800
+ const root = await getGitRoot(cwd);
4801
+ if (!(await regularFileExists(path.join(root, ".gitmodules")))) {
4802
+ return { root, hasSubmodules: false, submodules: [], dirty: 0 };
4803
+ }
4804
+ const out = await runGitReadCommand(root, ["submodule", "status", "--recursive"], { timeoutMs: 30_000, maxOutputLength: 200_000 });
4805
+ const submodules = out
4806
+ .split(/\r?\n/)
4807
+ .filter(Boolean)
4808
+ .map((line) => {
4809
+ const flag = line[0] || " ";
4810
+ const rest = line.slice(1).trim();
4811
+ const firstSpace = rest.indexOf(" ");
4812
+ const sha = firstSpace === -1 ? rest : rest.slice(0, firstSpace);
4813
+ const remainder = firstSpace === -1 ? "" : rest.slice(firstSpace + 1);
4814
+ const describeMatch = remainder.match(/^(.*?)( \([^)]*\))?$/);
4815
+ return {
4816
+ sha,
4817
+ path: (describeMatch?.[1] ?? remainder).trim(),
4818
+ describe: describeMatch?.[2] ? describeMatch[2].trim().replace(/^\(|\)$/g, "") : "",
4819
+ state: flag === "-" ? "uninitialized" : flag === "+" ? "out-of-sync" : flag === "U" ? "conflicts" : "clean",
4820
+ };
4821
+ });
4822
+ return { root, hasSubmodules: true, submodules, dirty: submodules.filter((item) => item.state !== "clean").length };
4823
+ }
4824
+
4825
+ async function updateGitSubmodules(cwd, body = {}) {
4826
+ requireConfirmed(body, "Recursively updating submodules can check out new commits and");
4827
+ const root = await getGitRoot(cwd);
4828
+ const payload = await runGuardedGitMutation(["submodule", "update", "--init", "--recursive"], { cwd: root, timeoutMs: GIT_PULL_TIMEOUT_MS });
4829
+ if (payload.data) payload.data.root = root;
4830
+ if (payload.ok) payload.data.submodules = (await readGitSubmodules(root)).submodules;
4831
+ return payload;
4832
+ }
4833
+
4834
+ // ---- Tags ----
4835
+
4836
+ function cleanGitTagName(value) {
4837
+ const name = String(value || "").trim();
4838
+ if (!name || name.includes("\0") || name.includes("@{") || name.startsWith("-") || name.startsWith("/") || /\s/.test(name)) {
4839
+ throw makeHttpError(400, "Invalid tag name");
4840
+ }
4841
+ return name;
4842
+ }
4843
+
4844
+ async function validateGitTagName(root, name) {
4845
+ const result = await runCommand("git", ["check-ref-format", `refs/tags/${name}`], { cwd: root, timeoutMs: 5000 });
4846
+ if (result.exitCode !== 0) throw makeHttpError(400, `Invalid tag name: ${name}`);
4847
+ }
4848
+
4849
+ async function readGitTags(cwd) {
4850
+ const root = await getGitRoot(cwd);
4851
+ const [headOut, recentOut] = await Promise.all([
4852
+ runGitReadCommand(root, ["tag", "--points-at", "HEAD", "--sort=-creatordate"], { maxOutputLength: 60_000 }).catch(() => ""),
4853
+ runGitReadCommand(
4854
+ root,
4855
+ ["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)"],
4856
+ { maxOutputLength: 120_000 },
4857
+ ).catch(() => ""),
4858
+ ]);
4859
+ const headTags = headOut.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
4860
+ const tags = recentOut
4861
+ .split(/\r?\n/)
4862
+ .filter(Boolean)
4863
+ .map((line) => {
4864
+ const [name, objectType, objectName, target, date, ...subject] = line.split("\t");
4865
+ return {
4866
+ name: name || "",
4867
+ annotated: objectType === "tag",
4868
+ target: (objectType === "tag" ? target : objectName) || "",
4869
+ date: date || "",
4870
+ subject: subject.join("\t"),
4871
+ atHead: headTags.includes(name || ""),
4872
+ };
4873
+ });
4874
+ return { root, headTags, tags, generatedAt: new Date().toISOString() };
4875
+ }
4876
+
4877
+ async function createGitTag(cwd, body = {}) {
4878
+ requireConfirmed(body, "Creating a tag");
4879
+ const root = await getGitRoot(cwd);
4880
+ const name = cleanGitTagName(body.name);
4881
+ await validateGitTagName(root, name);
4882
+ const message = cleanGitCommitMessageInput(body.message || name);
4883
+ const payload = await runGuardedGitMutation(["tag", "-a", name, "-m", message], { cwd: root, label: `git tag -a ${name} -m <message>` });
4884
+ if (payload.data) {
4885
+ payload.data.root = root;
4886
+ payload.data.tag = name;
4887
+ // Tags never leave the machine implicitly; pushing stays a separate,
4888
+ // explicit action.
4889
+ payload.data.pushCommand = `git push ${"origin"} ${name}`;
4890
+ }
4891
+ if (payload.ok) payload.data.tags = (await readGitTags(root)).tags;
4892
+ return payload;
4893
+ }
4894
+
4895
+ // ---- Signing diagnostics ----
4896
+
4897
+ async function readGitSigningDiagnostics(cwd) {
4898
+ const root = await getGitRoot(cwd);
4899
+ const readConfig = async (args) => {
4900
+ const result = await runCommand("git", ["config", ...args], { cwd: root, timeoutMs: 2000 });
4901
+ return result.exitCode === 0 ? result.stdout.trim() : "";
4902
+ };
4903
+ const [gpgSign, gpgFormat, signingKey, lastLog] = await Promise.all([
4904
+ readConfig(["--bool", "--get", "commit.gpgsign"]),
4905
+ readConfig(["--get", "gpg.format"]),
4906
+ readConfig(["--get", "user.signingkey"]),
4907
+ runGitReadCommand(root, ["log", "-1", "--format=%h%x09%G?%x09%GS"], { maxOutputLength: 10_000 }).catch(() => ""),
4908
+ ]);
4909
+ const [lastHash = "", signState = "", signer = ""] = lastLog.trim().split("\t");
4910
+ const commitSignRequired = gpgSign.toLowerCase() === "true";
4911
+ const normalizedState = signState.trim().toUpperCase();
4912
+ const mismatch = commitSignRequired && (!normalizedState || normalizedState === "N" || normalizedState === "E");
4913
+ const suggestions = [];
4914
+ if (mismatch) {
4915
+ if (!signingKey) suggestions.push({ label: "Set your signing key (repo only)", command: "git config user.signingkey <KEY-ID>" });
4916
+ suggestions.push({ label: "Re-sign the last commit", command: "git commit --amend --no-edit -S" });
4917
+ suggestions.push({ label: "Disable signing for this repository", command: "git config commit.gpgsign false" });
4918
+ }
4919
+ return {
4920
+ root,
4921
+ commitSignRequired,
4922
+ gpgFormat: gpgFormat || "(default: gpg)",
4923
+ signingKey: signingKey || "(not set)",
4924
+ lastCommit: lastHash ? { hash: lastHash, signState: normalizedState || "N", signer } : null,
4925
+ mismatch,
4926
+ suggestions,
4927
+ };
4928
+ }
4929
+
4126
4930
  function gitWorkflowMessageCwd(root, cwd) {
4127
4931
  const messageCwd = path.resolve(String(cwd || root));
4128
4932
  if (!pathInside(root, messageCwd)) throw new Error(`Git workflow cwd must stay inside repository root: ${messageCwd}`);
@@ -4396,7 +5200,7 @@ async function prepareInitialRepositoryFiles(cwd, { repoName: repoNameInput, sta
4396
5200
  await writeFile(before.gitignorePath, gitignoreLinesForStack(stack, before.detectedStack), "utf8");
4397
5201
  gitignoreCreated = true;
4398
5202
  }
4399
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(["add", "--", "README.md", ".gitignore"], { cwd: before.root, label: "git add README.md .gitignore" }));
5203
+ const payload = gitMutationPayload(await runGitMutationCommand(["add", "--", "README.md", ".gitignore"], { cwd: before.root, label: "git add README.md .gitignore" }));
4400
5204
  if (payload.data) {
4401
5205
  payload.data.root = before.root;
4402
5206
  payload.data.readme = { path: before.readmePath, exists: true, created: !before.readmeExists };
@@ -4500,7 +5304,7 @@ async function switchGitBranch(cwd, branch, { create = false } = {}) {
4500
5304
  return { ok: true, data: { command: `git switch ${targetBranch}`, stdout: "", stderr: "", exitCode: 0, branch: targetBranch, root, switched: false, created: false } };
4501
5305
  }
4502
5306
  const args = create ? ["switch", "-c", targetBranch] : ["switch", targetBranch];
4503
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(args, { cwd: root, timeoutMs: 10 * 60 * 1000 }));
5307
+ const payload = gitMutationPayload(await runGitMutationCommand(args, { cwd: root, timeoutMs: 10 * 60 * 1000 }));
4504
5308
  if (payload.ok) {
4505
5309
  payload.data.branch = targetBranch;
4506
5310
  payload.data.root = root;
@@ -4827,7 +5631,9 @@ function runWorkflowCommand(command, args, { cwd, label = formatWorkflowCommand(
4827
5631
  return new Promise((resolve) => {
4828
5632
  const child = spawn(command, args, {
4829
5633
  cwd,
4830
- env: { ...process.env, GIT_TERMINAL_PROMPT: process.env.GIT_TERMINAL_PROMPT || "0", GH_PROMPT_DISABLED: process.env.GH_PROMPT_DISABLED || "1" },
5634
+ // LC_ALL=C keeps git/gh output in English so failure classification
5635
+ // (classifyGitSyncFailure, isGitLockFailure) works regardless of locale.
5636
+ env: { ...process.env, GIT_TERMINAL_PROMPT: process.env.GIT_TERMINAL_PROMPT || "0", GH_PROMPT_DISABLED: process.env.GH_PROMPT_DISABLED || "1", LC_ALL: "C" },
4831
5637
  stdio: ["ignore", "pipe", "pipe"],
4832
5638
  windowsHide: true,
4833
5639
  });
@@ -4891,6 +5697,33 @@ function gitWorkflowCommandPayload(result) {
4891
5697
  };
4892
5698
  }
4893
5699
 
5700
+ // Read-only workflow lookups are safe over GET; everything else mutates the
5701
+ // repository (or process state, for cancel) and must be POST. Method + access
5702
+ // guard are enforced at the router before dispatch — never dispatch on path
5703
+ // alone, or cross-origin GETs (image/script tags) could drive git mutations.
5704
+ const GIT_WORKFLOW_READONLY_PATHS = new Set([
5705
+ "/api/git-workflow/message",
5706
+ "/api/git-workflow/default-commit-message",
5707
+ "/api/git-workflow/branch-name",
5708
+ "/api/git-workflow/pr-description",
5709
+ "/api/git-workflow/init-files-status",
5710
+ ]);
5711
+
5712
+ const GIT_WORKFLOW_MUTATING_PATHS = new Set([
5713
+ "/api/git-workflow/init",
5714
+ "/api/git-workflow/readme",
5715
+ "/api/git-workflow/initial-commit",
5716
+ "/api/git-workflow/main-branch",
5717
+ "/api/git-workflow/remote",
5718
+ "/api/git-workflow/init-push",
5719
+ "/api/git-workflow/add",
5720
+ "/api/git-workflow/branch",
5721
+ "/api/git-workflow/commit",
5722
+ "/api/git-workflow/push",
5723
+ "/api/git-workflow/create-pr",
5724
+ "/api/git-workflow/cancel",
5725
+ ]);
5726
+
4894
5727
  async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.cwd) {
4895
5728
  const tab = tabOrCwd && typeof tabOrCwd === "object" ? tabOrCwd : null;
4896
5729
  const cwd = tab?.cwd || tabOrCwd || options.cwd;
@@ -4906,25 +5739,25 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
4906
5739
  return { ok: true, data: await readGitWorkflowPrDescription(cwd) };
4907
5740
  case "/api/git-workflow/init":
4908
5741
  await ensureOutsideGitRepository(cwd);
4909
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["init"], { cwd }));
5742
+ return gitMutationPayload(await runGitMutationCommand(["init"], { cwd }));
4910
5743
  case "/api/git-workflow/init-files-status":
4911
5744
  return { ok: true, data: await initialRepositoryFilesStatus(cwd) };
4912
5745
  case "/api/git-workflow/readme":
4913
5746
  return prepareInitialRepositoryFiles(cwd, { repoName: body.repoName, stack: body.stack });
4914
5747
  case "/api/git-workflow/initial-commit": {
4915
5748
  const root = await getGitRoot(cwd);
4916
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["commit", "-m", "Initial commit"], { cwd: root, label: "git commit -m \"Initial commit\"" }));
5749
+ return gitMutationPayload(await runGitMutationCommand(["commit", "-m", "Initial commit"], { cwd: root, label: "git commit -m \"Initial commit\"" }));
4917
5750
  }
4918
5751
  case "/api/git-workflow/main-branch": {
4919
5752
  const root = await getGitRoot(cwd);
4920
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["branch", "-M", "main"], { cwd: root }));
5753
+ return gitMutationPayload(await runGitMutationCommand(["branch", "-M", "main"], { cwd: root }));
4921
5754
  }
4922
5755
  case "/api/git-workflow/remote": {
4923
5756
  const root = await getGitRoot(cwd);
4924
5757
  const username = cleanGitHubUsername(body.username);
4925
5758
  const repoName = cleanGitHubRepoName(body.repoName);
4926
5759
  const remoteUrl = gitHubOriginUrl(username, repoName);
4927
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(["remote", "add", "origin", remoteUrl], { cwd: root }));
5760
+ const payload = gitMutationPayload(await runGitMutationCommand(["remote", "add", "origin", remoteUrl], { cwd: root }));
4928
5761
  if (payload.data) {
4929
5762
  payload.data.root = root;
4930
5763
  payload.data.remote = "origin";
@@ -4936,11 +5769,11 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
4936
5769
  }
4937
5770
  case "/api/git-workflow/init-push": {
4938
5771
  const root = await getGitRoot(cwd);
4939
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["push", "-u", "origin", "main"], { cwd: root, timeoutMs: 15 * 60 * 1000 }));
5772
+ return applyGitSyncFailure(gitMutationPayload(await runGitMutationCommand(["push", "-u", "origin", "main"], { cwd: root, timeoutMs: 15 * 60 * 1000 })), { push: true });
4940
5773
  }
4941
5774
  case "/api/git-workflow/add":
4942
5775
  await getGitRoot(cwd);
4943
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["add", "."], { cwd }));
5776
+ return gitMutationPayload(await runGitMutationCommand(["add", "."], { cwd }));
4944
5777
  case "/api/git-workflow/branch": {
4945
5778
  if (!tab) throw new Error("Git workflow branch worktree requires a Web UI tab");
4946
5779
  return { ok: true, data: await createGitWorkflowBranchWorktree(tab, body) };
@@ -4951,32 +5784,45 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
4951
5784
  if (variant === "input") {
4952
5785
  const root = await getGitRoot(cwd);
4953
5786
  const message = cleanGitCommitMessageInput(body.message);
4954
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["commit", "-m", message], { cwd: root, label: "git commit -m <input message>" }));
5787
+ return gitMutationPayload(await runGitMutationCommand(["commit", "-m", message], { cwd: root, label: "git commit -m <input message>" }));
4955
5788
  }
4956
5789
  const messages = await readGitWorkflowMessages(cwd);
4957
5790
  if (variant === "short") {
4958
5791
  const message = messages.short.trim();
4959
5792
  if (!message) throw new Error(`${messages.shortPath} is empty`);
4960
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["commit", "-m", message], { cwd: messages.root, label: "git commit -m <dev/COMMIT/staged-commit-short.txt>" }));
5793
+ return gitMutationPayload(await runGitMutationCommand(["commit", "-m", message], { cwd: messages.root, label: "git commit -m <dev/COMMIT/staged-commit-short.txt>" }));
4961
5794
  }
4962
5795
  if (!messages.long.trim()) throw new Error(`${messages.longPath} is empty`);
4963
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["commit", "-F", messages.longPath], { cwd: messages.root, label: "git commit -F dev/COMMIT/staged-commit-long.txt" }));
5796
+ return gitMutationPayload(await runGitMutationCommand(["commit", "-F", messages.longPath], { cwd: messages.root, label: "git commit -F dev/COMMIT/staged-commit-long.txt" }));
4964
5797
  }
4965
5798
  case "/api/git-workflow/push": {
4966
5799
  const root = await getGitRoot(cwd);
5800
+ const currentBranch = await currentGitBranch(root);
5801
+ const protectedBranch = PROTECTED_GIT_BRANCHES.has(currentBranch);
4967
5802
  if (body.setUpstream) {
4968
- const currentBranch = await currentGitBranch(root);
4969
5803
  const requestedBranch = body.branch ? cleanGitBranchName(body.branch) : currentBranch;
4970
5804
  if (requestedBranch !== currentBranch) throw new Error(`Current branch is ${currentBranch}, not ${requestedBranch}`);
4971
5805
  const remote = await defaultGitRemote(root);
4972
- const payload = gitWorkflowCommandPayload(await runGitWorkflowCommand(["push", "-u", remote, currentBranch], { cwd: root, label: `git push -u ${remote} ${currentBranch}`, timeoutMs: 15 * 60 * 1000 }));
4973
- if (payload.ok) {
5806
+ const payload = await runGuardedGitMutation(["push", "-u", remote, currentBranch], { cwd: root, label: `git push -u ${remote} ${currentBranch}`, timeoutMs: 15 * 60 * 1000 });
5807
+ if (payload.data) {
4974
5808
  payload.data.branch = currentBranch;
4975
- payload.data.remote = remote;
5809
+ payload.data.protectedBranch = protectedBranch;
5810
+ if (payload.ok) payload.data.remote = remote;
4976
5811
  }
4977
- return payload;
5812
+ return applyGitSyncFailure(payload, { push: true });
5813
+ }
5814
+ // Plain --force is never offered; --force-with-lease still refuses to
5815
+ // clobber remote commits we have not seen, and requires confirmation.
5816
+ const forceWithLease = body.forceWithLease === true;
5817
+ if (forceWithLease) requireConfirmed(body, `Force-pushing ${currentBranch} (--force-with-lease) rewrites the remote branch and`);
5818
+ const args = forceWithLease ? ["push", "--force-with-lease"] : ["push"];
5819
+ const payload = await runGuardedGitMutation(args, { cwd: root, timeoutMs: 15 * 60 * 1000 });
5820
+ if (payload.data) {
5821
+ payload.data.branch = currentBranch;
5822
+ payload.data.protectedBranch = protectedBranch;
5823
+ payload.data.forceWithLease = forceWithLease;
4978
5824
  }
4979
- return gitWorkflowCommandPayload(await runGitWorkflowCommand(["push"], { cwd: root, timeoutMs: 15 * 60 * 1000 }));
5825
+ return applyGitSyncFailure(payload, { push: true });
4980
5826
  }
4981
5827
  case "/api/git-workflow/create-pr": {
4982
5828
  const root = await getGitRoot(cwd);
@@ -5184,6 +6030,7 @@ async function serveStatic(req, res, url) {
5184
6030
 
5185
6031
  function requestBodyLimitForPath(pathname) {
5186
6032
  if (pathname === "/api/attachments") return UPLOAD_BODY_LIMIT_BYTES;
6033
+ if (pathname === "/api/files/content") return FILE_VIEWER_BODY_LIMIT_BYTES;
5187
6034
  if (["/api/prompt", "/api/steer", "/api/follow-up"].includes(pathname)) return PROMPT_BODY_LIMIT_BYTES;
5188
6035
  return BODY_LIMIT_BYTES;
5189
6036
  }
@@ -8094,6 +8941,395 @@ function resolveTabPath(tab, value) {
8094
8941
  return path.isAbsolute(text) ? text : path.resolve(tab?.cwd || options.cwd, text);
8095
8942
  }
8096
8943
 
8944
+ async function workspaceRoot(tab) {
8945
+ const root = path.resolve(tab?.cwd || options.cwd);
8946
+ return { root, realRoot: await realpath(root).catch(() => root) };
8947
+ }
8948
+
8949
+ async function resolveWorkspacePath(tab, value = "", { mustExist = true } = {}) {
8950
+ const { root, realRoot } = await workspaceRoot(tab);
8951
+ const text = String(value || "").trim();
8952
+ if (text.includes("\0")) throw makeHttpError(400, "Path cannot contain null bytes");
8953
+ const targetPath = text ? (path.isAbsolute(text) ? path.resolve(text) : path.resolve(root, text)) : root;
8954
+ if (targetPath !== root && !pathInside(root, targetPath)) throw makeHttpError(403, "Path must stay inside the active tab working directory");
8955
+ let info = null;
8956
+ let realTarget = targetPath;
8957
+ try {
8958
+ info = await stat(targetPath);
8959
+ realTarget = await realpath(targetPath).catch(() => targetPath);
8960
+ } catch (error) {
8961
+ if (mustExist) throw makeHttpError(error?.code === "ENOENT" ? 404 : 400, `Path not found: ${displayPath(targetPath)}`);
8962
+ }
8963
+ if (realTarget !== realRoot && !pathInside(realRoot, realTarget)) throw makeHttpError(403, "Resolved path escapes the active tab working directory");
8964
+ const relative = path.relative(root, targetPath).split(path.sep).join("/");
8965
+ return { root, realRoot, targetPath, realTarget, relative, info };
8966
+ }
8967
+
8968
+ function fileViewerLanguage(filePath) {
8969
+ const ext = path.extname(String(filePath || "")).toLowerCase();
8970
+ if (ext === ".md" || ext === ".markdown") return "markdown";
8971
+ return "text";
8972
+ }
8973
+
8974
+ function fileTreeEntryType(dirent, info) {
8975
+ if (info?.isDirectory?.() || dirent?.isDirectory?.()) return "directory";
8976
+ if (info?.isFile?.() || dirent?.isFile?.()) return "file";
8977
+ return dirent?.isSymbolicLink?.() ? "symlink" : "other";
8978
+ }
8979
+
8980
+ async function statFileTreeEntries(dirPath, dirents, root, realRoot) {
8981
+ const ordered = [...dirents].sort((a, b) => {
8982
+ const aRank = a.isDirectory() ? 0 : a.isFile() ? 1 : 2;
8983
+ const bRank = b.isDirectory() ? 0 : b.isFile() ? 1 : 2;
8984
+ return aRank - bRank || a.name.localeCompare(b.name);
8985
+ });
8986
+ const selected = ordered.slice(0, FILE_TREE_MAX_ENTRIES);
8987
+ const entries = [];
8988
+ let cursor = 0;
8989
+ async function worker() {
8990
+ while (cursor < selected.length) {
8991
+ const dirent = selected[cursor++];
8992
+ const targetPath = path.join(dirPath, dirent.name);
8993
+ const relative = path.relative(root, targetPath).split(path.sep).join("/");
8994
+ try {
8995
+ const [info, realTarget] = await Promise.all([stat(targetPath), realpath(targetPath).catch(() => targetPath)]);
8996
+ const outsideRoot = realTarget !== realRoot && !pathInside(realRoot, realTarget);
8997
+ const type = outsideRoot ? "other" : fileTreeEntryType(dirent, info);
8998
+ entries.push({
8999
+ name: dirent.name,
9000
+ path: relative,
9001
+ type,
9002
+ directory: type === "directory",
9003
+ file: type === "file",
9004
+ symlink: dirent.isSymbolicLink(),
9005
+ outsideRoot,
9006
+ size: info.size,
9007
+ mtimeMs: info.mtimeMs,
9008
+ extension: path.extname(dirent.name).toLowerCase(),
9009
+ canOpenInWebui: type === "file",
9010
+ });
9011
+ } catch (error) {
9012
+ entries.push({ name: dirent.name, path: relative, type: "error", directory: false, file: false, error: sanitizeError(error), canOpenInWebui: false });
9013
+ }
9014
+ }
9015
+ }
9016
+ const workers = Array.from({ length: Math.min(FILE_TREE_ENTRY_STAT_CONCURRENCY, selected.length) }, () => worker());
9017
+ await Promise.all(workers);
9018
+ entries.sort((a, b) => {
9019
+ const aRank = a.type === "directory" ? 0 : a.type === "file" ? 1 : 2;
9020
+ const bRank = b.type === "directory" ? 0 : b.type === "file" ? 1 : 2;
9021
+ return aRank - bRank || a.name.localeCompare(b.name);
9022
+ });
9023
+ return { entries, truncated: ordered.length > selected.length, total: ordered.length };
9024
+ }
9025
+
9026
+ async function getFileTreeData(tab, requestedPath = "") {
9027
+ const resolved = await resolveWorkspacePath(tab, requestedPath);
9028
+ if (!resolved.info?.isDirectory()) throw makeHttpError(400, "Path is not a directory");
9029
+ const dirents = await readdir(resolved.targetPath, { withFileTypes: true });
9030
+ const [listed, gitStatus] = await Promise.all([
9031
+ statFileTreeEntries(resolved.targetPath, dirents, resolved.root, resolved.realRoot),
9032
+ readWorkspaceGitStatusIndex(resolved.root),
9033
+ ]);
9034
+ return {
9035
+ root: resolved.root,
9036
+ displayRoot: displayPath(resolved.root),
9037
+ path: resolved.relative,
9038
+ displayPath: displayPath(resolved.targetPath),
9039
+ entries: withFileTreeGitStatus(listed.entries, resolved.root, gitStatus),
9040
+ gitStatus: fileTreeGitStatusPayload(resolved.root, gitStatus),
9041
+ truncated: listed.truncated,
9042
+ total: listed.total,
9043
+ };
9044
+ }
9045
+
9046
+ function normalizeFileSearchQuery(value = "") {
9047
+ const query = String(value || "").trim().replace(/\s+/g, " ");
9048
+ if (query.includes("\0")) throw makeHttpError(400, "Search query cannot contain null bytes");
9049
+ if (query.length > 160) throw makeHttpError(400, "Search query is too long");
9050
+ return query;
9051
+ }
9052
+
9053
+ function fileSearchMatches(entry, queryLower) {
9054
+ const name = String(entry.name || "").toLowerCase();
9055
+ const filePath = String(entry.path || "").toLowerCase();
9056
+ return name.includes(queryLower) || filePath.includes(queryLower);
9057
+ }
9058
+
9059
+ async function getFileSearchData(tab, rawQuery = "") {
9060
+ const query = normalizeFileSearchQuery(rawQuery);
9061
+ if (!query) {
9062
+ const root = path.resolve(tab?.cwd || options.cwd);
9063
+ return { root, displayRoot: displayPath(root), query, entries: [], truncated: false, total: 0, scanned: 0, maxDepth: FILE_SEARCH_MAX_DEPTH };
9064
+ }
9065
+ const resolved = await resolveWorkspacePath(tab, "");
9066
+ if (!resolved.info?.isDirectory()) throw makeHttpError(400, "Workspace root is not a directory");
9067
+ const gitStatus = await readWorkspaceGitStatusIndex(resolved.root);
9068
+ const queryLower = query.toLowerCase();
9069
+ const entries = [];
9070
+ const queue = [{ dirPath: resolved.root, relative: "", depth: 0 }];
9071
+ const visitedRealDirs = new Set([resolved.realRoot]);
9072
+ let scanned = 0;
9073
+ let truncated = false;
9074
+
9075
+ while (queue.length && scanned < FILE_SEARCH_MAX_SCANNED && entries.length < FILE_SEARCH_MAX_RESULTS) {
9076
+ const current = queue.shift();
9077
+ let dirents = [];
9078
+ try {
9079
+ dirents = await readdir(current.dirPath, { withFileTypes: true });
9080
+ } catch {
9081
+ continue;
9082
+ }
9083
+ dirents.sort((a, b) => {
9084
+ const aRank = a.isDirectory() ? 0 : a.isFile() ? 1 : 2;
9085
+ const bRank = b.isDirectory() ? 0 : b.isFile() ? 1 : 2;
9086
+ return aRank - bRank || a.name.localeCompare(b.name);
9087
+ });
9088
+
9089
+ for (const dirent of dirents) {
9090
+ if (scanned >= FILE_SEARCH_MAX_SCANNED || entries.length >= FILE_SEARCH_MAX_RESULTS) break;
9091
+ scanned += 1;
9092
+ const targetPath = path.join(current.dirPath, dirent.name);
9093
+ const relative = (current.relative ? `${current.relative}/${dirent.name}` : dirent.name).split(path.sep).join("/");
9094
+ const depth = current.depth + 1;
9095
+ try {
9096
+ const [info, realTarget] = await Promise.all([stat(targetPath), realpath(targetPath).catch(() => targetPath)]);
9097
+ const outsideRoot = realTarget !== resolved.realRoot && !pathInside(resolved.realRoot, realTarget);
9098
+ const type = outsideRoot ? "other" : fileTreeEntryType(dirent, info);
9099
+ const entry = {
9100
+ name: dirent.name,
9101
+ path: relative,
9102
+ type,
9103
+ directory: type === "directory",
9104
+ file: type === "file",
9105
+ symlink: dirent.isSymbolicLink(),
9106
+ outsideRoot,
9107
+ size: info.size,
9108
+ mtimeMs: info.mtimeMs,
9109
+ extension: path.extname(dirent.name).toLowerCase(),
9110
+ depth,
9111
+ canOpenInWebui: type === "file",
9112
+ };
9113
+ if (fileSearchMatches(entry, queryLower)) entries.push(entry);
9114
+ if (depth < FILE_SEARCH_MAX_DEPTH && type === "directory" && !FILE_SEARCH_EXCLUDED_DIRS.has(dirent.name) && !visitedRealDirs.has(realTarget)) {
9115
+ visitedRealDirs.add(realTarget);
9116
+ queue.push({ dirPath: targetPath, relative, depth });
9117
+ }
9118
+ } catch (error) {
9119
+ const entry = { name: dirent.name, path: relative, type: "error", directory: false, file: false, depth, error: sanitizeError(error), canOpenInWebui: false };
9120
+ if (fileSearchMatches(entry, queryLower)) entries.push(entry);
9121
+ }
9122
+ }
9123
+ }
9124
+ truncated = queue.length > 0 || scanned >= FILE_SEARCH_MAX_SCANNED || entries.length >= FILE_SEARCH_MAX_RESULTS;
9125
+ return {
9126
+ root: resolved.root,
9127
+ displayRoot: displayPath(resolved.root),
9128
+ query,
9129
+ entries: withFileTreeGitStatus(entries, resolved.root, gitStatus),
9130
+ gitStatus: fileTreeGitStatusPayload(resolved.root, gitStatus),
9131
+ truncated,
9132
+ total: entries.length,
9133
+ scanned,
9134
+ maxDepth: FILE_SEARCH_MAX_DEPTH,
9135
+ excludedDirs: [...FILE_SEARCH_EXCLUDED_DIRS],
9136
+ };
9137
+ }
9138
+
9139
+ function assertTextFileBuffer(buffer) {
9140
+ if (isLikelyBinaryBuffer(buffer)) throw makeHttpError(415, "File appears to be binary; only text files can be opened in WebUI");
9141
+ }
9142
+
9143
+ async function getFileContentData(tab, requestedPath = "") {
9144
+ const resolved = await resolveWorkspacePath(tab, requestedPath);
9145
+ if (!resolved.info?.isFile()) throw makeHttpError(400, "Path is not a regular file");
9146
+ if (resolved.info.size > FILE_VIEWER_MAX_BYTES) throw makeHttpError(413, `File is too large to open in WebUI (limit ${formatBytes(FILE_VIEWER_MAX_BYTES)})`);
9147
+ const buffer = await readFile(resolved.targetPath);
9148
+ assertTextFileBuffer(buffer);
9149
+ return {
9150
+ root: resolved.root,
9151
+ path: resolved.relative,
9152
+ name: path.basename(resolved.targetPath),
9153
+ content: buffer.toString("utf8"),
9154
+ size: resolved.info.size,
9155
+ mtimeMs: resolved.info.mtimeMs,
9156
+ extension: path.extname(resolved.targetPath).toLowerCase(),
9157
+ language: fileViewerLanguage(resolved.targetPath),
9158
+ };
9159
+ }
9160
+
9161
+ async function saveFileContentData(tab, body = {}) {
9162
+ if (typeof body.content !== "string") throw makeHttpError(400, "File content must be a string");
9163
+ if (body.content.includes("\0")) throw makeHttpError(400, "File content cannot contain null bytes");
9164
+ if (Buffer.byteLength(body.content, "utf8") > FILE_VIEWER_MAX_BYTES) throw makeHttpError(413, `File is too large to save in WebUI (limit ${formatBytes(FILE_VIEWER_MAX_BYTES)})`);
9165
+ const resolved = await resolveWorkspacePath(tab, body.path || body.filePath || "");
9166
+ if (!resolved.info?.isFile()) throw makeHttpError(400, "Path is not a regular file");
9167
+ if (resolved.info.size > FILE_VIEWER_MAX_BYTES) throw makeHttpError(413, `File is too large to save in WebUI (limit ${formatBytes(FILE_VIEWER_MAX_BYTES)})`);
9168
+ assertTextFileBuffer(await readFile(resolved.targetPath));
9169
+ const expectedMtimeMs = Number(body.mtimeMs);
9170
+ if (Number.isFinite(expectedMtimeMs) && Math.abs(resolved.info.mtimeMs - expectedMtimeMs) > 5) {
9171
+ throw makeHttpError(409, "File changed on disk after it was opened. Reopen it before saving.");
9172
+ }
9173
+ const tmpFile = `${resolved.targetPath}.${process.pid}.${Date.now()}.tmp`;
9174
+ try {
9175
+ await writeFile(tmpFile, body.content, { encoding: "utf8", mode: resolved.info.mode & 0o777 });
9176
+ await rename(tmpFile, resolved.targetPath);
9177
+ } catch (error) {
9178
+ await rm(tmpFile, { force: true }).catch(() => {});
9179
+ throw error;
9180
+ }
9181
+ const nextStats = await stat(resolved.targetPath);
9182
+ return {
9183
+ path: resolved.relative,
9184
+ name: path.basename(resolved.targetPath),
9185
+ size: nextStats.size,
9186
+ mtimeMs: nextStats.mtimeMs,
9187
+ extension: path.extname(resolved.targetPath).toLowerCase(),
9188
+ language: fileViewerLanguage(resolved.targetPath),
9189
+ };
9190
+ }
9191
+
9192
+ function workspaceRelativePath(root, targetPath) {
9193
+ return path.relative(root, targetPath).split(path.sep).join("/");
9194
+ }
9195
+
9196
+ function fileOperationEntryType(info) {
9197
+ if (info?.isDirectory?.()) return "directory";
9198
+ if (info?.isFile?.()) return "file";
9199
+ return "other";
9200
+ }
9201
+
9202
+ function assertWorkspaceEntryMutable(resolved, action) {
9203
+ if (!resolved.relative) throw makeHttpError(400, `Workspace root cannot be ${action}`);
9204
+ const type = fileOperationEntryType(resolved.info);
9205
+ if (type !== "file" && type !== "directory") throw makeHttpError(400, "Only regular files and directories can be modified from WebUI");
9206
+ return type;
9207
+ }
9208
+
9209
+ async function existingDestinationStats(targetPath) {
9210
+ try {
9211
+ return await stat(targetPath);
9212
+ } catch (error) {
9213
+ if (error?.code === "ENOENT") return null;
9214
+ throw makeHttpError(400, `Cannot access destination: ${displayPath(targetPath)}`);
9215
+ }
9216
+ }
9217
+
9218
+ async function resolveWorkspaceMoveDestination(tab, source, rawDestination = "") {
9219
+ const destinationText = String(rawDestination || "").trim();
9220
+ if (!destinationText) throw makeHttpError(400, "Destination path is required");
9221
+ if (destinationText.includes("\0")) throw makeHttpError(400, "Destination path cannot contain null bytes");
9222
+
9223
+ const candidatePath = path.isAbsolute(destinationText) ? path.resolve(destinationText) : path.resolve(source.root, destinationText);
9224
+ if (candidatePath !== source.root && !pathInside(source.root, candidatePath)) throw makeHttpError(403, "Destination path must stay inside the active tab working directory");
9225
+
9226
+ const candidateInfo = await existingDestinationStats(candidatePath);
9227
+ let targetPath = candidatePath;
9228
+ let targetInfo = candidateInfo;
9229
+ if (candidateInfo?.isDirectory?.()) {
9230
+ targetPath = path.join(candidatePath, path.basename(source.targetPath));
9231
+ targetInfo = await existingDestinationStats(targetPath);
9232
+ }
9233
+
9234
+ if (path.resolve(targetPath) === path.resolve(source.targetPath)) throw makeHttpError(400, "Source and destination are the same path");
9235
+ if (targetInfo) throw makeHttpError(409, `Destination already exists: ${workspaceRelativePath(source.root, targetPath)}`);
9236
+ if (source.info?.isDirectory?.() && pathInside(source.targetPath, targetPath)) throw makeHttpError(400, "A directory cannot be moved into itself or one of its descendants");
9237
+
9238
+ const parentPath = path.dirname(targetPath);
9239
+ if (parentPath !== source.root && !pathInside(source.root, parentPath)) throw makeHttpError(403, "Destination parent must stay inside the active tab working directory");
9240
+ const parentInfo = await stat(parentPath).catch((error) => {
9241
+ if (error?.code === "ENOENT") throw makeHttpError(404, `Destination parent not found: ${displayPath(parentPath)}`);
9242
+ throw makeHttpError(400, `Cannot access destination parent: ${displayPath(parentPath)}`);
9243
+ });
9244
+ if (!parentInfo?.isDirectory?.()) throw makeHttpError(400, "Destination parent is not a directory");
9245
+ const realParent = await realpath(parentPath).catch(() => parentPath);
9246
+ if (realParent !== source.realRoot && !pathInside(source.realRoot, realParent)) throw makeHttpError(403, "Destination parent escapes the active tab working directory");
9247
+
9248
+ return {
9249
+ targetPath,
9250
+ relative: workspaceRelativePath(source.root, targetPath),
9251
+ parentPath: workspaceRelativePath(source.root, parentPath),
9252
+ };
9253
+ }
9254
+
9255
+ async function deleteFileSystemEntryData(tab, body = {}) {
9256
+ if (body.confirmed !== true) throw makeHttpError(409, "Deleting files or directories requires confirmed: true");
9257
+ const resolved = await resolveWorkspacePath(tab, body.path || body.filePath || "");
9258
+ const type = assertWorkspaceEntryMutable(resolved, "deleted");
9259
+ await rm(resolved.targetPath, { recursive: type === "directory" });
9260
+ return {
9261
+ path: resolved.relative,
9262
+ name: path.basename(resolved.targetPath),
9263
+ type,
9264
+ parentPath: workspaceRelativePath(resolved.root, path.dirname(resolved.targetPath)),
9265
+ deleted: true,
9266
+ };
9267
+ }
9268
+
9269
+ async function moveFileSystemEntryData(tab, body = {}) {
9270
+ if (body.confirmed !== true) throw makeHttpError(409, "Moving files or directories requires confirmed: true");
9271
+ const source = await resolveWorkspacePath(tab, body.path || body.filePath || body.sourcePath || "");
9272
+ const type = assertWorkspaceEntryMutable(source, "moved");
9273
+ const destination = await resolveWorkspaceMoveDestination(tab, source, body.toPath || body.destinationPath || body.destination || "");
9274
+ await rename(source.targetPath, destination.targetPath);
9275
+ const nextStats = await stat(destination.targetPath).catch(() => null);
9276
+ return {
9277
+ path: source.relative,
9278
+ destination: destination.relative,
9279
+ name: path.basename(destination.targetPath),
9280
+ type,
9281
+ parentPath: workspaceRelativePath(source.root, path.dirname(source.targetPath)),
9282
+ destinationParentPath: destination.parentPath,
9283
+ moved: true,
9284
+ size: nextStats?.size,
9285
+ mtimeMs: nextStats?.mtimeMs,
9286
+ };
9287
+ }
9288
+
9289
+ function defaultEditorCommand(targetPath) {
9290
+ if (platform() === "win32") return { command: "cmd", args: ["/c", "start", "", targetPath] };
9291
+ if (platform() === "darwin") return { command: "open", args: [targetPath] };
9292
+ return { command: process.env.PI_WEBUI_OPEN_COMMAND || "xdg-open", args: [targetPath] };
9293
+ }
9294
+
9295
+ function firstCommandOutputLine(value = "") {
9296
+ return String(value || "").split(/\r?\n/).map((line) => line.trim()).find(Boolean) || "";
9297
+ }
9298
+
9299
+ async function queryXdgMime(args = [], cwd = options.cwd) {
9300
+ const result = await runCommand("xdg-mime", args, { cwd, timeoutMs: 1500, maxOutputLength: 4096 });
9301
+ if (result.exitCode !== 0) return "";
9302
+ return firstCommandOutputLine(result.stdout);
9303
+ }
9304
+
9305
+ async function linuxDefaultEditorCommand(targetPath, { cwd = options.cwd, isFile = true } = {}) {
9306
+ if (process.env.PI_WEBUI_OPEN_COMMAND) return defaultEditorCommand(targetPath);
9307
+ if (!isFile) return defaultEditorCommand(targetPath);
9308
+ const fileMime = await queryXdgMime(["query", "filetype", targetPath], cwd);
9309
+ const fileDefaultDesktop = fileMime ? await queryXdgMime(["query", "default", fileMime], cwd) : "";
9310
+ if (fileDefaultDesktop) return { command: "xdg-open", args: [targetPath], mime: fileMime, desktopFile: fileDefaultDesktop, fallbackToTextEditor: false };
9311
+ const textDefaultDesktop = await queryXdgMime(["query", "default", "text/plain"], cwd);
9312
+ if (textDefaultDesktop) {
9313
+ return { command: "gio", args: ["launch", textDefaultDesktop, targetPath], mime: fileMime, desktopFile: textDefaultDesktop, fallbackToTextEditor: true };
9314
+ }
9315
+ return { ...defaultEditorCommand(targetPath), mime: fileMime, fallbackToTextEditor: false };
9316
+ }
9317
+
9318
+ async function defaultEditorCommandForPath(targetPath, options = {}) {
9319
+ if (platform() === "linux") return linuxDefaultEditorCommand(targetPath, options);
9320
+ return defaultEditorCommand(targetPath);
9321
+ }
9322
+
9323
+ async function openPathInDefaultEditor(tab, requestedPath = "") {
9324
+ if (!String(requestedPath || "").trim()) throw makeHttpError(400, "Path to open is required");
9325
+ const resolved = await resolveWorkspacePath(tab, requestedPath);
9326
+ const { command, args, mime, desktopFile, fallbackToTextEditor } = await defaultEditorCommandForPath(resolved.targetPath, { cwd: resolved.root, isFile: !!resolved.info?.isFile?.() });
9327
+ const child = spawn(command, args, { cwd: resolved.root, stdio: "ignore", detached: true, windowsHide: true });
9328
+ child.on("error", () => {});
9329
+ child.unref?.();
9330
+ return { path: resolved.relative, command: [command, ...args].join(" "), mime, desktopFile, fallbackToTextEditor: !!fallbackToTextEditor };
9331
+ }
9332
+
8097
9333
  function configuredSessionDir() {
8098
9334
  for (let index = 0; index < options.piArgs.length; index++) {
8099
9335
  const arg = options.piArgs[index];
@@ -8169,7 +9405,7 @@ function extractSessionTextContent(content) {
8169
9405
  .map((part) => {
8170
9406
  if (typeof part === "string") return part;
8171
9407
  if (part?.type === "text" && typeof part.text === "string") return part.text;
8172
- if (part?.type === "toolCall") return `[tool call: ${part.toolName || "tool"}]`;
9408
+ if (part?.type === "toolCall") return `[tool call: ${part.toolName || part.name || "tool"}]`;
8173
9409
  if (part?.type === "thinking") return "[thinking]";
8174
9410
  if (part?.type === "image") return "[image]";
8175
9411
  return "";
@@ -8178,6 +9414,104 @@ function extractSessionTextContent(content) {
8178
9414
  .join(" ");
8179
9415
  }
8180
9416
 
9417
+ function generatedSessionEntryId(usedIds) {
9418
+ let id = "";
9419
+ do {
9420
+ id = randomUUID().replace(/-/g, "").slice(0, 8);
9421
+ } while (usedIds.has(id));
9422
+ usedIds.add(id);
9423
+ return id;
9424
+ }
9425
+
9426
+ async function writeForkedSessionFromEntries({ entries, targetLeafId, cwd, parentSession }) {
9427
+ const manager = SessionManager.create(cwd, configuredSessionDir(), { parentSession });
9428
+ const header = manager.getHeader();
9429
+ const sessionFile = manager.getSessionFile();
9430
+ if (!header || !sessionFile) throw new Error("Failed to create forked session metadata");
9431
+
9432
+ const outputEntries = [header];
9433
+ if (targetLeafId) {
9434
+ const byId = new Map(entries.map((entry) => [entry.id, entry]));
9435
+ const pathEntries = [];
9436
+ let current = byId.get(targetLeafId);
9437
+ while (current) {
9438
+ pathEntries.push(current);
9439
+ current = current.parentId ? byId.get(current.parentId) : undefined;
9440
+ }
9441
+ pathEntries.reverse();
9442
+ if (!pathEntries.length) throw makeHttpError(400, `Fork target entry not found in the active session: ${targetLeafId}`);
9443
+
9444
+ const pathWithoutLabels = [];
9445
+ let pathParentId = null;
9446
+ for (const entry of pathEntries) {
9447
+ if (entry.type === "label") continue;
9448
+ pathWithoutLabels.push({ ...entry, parentId: pathParentId });
9449
+ pathParentId = entry.id;
9450
+ }
9451
+ outputEntries.push(...pathWithoutLabels);
9452
+
9453
+ const pathEntryIds = new Set(pathWithoutLabels.map((entry) => entry.id));
9454
+ const labelsByTarget = new Map();
9455
+ const labelTimestampsByTarget = new Map();
9456
+ for (const entry of entries) {
9457
+ if (entry?.type !== "label" || !pathEntryIds.has(entry.targetId)) continue;
9458
+ if (entry.label) {
9459
+ labelsByTarget.set(entry.targetId, entry.label);
9460
+ labelTimestampsByTarget.set(entry.targetId, entry.timestamp);
9461
+ } else {
9462
+ labelsByTarget.delete(entry.targetId);
9463
+ labelTimestampsByTarget.delete(entry.targetId);
9464
+ }
9465
+ }
9466
+
9467
+ let labelParentId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
9468
+ const usedIds = new Set([...pathEntryIds, header.id]);
9469
+ for (const [targetId, label] of labelsByTarget) {
9470
+ const labelEntry = {
9471
+ type: "label",
9472
+ id: generatedSessionEntryId(usedIds),
9473
+ parentId: labelParentId,
9474
+ timestamp: labelTimestampsByTarget.get(targetId) || new Date().toISOString(),
9475
+ targetId,
9476
+ label,
9477
+ };
9478
+ outputEntries.push(labelEntry);
9479
+ labelParentId = labelEntry.id;
9480
+ }
9481
+ }
9482
+
9483
+ await writeFile(sessionFile, `${outputEntries.map((entry) => JSON.stringify(entry)).join("\n")}\n`, { flag: "wx" });
9484
+ return sessionFile;
9485
+ }
9486
+
9487
+ async function createForkedSessionFile(tab, entryId) {
9488
+ requirePersistentSessions();
9489
+ const targetEntryId = String(entryId || "").trim();
9490
+ if (!targetEntryId) throw makeHttpError(400, "entryId is required");
9491
+
9492
+ const state = await currentSessionState(tab).catch(() => tab.lastState || {});
9493
+ if (state.isCompacting) throw makeHttpError(409, "Wait for compaction to finish before forking the session.");
9494
+ const parentSession = state.sessionFile || tabRestorableSessionFile(tab);
9495
+
9496
+ const entriesResponse = await safeRpcResponse(tab, { type: "get_entries" }, REQUEST_TIMEOUT_MS);
9497
+ if (entriesResponse.success === false) throw makeHttpError(400, entriesResponse.error || "failed to load session entries");
9498
+ const entries = Array.isArray(entriesResponse.data?.entries) ? entriesResponse.data.entries : [];
9499
+ const selectedEntry = entries.find((entry) => entry?.id === targetEntryId);
9500
+ if (!selectedEntry) throw makeHttpError(400, `Fork target entry not found in the active session: ${targetEntryId}`);
9501
+ if (selectedEntry.type !== "message" || selectedEntry.message?.role !== "user") {
9502
+ throw makeHttpError(400, "Fork point must be a user message");
9503
+ }
9504
+
9505
+ const text = extractSessionTextContent(selectedEntry.message.content).trim();
9506
+ const sessionFile = await writeForkedSessionFromEntries({
9507
+ entries,
9508
+ targetLeafId: selectedEntry.parentId || null,
9509
+ cwd: tab.cwd,
9510
+ parentSession,
9511
+ });
9512
+ return { sessionFile, text, parentSession, targetEntryId };
9513
+ }
9514
+
8181
9515
  function sessionTreeEntryLabel(entry) {
8182
9516
  if (!entry || typeof entry !== "object") return "entry";
8183
9517
  if (entry.type === "message") return entry.message?.role || "message";
@@ -8249,18 +9583,26 @@ async function requireIdleForSessionAction(tab, actionLabel) {
8249
9583
  }
8250
9584
 
8251
9585
  async function runForkCommand(tab, entryId) {
8252
- await requireIdleForSessionAction(tab, "forking the session");
8253
- const targetEntryId = String(entryId || "").trim();
8254
- if (!targetEntryId) throw makeHttpError(400, "entryId is required");
8255
- const response = await tab.rpc.send({ type: "fork", entryId: targetEntryId });
8256
- if (response.success === false) return response;
8257
- const state = await safeRpcData(tab, { type: "get_state" }, STATUS_RPC_TIMEOUT_MS);
8258
- if (state.ok) rememberTabState(tab, state.data);
9586
+ const fork = await createForkedSessionFile(tab, entryId);
9587
+ const title = uniqueTabTitle(generatedTabTitleFromPrompt(fork.text) || `${tab.title || "Session"} fork`, null);
9588
+ const forkTab = await createTab({
9589
+ title,
9590
+ titleSource: title ? "auto" : undefined,
9591
+ conversationStarted: true,
9592
+ cwd: tab.cwd,
9593
+ sessionFile: fork.sessionFile,
9594
+ gitWorkspace: tab.gitWorkspace,
9595
+ });
9596
+ const forkTabMeta = tabMeta(forkTab);
8259
9597
  return rpcSuccess("fork", {
8260
- message: response.data?.cancelled ? "Fork cancelled." : "Forked the current session.",
8261
- text: response.data?.text || "",
8262
- result: response.data,
8263
- tab: tabMeta(tab),
9598
+ message: "Forked the current session in a new terminal tab.",
9599
+ text: fork.text || "",
9600
+ result: { cancelled: false, text: fork.text || "", sessionFile: fork.sessionFile, targetEntryId: fork.targetEntryId },
9601
+ sessionFile: fork.sessionFile,
9602
+ parentSession: fork.parentSession,
9603
+ tab: forkTabMeta,
9604
+ tabs: listTabs(),
9605
+ sourceTab: tabMeta(tab),
8264
9606
  });
8265
9607
  }
8266
9608
 
@@ -9455,6 +10797,59 @@ const server = createServer(async (req, res) => {
9455
10797
  return;
9456
10798
  }
9457
10799
 
10800
+ if (url.pathname === "/api/files" && req.method === "GET") {
10801
+ const tab = getRequestedTab(req, url);
10802
+ sendJson(res, 200, { ok: true, data: await getFileTreeData(tab, url.searchParams.get("path") || "") });
10803
+ return;
10804
+ }
10805
+
10806
+ if (url.pathname === "/api/files" && req.method === "DELETE") {
10807
+ requireLocalhostRoute(req, url.pathname);
10808
+ const body = await readJsonBody(req);
10809
+ const tab = getRequestedTab(req, url, body);
10810
+ ensureNaturalConversationRouteAllowed(tab, "file deletion is blocked");
10811
+ sendJson(res, 200, { ok: true, data: await deleteFileSystemEntryData(tab, body) });
10812
+ return;
10813
+ }
10814
+
10815
+ if (url.pathname === "/api/files/move" && req.method === "POST") {
10816
+ requireLocalhostRoute(req, url.pathname);
10817
+ const body = await readJsonBody(req);
10818
+ const tab = getRequestedTab(req, url, body);
10819
+ ensureNaturalConversationRouteAllowed(tab, "file moves are blocked");
10820
+ sendJson(res, 200, { ok: true, data: await moveFileSystemEntryData(tab, body) });
10821
+ return;
10822
+ }
10823
+
10824
+ if (url.pathname === "/api/files/search" && req.method === "GET") {
10825
+ const tab = getRequestedTab(req, url);
10826
+ sendJson(res, 200, { ok: true, data: await getFileSearchData(tab, url.searchParams.get("q") || url.searchParams.get("query") || "") });
10827
+ return;
10828
+ }
10829
+
10830
+ if (url.pathname === "/api/files/content" && req.method === "GET") {
10831
+ const tab = getRequestedTab(req, url);
10832
+ sendJson(res, 200, { ok: true, data: await getFileContentData(tab, url.searchParams.get("path") || "") });
10833
+ return;
10834
+ }
10835
+
10836
+ if (url.pathname === "/api/files/content" && req.method === "POST") {
10837
+ requireLocalhostRoute(req, url.pathname);
10838
+ const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
10839
+ const tab = getRequestedTab(req, url, body);
10840
+ if (isNaturalConversationActive(tab)) throw makeHttpError(409, "file edits are blocked");
10841
+ sendJson(res, 200, { ok: true, data: await saveFileContentData(tab, body) });
10842
+ return;
10843
+ }
10844
+
10845
+ if (url.pathname === "/api/files/open-default" && req.method === "POST") {
10846
+ requireLocalhostRoute(req, url.pathname);
10847
+ const body = await readJsonBody(req);
10848
+ const tab = getRequestedTab(req, url, body);
10849
+ sendJson(res, 200, { ok: true, data: await openPathInDefaultEditor(tab, body.path || body.filePath || "") });
10850
+ return;
10851
+ }
10852
+
9458
10853
  if (url.pathname === "/api/attachments" && req.method === "POST") {
9459
10854
  const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
9460
10855
  const tab = getRequestedTab(req, url, body);
@@ -9501,7 +10896,7 @@ const server = createServer(async (req, res) => {
9501
10896
  const tab = getRequestedTab(req, url, body);
9502
10897
  ensureNaturalConversationRouteAllowed(tab, "session fork actions are blocked");
9503
10898
  const response = await runForkCommand(tab, body.entryId);
9504
- sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));
10899
+ sendJson(res, response.success === false ? 400 : 200, response);
9505
10900
  return;
9506
10901
  }
9507
10902
 
@@ -9856,15 +11251,89 @@ const server = createServer(async (req, res) => {
9856
11251
  return;
9857
11252
  }
9858
11253
 
9859
- if (url.pathname.startsWith("/api/git-workflow/")) {
9860
- const body = req.method === "POST" ? await readJsonBody(req) : {};
9861
- const tab = getRequestedTab(req, url, body);
9862
- if (req.method !== "GET") ensureNaturalConversationRouteAllowed(tab, "git workflow actions are blocked");
9863
- const response = await handleGitWorkflowRequest(url.pathname, body, tab);
9864
- if (response) {
9865
- sendJson(res, 200, response);
11254
+ {
11255
+ const gitActionError = (error) => {
11256
+ sendJson(res, error?.statusCode || 200, { ok: false, ...(error?.code ? { code: error.code } : {}), error: sanitizeError(error) });
11257
+ };
11258
+ const GIT_READ_ROUTES = {
11259
+ "/api/git-operation": (cwd) => readGitOperationSnapshot(cwd),
11260
+ "/api/git-stash": (cwd) => readGitStashes(cwd),
11261
+ "/api/git-stash/show": (cwd) => readGitStashPreview(cwd, url.searchParams.get("ref") || ""),
11262
+ "/api/git-undo": (cwd) => readGitUndoState(cwd),
11263
+ "/api/git-reflog": (cwd) => readGitReflog(cwd),
11264
+ "/api/git-submodules": (cwd) => readGitSubmodules(cwd),
11265
+ "/api/git-tags": (cwd) => readGitTags(cwd),
11266
+ "/api/git-signing": (cwd) => readGitSigningDiagnostics(cwd),
11267
+ "/api/git-worktrees/prune": (cwd) => pruneGitWorktrees(cwd, { dryRun: true }),
11268
+ };
11269
+ if (req.method === "GET" && GIT_READ_ROUTES[url.pathname]) {
11270
+ const tab = getRequestedTab(req, url);
11271
+ try {
11272
+ sendJson(res, 200, { ok: true, data: await GIT_READ_ROUTES[url.pathname](tab.cwd) });
11273
+ } catch (error) {
11274
+ gitActionError(error);
11275
+ }
9866
11276
  return;
9867
11277
  }
11278
+
11279
+ const GIT_MUTATION_ROUTES = {
11280
+ "/api/git-fetch": (cwd) => fetchGitChanges(cwd),
11281
+ "/api/git-changes/integrate": (cwd, body) => integrateGitUpstream(cwd, body),
11282
+ "/api/git-changes/stage-file": (cwd, body) => stageGitFile(cwd, body),
11283
+ "/api/git-changes/unstage-file": (cwd, body) => unstageGitFile(cwd, body),
11284
+ "/api/git-changes/discard-file": (cwd, body) => discardGitFile(cwd, body),
11285
+ "/api/git-changes/delete-untracked": (cwd, body) => deleteGitUntrackedFile(cwd, body),
11286
+ "/api/git-operation/continue": (cwd, body) => gitOperationAction(cwd, "continue", body),
11287
+ "/api/git-operation/skip": (cwd, body) => gitOperationAction(cwd, "skip", body),
11288
+ "/api/git-operation/abort": (cwd, body) => gitOperationAction(cwd, "abort", body),
11289
+ "/api/git-operation/stage-file": (cwd, body) => gitOperationStageFile(cwd, body),
11290
+ "/api/git-operation/bisect": (cwd, body) => gitBisectAction(cwd, body),
11291
+ "/api/git-stash/save": (cwd, body) => saveGitStash(cwd, body),
11292
+ "/api/git-stash/apply": (cwd, body) => applyGitStash(cwd, body),
11293
+ "/api/git-stash/pop": (cwd, body) => applyGitStash(cwd, body, { pop: true }),
11294
+ "/api/git-stash/drop": (cwd, body) => dropGitStash(cwd, body),
11295
+ "/api/git-undo/last-commit": (cwd, body) => undoLastGitCommit(cwd, body),
11296
+ "/api/git-undo/amend-message": (cwd, body) => amendLastGitCommitMessage(cwd, body),
11297
+ "/api/git-submodules/update": (cwd, body) => updateGitSubmodules(cwd, body),
11298
+ "/api/git-tags/create": (cwd, body) => createGitTag(cwd, body),
11299
+ "/api/git-worktrees/prune": (cwd, body) => {
11300
+ requireConfirmed(body, "Pruning stale worktree records");
11301
+ return pruneGitWorktrees(cwd, { dryRun: false });
11302
+ },
11303
+ };
11304
+ if (req.method === "POST" && GIT_MUTATION_ROUTES[url.pathname]) {
11305
+ const body = await readJsonBody(req);
11306
+ const tab = getRequestedTab(req, url, body);
11307
+ ensureNaturalConversationRouteAllowed(tab, "git actions are blocked");
11308
+ try {
11309
+ const payload = await GIT_MUTATION_ROUTES[url.pathname](tab.cwd, body);
11310
+ sendJson(res, 200, payload && typeof payload === "object" && "ok" in payload ? payload : { ok: true, data: payload });
11311
+ } catch (error) {
11312
+ gitActionError(error);
11313
+ }
11314
+ return;
11315
+ }
11316
+ }
11317
+
11318
+ if (url.pathname.startsWith("/api/git-workflow/")) {
11319
+ const readOnlyWorkflow = GIT_WORKFLOW_READONLY_PATHS.has(url.pathname);
11320
+ const mutatingWorkflow = GIT_WORKFLOW_MUTATING_PATHS.has(url.pathname);
11321
+ if (readOnlyWorkflow || mutatingWorkflow) {
11322
+ const requiredMethod = mutatingWorkflow ? "POST" : "GET";
11323
+ if (req.method !== requiredMethod) {
11324
+ res.setHeader("Allow", requiredMethod);
11325
+ sendJson(res, 405, { ok: false, error: `${url.pathname} requires ${requiredMethod}` });
11326
+ return;
11327
+ }
11328
+ const body = mutatingWorkflow ? await readJsonBody(req) : {};
11329
+ const tab = getRequestedTab(req, url, body);
11330
+ if (mutatingWorkflow) ensureNaturalConversationRouteAllowed(tab, "git workflow actions are blocked");
11331
+ const response = await handleGitWorkflowRequest(url.pathname, body, tab);
11332
+ if (response) {
11333
+ sendJson(res, 200, response);
11334
+ return;
11335
+ }
11336
+ }
9868
11337
  }
9869
11338
 
9870
11339
  const getCommand = req.method === "GET" ? commandFromGet(url.pathname) : undefined;