pi-web-ui 0.104.4 → 0.105.1

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.
Files changed (52) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +1 -1
  3. package/README.zh-CN.md +2 -2
  4. package/bin/pi-web-ui.mjs +9 -3
  5. package/dist/server/agent-service-daemon.js +7 -7
  6. package/dist/server/agent-service.js +497 -109
  7. package/dist/server/approval-default-rules.js +15 -0
  8. package/dist/server/client-state.js +39 -2
  9. package/dist/server/dispatch-domain-handlers.js +35 -7
  10. package/dist/server/dsh/dsh-agent-service.js +88 -33
  11. package/dist/server/dsh/dsh-serialize.js +16 -1
  12. package/dist/server/ensure-bash.js +7 -2
  13. package/dist/server/file-transfer-routes.js +114 -1
  14. package/dist/server/index.js +347 -68
  15. package/dist/server/load-tools-tool.js +2 -1
  16. package/dist/server/locales.js +5 -0
  17. package/dist/server/markers/marker.js +28 -0
  18. package/dist/server/mcp-bridge.js +20 -6
  19. package/dist/server/pkg-info.js +69 -0
  20. package/dist/server/plugin-facilities.js +18 -9
  21. package/dist/server/plugin-manifest-validate.js +3 -0
  22. package/dist/server/plugin-updater.js +11 -5
  23. package/dist/server/plugins.js +3 -12
  24. package/dist/server/present-files-tool.js +47 -1
  25. package/dist/server/preset-fields.js +14 -0
  26. package/dist/server/preset-share.js +5 -12
  27. package/dist/server/prompt-composer.js +1 -1
  28. package/dist/server/remote-ssh-service.js +158 -5
  29. package/dist/server/serialize.js +15 -4
  30. package/dist/server/session-parser.js +138 -2
  31. package/dist/server/settings-service.js +19 -0
  32. package/dist/server/terminals.js +7 -1
  33. package/dist/server/text-quote.js +64 -2
  34. package/dist/server/tool-manager.js +10 -0
  35. package/dist/server/tool-prompts.js +1 -0
  36. package/dist/server/update-check.js +98 -24
  37. package/dist/server/workspace-snapshot.js +251 -13
  38. package/dist/server/worktree-service.js +262 -0
  39. package/dist/server/worktree-tool.js +173 -0
  40. package/package.json +3 -1
  41. package/plugin-sdk/index.d.ts +14 -1
  42. package/themes/zhujian-dark.css +16 -4
  43. package/themes/zhujian.css +16 -4
  44. package/themes/zhupi-dark.css +16 -4
  45. package/themes/zhupi.css +16 -4
  46. package/web/dist/assets/{TerminalPanel-B7x99tkg.js → TerminalPanel-Mk4laCAL.js} +1 -1
  47. package/web/dist/assets/index-BDLVjBeK.js +690 -0
  48. package/web/dist/assets/index-BQC6lADz.css +1 -0
  49. package/web/dist/index.html +21 -21
  50. package/web/dist/sw.js +1 -1
  51. package/web/dist/assets/index-DOrLcjLY.js +0 -680
  52. package/web/dist/assets/index-_H2BS7OX.css +0 -1
@@ -11,9 +11,10 @@
11
11
  * - 回滚时若启用 restoreWorkspace,通过 `git checkout <snapshotRef> -- <prefix>` 与 `git clean -fd -- <prefix>`
12
12
  * 只还原/清理 cwd 子树,绝不触碰同仓库的兄弟目录。
13
13
  */
14
- import { execFile } from "node:child_process";
15
- import { randomUUID } from "node:crypto";
14
+ import { execFile, spawn } from "node:child_process";
15
+ import { createHash, randomUUID } from "node:crypto";
16
16
  import { copyFile, rm } from "node:fs/promises";
17
+ import { existsSync } from "node:fs";
17
18
  import { join, resolve } from "node:path";
18
19
  import { promisify } from "node:util";
19
20
  import { gitDirOf } from "./scm.js";
@@ -31,8 +32,157 @@ async function runGit(cwd, args, envExtra) {
31
32
  });
32
33
  return stdout.trim();
33
34
  }
35
+ /** 向 git 标准输入写一段内容。用于 `update-index --index-info` 这类不能把数万路径塞进 argv 的命令。 */
36
+ function runGitInput(cwd, args, input, envExtra) {
37
+ return new Promise((resolvePromise, reject) => {
38
+ const child = spawn("git", ["-c", "core.quotepath=false", ...args], {
39
+ cwd,
40
+ env: envExtra ? { ...process.env, ...envExtra } : process.env,
41
+ windowsHide: true,
42
+ // stdout 不读会把管道缓冲写满,git 可能一直不退出;也不要让它漏进测试进程的 console。
43
+ stdio: ["pipe", "ignore", "pipe"],
44
+ });
45
+ let stderr = "";
46
+ let settled = false;
47
+ const timer = setTimeout(() => {
48
+ if (settled)
49
+ return;
50
+ settled = true;
51
+ child.kill();
52
+ reject(new Error(`git ${args[0] ?? ""} timed out`));
53
+ }, GIT_SNAPSHOT_TIMEOUT_MS);
54
+ // 防御 EPIPE:当子进程异常提早退出时,写管道不会引发未捕获异常崩溃 Node 进程
55
+ child.stdin?.on("error", () => { });
56
+ child.stderr?.on("data", (chunk) => {
57
+ stderr += chunk.toString();
58
+ });
59
+ child.on("error", (err) => {
60
+ if (settled)
61
+ return;
62
+ settled = true;
63
+ clearTimeout(timer);
64
+ reject(err);
65
+ });
66
+ child.on("close", (code) => {
67
+ if (settled)
68
+ return;
69
+ settled = true;
70
+ clearTimeout(timer);
71
+ if (code === 0)
72
+ resolvePromise();
73
+ else
74
+ reject(new Error(stderr.trim() || `git exited ${code}`));
75
+ });
76
+ try {
77
+ child.stdin.end(input);
78
+ }
79
+ catch {
80
+ // ignore synchronous pipe write error
81
+ }
82
+ });
83
+ }
84
+ /**
85
+ * 一次性获取仓库核心元数据:gitDir、indexFile 与 prefix。
86
+ * 合并多次独立的 `rev-parse` 调用,减少 Windows 下子进程启动开销。
87
+ */
88
+ export async function probeGitRepo(cwd) {
89
+ try {
90
+ const out = await runGit(cwd, ["rev-parse", "--git-dir", "--git-path", "index", "--show-prefix"]);
91
+ const lines = out.split("\n").map((l) => l.trim());
92
+ if (lines.length < 2)
93
+ return null;
94
+ const rawGitDir = lines[0];
95
+ const rawIndex = lines[1];
96
+ const rawPrefix = lines[2] ?? "";
97
+ if (!rawGitDir || !rawIndex)
98
+ return null;
99
+ return {
100
+ gitDir: resolve(cwd, rawGitDir),
101
+ indexFile: resolve(cwd, rawIndex),
102
+ prefix: rawPrefix.replace(/\\/g, "/").replace(/\/+$/, ""),
103
+ };
104
+ }
105
+ catch {
106
+ return null;
107
+ }
108
+ }
109
+ /** 影子 index 缓存文件路径(按 gitDir 与规范化 cwd 的哈希隔离)。 */
110
+ export function snapshotCachePath(gitDir, cwd) {
111
+ const hash = createHash("sha1").update(resolve(cwd)).digest("hex").slice(0, 16);
112
+ return join(gitDir, `pi-snapshot-cache-${hash}`);
113
+ }
114
+ /**
115
+ * 把持久化的影子 index 缓存或用户真实 index 拷贝为快照用的临时 index。
116
+ *
117
+ * 优化:若之前已有该 cwd 的影子 index 缓存且有效,直接复用拷贝它(无需重复扫描兄弟目录且保留上一轮已跟踪/未跟踪文件的 stat 缓存);
118
+ * 若无缓存,拷贝用户真实 index 并剔除子树外条目;若出错则回退。
119
+ */
120
+ async function seedSnapshotIndex(cwd, tempIndex, repo, env) {
121
+ const cachePath = snapshotCachePath(repo.gitDir, cwd);
122
+ if (existsSync(cachePath)) {
123
+ try {
124
+ await copyFile(cachePath, tempIndex);
125
+ return { fromCache: true };
126
+ }
127
+ catch {
128
+ // 缓存损坏或不可读,清理并回落到真实 index
129
+ await rm(cachePath, { force: true }).catch(() => { });
130
+ }
131
+ }
132
+ try {
133
+ await copyFile(repo.indexFile, tempIndex);
134
+ }
135
+ catch {
136
+ return { fromCache: false };
137
+ }
138
+ const prefix = repo.prefix;
139
+ if (!prefix)
140
+ return { fromCache: false };
141
+ const prefixSlash = `${prefix}/`;
142
+ let listed = "";
143
+ try {
144
+ listed = await runGit(cwd, ["ls-files", "-z", "--full-name", "--", ":(top)"], env);
145
+ }
146
+ catch {
147
+ await rm(tempIndex, { force: true }).catch(() => { });
148
+ return { fromCache: false };
149
+ }
150
+ const outside = listed.split("\0").filter((path) => {
151
+ if (!path || path.includes("\n"))
152
+ return false;
153
+ const norm = path.replace(/\\/g, "/");
154
+ return norm !== prefix && !norm.startsWith(prefixSlash);
155
+ });
156
+ if (listed.includes("\n") && listed.split("\0").some((path) => path.includes("\n"))) {
157
+ await rm(tempIndex, { force: true }).catch(() => { });
158
+ return { fromCache: false };
159
+ }
160
+ if (outside.length > 0) {
161
+ const info = outside.map((path) => `0 0000000000000000000000000000000000000000\t${path}\n`).join("");
162
+ try {
163
+ await runGitInput(cwd, ["update-index", "--index-info"], info, env);
164
+ }
165
+ catch {
166
+ await rm(tempIndex, { force: true }).catch(() => { });
167
+ }
168
+ }
169
+ return { fromCache: false };
170
+ }
171
+ const lastSnapshotByCwd = new Map();
172
+ /** 清理特定 cwd(或全部)的上次快照内存缓存(单测或工作区还原时调用)。 */
173
+ export function clearWorkspaceSnapshotCaches(cwd) {
174
+ if (cwd) {
175
+ lastSnapshotByCwd.delete(resolve(cwd));
176
+ }
177
+ else {
178
+ lastSnapshotByCwd.clear();
179
+ }
180
+ }
34
181
  /** 检查工作区是否由 Git 管理。 */
35
182
  export async function isGitWorkspace(cwd) {
183
+ const info = await probeGitRepo(cwd);
184
+ if (info)
185
+ return true;
36
186
  return (await gitDirOf(cwd)) !== null;
37
187
  }
38
188
  /**
@@ -42,20 +192,45 @@ export async function isGitWorkspace(cwd) {
42
192
  * 该操作纯粹在临时 index 文件中完成,绝不影响用户的实际 index 或 HEAD。
43
193
  */
44
194
  export async function createWorkspaceSnapshot(cwd) {
45
- const gitDir = await gitDirOf(cwd);
46
- if (!gitDir)
195
+ const repo = await probeGitRepo(cwd);
196
+ if (!repo)
47
197
  return null;
48
- const tempIndex = join(gitDir, `temp-index-snapshot-${randomUUID()}`);
198
+ const tempIndex = join(repo.gitDir, `temp-index-snapshot-${randomUUID()}`);
49
199
  const env = { GIT_INDEX_FILE: tempIndex };
200
+ const cachePath = snapshotCachePath(repo.gitDir, cwd);
50
201
  try {
51
- // 1. 将 cwd 子树(而非整个工作区)的当前改动(含未跟踪与新增)记录到临时 index;
52
- // 暂存路径相对仓库根,write-tree 顶层因此只有该子目录一个条目
53
- await runGit(cwd, ["add", "-A", "--", "."], env);
54
- // 2. 写入 tree 对象
55
- const tree = await runGit(cwd, ["write-tree"], env);
202
+ // 1. 先种入 index(优先从持久化影子缓存拷贝,次选从真实 index 拷贝并剔除子树外条目)
203
+ await seedSnapshotIndex(cwd, tempIndex, repo, env);
204
+ // 2 & 3. 将 cwd 子树当前改动暂存到临时 index 并生成 tree 对象(若因 cache 损坏或脏索引失败,回退空 index 重试)
205
+ let tree = null;
206
+ try {
207
+ await runGit(cwd, ["add", "-A", "--", "."], env);
208
+ tree = await runGit(cwd, ["write-tree"], env);
209
+ }
210
+ catch (stageErr) {
211
+ // 回退兜底:清理损坏的临时 index 和缓存 index,从纯空 index 重试一次
212
+ await rm(tempIndex, { force: true }).catch(() => { });
213
+ await rm(cachePath, { force: true }).catch(() => { });
214
+ try {
215
+ await runGit(cwd, ["add", "-A", "--", "."], env);
216
+ tree = await runGit(cwd, ["write-tree"], env);
217
+ }
218
+ catch {
219
+ throw stageErr;
220
+ }
221
+ }
56
222
  if (!tree)
57
223
  return null;
58
- // 3. 检查是否有 HEAD commit 作为 parent
224
+ // 异步更新持久化影子 index 缓存供下轮秒级复用
225
+ void copyFile(tempIndex, cachePath).catch(() => { });
226
+ // 优化 3:检查 tree 是否与该 cwd 上次快照完全一致
227
+ const normCwd = resolve(cwd);
228
+ const last = lastSnapshotByCwd.get(normCwd);
229
+ if (last && last.treeSha === tree) {
230
+ // 工作区内容完全无变动:直接复用已有快照 SHA,省去 rev-parse HEAD + commit-tree
231
+ return last.snapshotRef;
232
+ }
233
+ // 4. 检查是否有 HEAD commit 作为 parent
59
234
  let hasHead = false;
60
235
  try {
61
236
  await runGit(cwd, ["rev-parse", "--verify", "HEAD"]);
@@ -64,14 +239,22 @@ export async function createWorkspaceSnapshot(cwd) {
64
239
  catch {
65
240
  hasHead = false;
66
241
  }
67
- // 4. 创建轻量 commit 对象,不关联任何分支引用
242
+ // 5. 创建轻量 commit 对象,不关联任何分支引用
68
243
  const commitArgs = ["commit-tree", tree];
69
244
  if (hasHead) {
70
245
  commitArgs.push("-p", "HEAD");
71
246
  }
72
247
  commitArgs.push("-m", `pi-web-ui: workspace shadow snapshot ${new Date().toISOString()}`);
73
248
  const commitHash = await runGit(cwd, commitArgs, env);
74
- return commitHash || null;
249
+ if (commitHash) {
250
+ lastSnapshotByCwd.set(normCwd, {
251
+ treeSha: tree,
252
+ snapshotRef: commitHash,
253
+ timestamp: Date.now(),
254
+ });
255
+ return commitHash;
256
+ }
257
+ return null;
75
258
  }
76
259
  catch (err) {
77
260
  console.warn(`[workspace-snapshot] 创建快照失败 (${cwd}):`, err.message);
@@ -118,6 +301,10 @@ export async function restoreWorkspaceSnapshot(cwd, snapshotRef) {
118
301
  // 仓库根 cwd:整仓还原,使用原子 read-tree --reset,旧实现经过长期验证且天然支持空仓库快照
119
302
  await runGit(cwd, ["read-tree", "-u", "--reset", snapshotRef]);
120
303
  await runGit(cwd, ["clean", "-fd"]);
304
+ // 还原成功后,清除该 cwd 的上次快照缓存与影子 index
305
+ lastSnapshotByCwd.delete(resolve(cwd));
306
+ const cachePath = snapshotCachePath(gitDir, cwd);
307
+ void rm(cachePath, { force: true }).catch(() => { });
121
308
  return { success: true };
122
309
  }
123
310
  // 子目录 cwd:作用域收敛到该子树,不误伤同仓兄弟目录与仓库根
@@ -151,6 +338,10 @@ export async function restoreWorkspaceSnapshot(cwd, snapshotRef) {
151
338
  }
152
339
  // 3. 清理快照之后新增的未跟踪文件与空目录(含第 1 步退回未跟踪的那些)
153
340
  await runGit(cwd, ["clean", "-fd", "--", pathspec]);
341
+ // 还原成功后,清除该 cwd 的上次快照缓存与影子 index,确保后续快照重新根据物理工作区生成
342
+ lastSnapshotByCwd.delete(resolve(cwd));
343
+ const cachePath = snapshotCachePath(gitDir, cwd);
344
+ void rm(cachePath, { force: true }).catch(() => { });
154
345
  return { success: true };
155
346
  }
156
347
  catch (err) {
@@ -198,3 +389,50 @@ export function findMatchingWorkspaceSnapshot(snapshots, entryId, entryTs = 0) {
198
389
  }
199
390
  return snapshots[0];
200
391
  }
392
+ /** 从会话 sessionManager entries 回放恢复之前持久化的快照映射记录。 */
393
+ export function readWorkspaceSnapshotsFromSession(sm) {
394
+ try {
395
+ const mgr = sm;
396
+ if (typeof mgr?.getEntries !== "function")
397
+ return [];
398
+ const entries = mgr.getEntries();
399
+ const records = [];
400
+ for (const e of entries) {
401
+ const entry = e;
402
+ if (entry?.type === "custom" && entry.customType === "pi-web-ui/workspace-snapshot" && entry.data?.snapshotRef) {
403
+ records.push({
404
+ entryId: entry.data.entryId,
405
+ timestamp: Number(entry.data.timestamp) || 0,
406
+ snapshotRef: String(entry.data.snapshotRef),
407
+ });
408
+ }
409
+ }
410
+ return records.slice(-50);
411
+ }
412
+ catch {
413
+ return [];
414
+ }
415
+ }
416
+ /** 将快照映射记录持久化到会话转录中(以便会话重载或服务重启后支持双向回滚)。 */
417
+ export function appendWorkspaceSnapshotToSession(sm, record) {
418
+ try {
419
+ const mgr = sm;
420
+ mgr?.appendCustomEntry?.("pi-web-ui/workspace-snapshot", record);
421
+ }
422
+ catch {
423
+ // ignore
424
+ }
425
+ }
426
+ /**
427
+ * 为工具定义叠加影子快照门禁:在工具执行物理写操作之前,确保正在并发生成的快照已经完成。
428
+ */
429
+ export function withWorkspaceSnapshotGate(def, awaitPendingSnapshot) {
430
+ const originalExecute = def.execute;
431
+ return {
432
+ ...def,
433
+ execute: async (...args) => {
434
+ await awaitPendingSnapshot();
435
+ return originalExecute.apply(def, args);
436
+ },
437
+ };
438
+ }
@@ -0,0 +1,262 @@
1
+ /**
2
+ * server/worktree-service.ts
3
+ *
4
+ * Git 工作树(Git Worktree)核心服务层。
5
+ *
6
+ * 功能:
7
+ * 1. 结构化解析 `git worktree list --porcelain`,获取主工作树与所有子工作树(Linked Worktrees);
8
+ * 2. 检测各工作树状态(分支名、HEAD SHA、未提交文件数、是否为当前工作区、是否为主仓库);
9
+ * 3. 规范化创建(create)、清理(remove)、剪枝(prune)工作树;
10
+ * 4. 组装 `WorktreeInfo` 上下文供 UI 横幅与 AI 工具消费。
11
+ */
12
+ import { execFile } from "node:child_process";
13
+ import { resolve, relative, normalize } from "node:path";
14
+ import { promisify } from "node:util";
15
+ import { existsSync } from "node:fs";
16
+ import { pick } from "./i18n.js";
17
+ const exec = promisify(execFile);
18
+ const GIT_TIMEOUT_MS = 15_000;
19
+ const FAST_GIT_TIMEOUT_MS = 5_000;
20
+ /** 统一路径分隔符为 '/',兼顾 Windows 盘符大小写归一化。 */
21
+ export function normalizeWirePath(p) {
22
+ const resolved = resolve(normalize(p)).replace(/\\/g, "/");
23
+ if (process.platform === "win32" && /^[a-zA-Z]:/.test(resolved)) {
24
+ return resolved[0].toUpperCase() + resolved.slice(1);
25
+ }
26
+ return resolved;
27
+ }
28
+ /** 运行单条 git 命令,失败时抛出友好错误。 */
29
+ async function runGit(cwd, args, timeoutMs = GIT_TIMEOUT_MS) {
30
+ try {
31
+ const { stdout } = await exec("git", ["-c", "core.quotepath=false", ...args], {
32
+ cwd,
33
+ timeout: timeoutMs,
34
+ maxBuffer: 8 * 1024 * 1024,
35
+ windowsHide: true,
36
+ });
37
+ return stdout;
38
+ }
39
+ catch (err) {
40
+ const e = err;
41
+ const detail = (e.stderr ?? e.message ?? "").trim().split("\n")[0];
42
+ throw new Error(detail || "Git command failed");
43
+ }
44
+ }
45
+ /** 检查指定目录是否位于 Git 仓库中。 */
46
+ export async function isInsideGitRepo(cwd) {
47
+ try {
48
+ const out = await runGit(cwd, ["rev-parse", "--is-inside-work-tree"], FAST_GIT_TIMEOUT_MS);
49
+ return out.trim() === "true";
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ }
55
+ /** 解析 `git worktree list --porcelain` 文本输出。 */
56
+ export function parseWorktreePorcelain(text) {
57
+ const items = [];
58
+ const blocks = text.trim().split(/\n\s*\n/);
59
+ for (const block of blocks) {
60
+ const lines = block
61
+ .split("\n")
62
+ .map((l) => l.trim())
63
+ .filter(Boolean);
64
+ if (lines.length === 0)
65
+ continue;
66
+ let path = "";
67
+ let head = "";
68
+ let branch;
69
+ let detached = false;
70
+ let bare = false;
71
+ let locked;
72
+ let prunable;
73
+ for (const line of lines) {
74
+ if (line.startsWith("worktree ")) {
75
+ path = normalizeWirePath(line.slice("worktree ".length).trim());
76
+ }
77
+ else if (line.startsWith("HEAD ")) {
78
+ head = line.slice("HEAD ".length).trim();
79
+ }
80
+ else if (line.startsWith("branch ")) {
81
+ const ref = line.slice("branch ".length).trim();
82
+ branch = ref.replace(/^refs\/heads\//, "");
83
+ }
84
+ else if (line === "detached") {
85
+ detached = true;
86
+ }
87
+ else if (line === "bare") {
88
+ bare = true;
89
+ }
90
+ else if (line.startsWith("locked")) {
91
+ const reason = line.slice("locked".length).trim();
92
+ locked = reason || true;
93
+ }
94
+ else if (line.startsWith("prunable")) {
95
+ const reason = line.slice("prunable".length).trim();
96
+ prunable = reason || true;
97
+ }
98
+ }
99
+ if (path) {
100
+ items.push({
101
+ path,
102
+ head,
103
+ branch,
104
+ detached,
105
+ bare,
106
+ locked,
107
+ prunable,
108
+ });
109
+ }
110
+ }
111
+ return items;
112
+ }
113
+ /** 快速检测指定工作树目录中的未提交更改数(status --porcelain)。 */
114
+ async function getUncommittedCount(worktreePath) {
115
+ if (!existsSync(worktreePath)) {
116
+ return { isDirty: false, count: 0 };
117
+ }
118
+ try {
119
+ const out = await runGit(worktreePath, ["status", "--porcelain"], FAST_GIT_TIMEOUT_MS);
120
+ const lines = out
121
+ .split("\n")
122
+ .map((l) => l.trim())
123
+ .filter(Boolean);
124
+ return {
125
+ isDirty: lines.length > 0,
126
+ count: lines.length,
127
+ };
128
+ }
129
+ catch {
130
+ return { isDirty: false, count: 0 };
131
+ }
132
+ }
133
+ /** 计算当前工作树相对于主分支领先的 commit 数。 */
134
+ async function getAheadCount(worktreePath, mainBranch = "main") {
135
+ if (!existsSync(worktreePath))
136
+ return 0;
137
+ try {
138
+ const out = await runGit(worktreePath, ["rev-list", "--count", `HEAD`, `^${mainBranch}`], FAST_GIT_TIMEOUT_MS);
139
+ const num = Number(out.trim());
140
+ return Number.isNaN(num) ? 0 : num;
141
+ }
142
+ catch {
143
+ // 主分支名可能是 master
144
+ if (mainBranch === "main") {
145
+ try {
146
+ const out = await runGit(worktreePath, ["rev-list", "--count", `HEAD`, `^master`], FAST_GIT_TIMEOUT_MS);
147
+ const num = Number(out.trim());
148
+ return Number.isNaN(num) ? 0 : num;
149
+ }
150
+ catch {
151
+ return 0;
152
+ }
153
+ }
154
+ return 0;
155
+ }
156
+ }
157
+ /** 列出当前 Git 仓库的所有工作树,包含主工作树与关联子工作树。 */
158
+ export async function listWorktrees(cwd) {
159
+ const inside = await isInsideGitRepo(cwd);
160
+ if (!inside)
161
+ return [];
162
+ const rawText = await runGit(cwd, ["worktree", "list", "--porcelain"]);
163
+ const rawItems = parseWorktreePorcelain(rawText);
164
+ if (rawItems.length === 0)
165
+ return [];
166
+ const normCurrent = normalizeWirePath(cwd);
167
+ const mainItem = rawItems[0];
168
+ const mainBranch = mainItem.branch || "main";
169
+ const results = [];
170
+ for (let i = 0; i < rawItems.length; i++) {
171
+ const item = rawItems[i];
172
+ const isMain = i === 0;
173
+ const isCurrent = normCurrent === item.path ||
174
+ normCurrent.startsWith(item.path + "/") ||
175
+ (process.platform === "win32" && normCurrent.toLowerCase() === item.path.toLowerCase());
176
+ const { isDirty, count } = await getUncommittedCount(item.path);
177
+ const ahead = isMain ? 0 : await getAheadCount(item.path, mainBranch);
178
+ results.push({
179
+ path: item.path,
180
+ branch: item.branch || (item.detached ? "(detached)" : undefined),
181
+ isCurrent,
182
+ isMain,
183
+ isDirty,
184
+ uncommittedCount: count,
185
+ aheadCount: ahead,
186
+ });
187
+ }
188
+ return results;
189
+ }
190
+ /** 创建新的 Git 工作树。 */
191
+ export async function createWorktree(cwd, opts, lang) {
192
+ const l = lang?.() ?? "en";
193
+ const inside = await isInsideGitRepo(cwd);
194
+ if (!inside) {
195
+ throw new Error(pick(l, "当前目录不是 Git 仓库", "Current directory is not a Git repository", "worktree.not.git"));
196
+ }
197
+ const targetPath = normalizeWirePath(resolve(cwd, opts.path));
198
+ const args = ["worktree", "add"];
199
+ let branchName = opts.branch;
200
+ if (typeof opts.newBranch === "string" && opts.newBranch.trim()) {
201
+ args.push("-b", opts.newBranch.trim());
202
+ branchName = opts.newBranch.trim();
203
+ }
204
+ else if (opts.newBranch === true && opts.branch) {
205
+ args.push("-b", opts.branch.trim());
206
+ }
207
+ args.push(targetPath);
208
+ if (opts.commit) {
209
+ args.push(opts.commit.trim());
210
+ }
211
+ else if (!opts.newBranch && opts.branch) {
212
+ args.push(opts.branch.trim());
213
+ }
214
+ await runGit(cwd, args);
215
+ return { path: targetPath, branch: branchName };
216
+ }
217
+ /** 移除指定 Git 工作树。 */
218
+ export async function removeWorktree(cwd, targetPathInput, force = false, lang) {
219
+ const l = lang?.() ?? "en";
220
+ const inside = await isInsideGitRepo(cwd);
221
+ if (!inside) {
222
+ throw new Error(pick(l, "当前目录不是 Git 仓库", "Current directory is not a Git repository", "worktree.not.git"));
223
+ }
224
+ const targetPath = normalizeWirePath(resolve(cwd, targetPathInput));
225
+ if (!force) {
226
+ const { isDirty, count } = await getUncommittedCount(targetPath);
227
+ if (isDirty) {
228
+ throw new Error(pick(l, `工作树「${targetPath}」包含 ${count} 个未提交的文件修改;请先提交或传入 force=true 强制删除`, `Worktree "${targetPath}" has ${count} uncommitted changes; commit them or pass force=true to remove`, "worktree.remove.dirty"));
229
+ }
230
+ }
231
+ const args = ["worktree", "remove"];
232
+ if (force)
233
+ args.push("--force");
234
+ args.push(targetPath);
235
+ await runGit(cwd, args);
236
+ }
237
+ /** 获取当前目录的完整工作树上下文元数据(用于 UI 横幅与快照)。 */
238
+ export async function getWorktreeContext(cwd) {
239
+ try {
240
+ const inside = await isInsideGitRepo(cwd);
241
+ if (!inside)
242
+ return null;
243
+ const list = await listWorktrees(cwd);
244
+ if (list.length === 0)
245
+ return null;
246
+ const mainEntry = list.find((e) => e.isMain) || list[0];
247
+ const currentEntry = list.find((e) => e.isCurrent);
248
+ const isLinkedWorktree = Boolean(currentEntry && !currentEntry.isMain);
249
+ const linkedWorktrees = list.filter((e) => !e.isMain);
250
+ return {
251
+ isLinkedWorktree,
252
+ currentPath: currentEntry ? currentEntry.path : normalizeWirePath(cwd),
253
+ branch: currentEntry?.branch,
254
+ mainPath: mainEntry.path,
255
+ mainBranch: mainEntry.branch,
256
+ linkedWorktrees,
257
+ };
258
+ }
259
+ catch {
260
+ return null;
261
+ }
262
+ }