DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
docs(dsh-tauri-worktree): add worktree deletion reliability optimization plan (#320)
Mao Mr04997eb22e8f
diff --git "a/docs/plugins/6.\344\274\230\345\214\226\350\256\241\345\210\222.worktree.md" "b/docs/plugins/6.\344\274\230\345\214\226\350\256\241\345\210\222.worktree.md"new file mode 100644index 00000000..b19d00a8--- /dev/null+++ "b/docs/plugins/6.\344\274\230\345\214\226\350\256\241\345\210\222.worktree.md"@@ -0,0 +1,184 @@+# Worktree 删除可靠性优化文档++> 目标:定位「删除工作树页面卡住、时不时删不掉、删掉了目录又还在」的根因,调研可靠方案,给出分层优化设计。+>+> 环境基线:本机实测 `git 2.48.1.windows.1` + `node v22.22.0`;桌面端捆绑 Node v22.19+ / v24(见 `docs/AGENTS.desktop.md`)。++## 1. 症状 → 结论速览++| 用户症状 | 直接根因 | 一句话结论 |+| --- | --- | --- |+| 删除页面卡住 | 删除是**同步**执行的;`git worktree remove --force` 在 git 进程内串行删除整个工作树目录(含 `node_modules` 数万文件),UI 的 HTTP 调用从头阻塞到尾,且 `execFile` 默认 30s 超时会中途杀进程 | 依赖大是**放大器**(决定耗时量级),真正根因是**同步执行 + 用 git.exe 删目录 + 无重试兜底** |+| 时不时删不掉 | 30s 超时杀 git、或 Windows 文件句柄占用(agent 进程 cwd / dev server / MCP / Defender 实时扫描)→ `EBUSY/EPERM`;git 的递归删除**无重试**;半删除后状态不一致,现有代码无 fs 兜底 | 需要:先杀占用进程 → 用 Node `fs.rm`(自带重试、junction 安全)删除 → `git worktree prune` 清 admin → 对三种残留态幂等 |+| 删掉了,目录又还在 | 删除过程中文件被锁,git 删掉能删的部分后失败,留下部分目录;客户端归档清理 `discardWorktree` 失败 `{ok:false}` 不抛错 → 永不重试 | 需要:rename-to-trash 预检 + 后台删除 + 失败重试 |++**用户猜测验证**:「每次依赖太大」成立但只是必要条件——`node_modules` 决定一次删除要碰多少个文件(分钟级);但「卡住/删不掉/残留」源自上面的执行与容错设计缺陷,只要是同步 + git 删除 + 无重试就必然复现。++---++## 2. 现状链路(代码位置)++```+UI「放弃」弹窗 → applyDiscard() client/store/index.ts:154-175 (await discardWorktree)+ → POST /api/dsh-worktree/discard client/apis/client.ts:40-44+ → discardWorktree() host/service/operation.ts:376-402+ → git(['worktree','remove','--force',path]) host/service/git.ts:18-31 (timeout 默认 30_000,无 windowsHide)+ → git(['worktree','prune']) (只清 admin,不删磁盘)+ → git(['branch','-D',...]) (仅 ownsBranch)+原生侧边栏「归档」 → cleanupArchivedWorktrees() client/register/hydration.ts:226-243+ → fetchStatus() → discardWorktree() (fire-and-forget,失败不重试)+```++**调试环境里测量到的事实**:`git worktree remove --force` 删除含 `node_modules` 的工作树木身就是整进整出——它是 `remove_dir_recurse()`(`git/dir.c`)单进程串行删文件,NTFS + Windows Defender 实时扫描下数万文件要数十秒到分钟,远超 30s 默认超时。++---++## 3. 根因分析(本机实测)++### 3.1 同步阻塞链路(→ 卡住)+- `git()`(`git.ts:20-25`)`execFileAsync('git', ...)` 用 `timeout: 30_000` 默认值;`worktree remove` 是大目录删除,不是短命令,30s 一到 git 被 SIGTERM 杀掉,返回 `Command failed ... killed`。+- HTTP `/discard` 直到 git 跑完或被杀才返回 → UI `await` 阻塞 30s+(对应 codemux 的同步 Tauri 命令阻塞主线程问题)。+- 次要问题:`execFile` 未设 `windowsHide: true`,桌面壳规范要求 `CREATE_NO_WINDOW`(见 `docs/AGENTS.desktop.md`「Windows」),git 子进程可能闪现控制台窗口。++### 3.2 git.exe 删除的三重问题(→ 删不掉 + 残留)+1. **慢**:`remove_dir_recurse` 无并行、单次 stat/unlink;依赖放大成分钟级。+2. **锁即失败、不重试**:Windows 上任何进程持有工作树内句柄(DSH 会话 agent 进程 `cwd` 在树内、dev server、MCP server、Defender 扫描)→ `unlink/rmdir` 报 `EBUSY/EPERM/ENOTEMPTY`,git 直接失败且无重试。实测见 §3.3 TEST4。+3. **junction 穿透(数据安全隐患)**:`git-for-windows < 2.54.0` 的 `remove_dir_recurse()` 会**穿透 NTFS junction 递归删除目标内容**(已由 git-for-windows PR #6151 修复,v2.54.0 里程碑,2026-03-31 merged)。本机 2.48.1 未修复,实测见 TEST1。这意味着**绝不能在同一台机器上用 git 删含 junction 的工作树**——若未来做「node_modules junction 共享依赖」,主仓库源码会被连带删除(对应 claude-code #60604/#84162 的数据毁灭事故)。++### 3.3 本机实测结果(`git 2.48.1.windows.1` / `node v22.22.0`,临时目录)++| 测试 | 场景 | 结果 |+| --- | --- | --- |+| TEST1 | `git worktree remove --force`,树内 `node_modules` → junction → 外部 victim 目录 | **victim 内容被删除(exit 0、静默)** → 证实 junction 穿透。 |+| TEST2 | Node `fs.rm(path,{recursive,force,maxRetries})` 删除含 junction 的树 | **victim 完整;工作树目录删光;但 `git worktree list` 仍列出** → fs 删除后必须 `git worktree prune` 清 admin。 |+| TEST3 | `Rename-Item` 重命名为 `.trash`(含 junction),再 `fs.rm` trash | 重命名 O(1) 瞬时完成、victim 完整;trash 的 `fs.rm` junction 安全。 |+| TEST4 | 隐藏 node 进程 `cwd` 置于树内,再重命名 / `fs.rm` | 重命名**失败**;`fs.rm` **失败 EBUSY(rmdir)**并留残树;`taskkill /T /F` 杀进程后重试 `fs.rm` **立即成功**。 |++结论:**fs 删除路径 junction 安全且可重试、可评估进度**;git 删除路径慢、锁即死、junction 危险。因此删除应改走「先杀进程 → Node `fs.rm` → `git worktree prune`」。实测方法可复用到 vitest 集成用例(见 §6)。++### 3.4 状态机缺口(→ 半删除残留后永远删不掉/重建失败)+`git worktree remove` 被中断/失败后可能落到三种残留态:++| 残留态 | 目录存在? | `.git/worktrees/<id>` admin | 现状代码 | 问题 |+| --- | --- | --- | --- | --- |+| A | ✅ | ✅ | 重试 `worktree remove --force` | 同一锁/超时再次失败;若 admin 已清而目录在则报「not a working tree」 |+| B | ✅ | ❌ | 无处理(`worktree remove` 报 not a working tree;`prune` 无对象) | **永不删除,孤儿磁盘常驻** |+| C | ❌ | ✅ | `worktree prune` 清 admin | 可,已能处理 |++- `discardWorktree`/`checkoutToLocal` 只有 `worktree remove --force` + `prune`,**没有 fs 兜底**,态 B 无法收敛 → 「时不时删不掉」。+- `ensureWorktree`(`operation.ts:83-85`)检出残留目录时只 `git worktree prune`——`prune` 只清 admin 条目不删磁盘目录(见 `git-worktree(1)`),孤儿目录残留 → `git worktree add` 报 `already exists` → **同一 hash 的会话重建永久失败**。+- 客户端 `cleanupArchivedWorktrees`(`hydration.ts:229-241`):`discardWorktree` 失败返回 `{ok:false, error}` **不抛错** → `.catch` 不触发 → `cleanedArchives` 已 add → **永不重试**,目录/分支永久残留。+- 无 in-flight 去重:双击「放弃」→ 两个并发 `git worktree remove` 竞争。++---++## 4. 业界案例对照(佐证根因与方向)++| 来源 | 问题/方案 | 与本库对照 |+| --- | --- | --- |+| [cmux PR #25](https://github.com/craigsc/cmux/pull/25) | Windows 上 `git worktree remove` 因 `Directory not empty` 失败;锁在进程退出后 1–8s 才释放,需重试 5×2s;最终兜底 `rm -rf && git worktree prune`;1.8GB node_modules 实测通过 | 印证「锁延迟释放需重试」+「fs+prune 兜底」 |+| [codemux 3947e6c](https://github.com/Zeus-Deus/codemux/commit/3947e6c8b2d3176d6ba29ea9a0c68bf521f94243) | 同步 Tauri 命令跑 `git worktree remove --force` 卡死整窗;改为后台化 + 立即更新 UI 状态 | 印证「同步删除是卡住根因」 |+| [claude-code #41740](https://github.com/anthropics/claude-code/issues/41740) | Node 进程在树内持锁,删除失败;应先杀 worktree 范围内子进程再删 | 印证「先杀进程」前置步骤 |+| [claude-code #32747](https://github.com/anthropics/claude-code/issues/32747) | 删除在 MCP server 关闭**之前**执行 → Permission denied;失败被误记为清除成功,空目录残留 | 印证「杀进程顺序 + 失败必须可重试、不得谎报成功」 |+| [Auto-Claude #1539](https://github.com/AndyMik90/Auto-Claude/issues/1539) | `git worktree remove --force` 在 Windows 面对未跟踪文件失败;改为 `fs.rm` + `git worktree prune` + `branch -D` | 与推荐方案一致 |+| [claude-code #60604](https://github.com/anthropics/claude-code/issues/60604) | agent 用 junction 共享 node_modules 后 `git worktree remove` 沿 npm workspace junction 链删掉主仓库源码 | **junction 共享的前提是绝不能再用 git 删** |+| [claude-code #84162](https://github.com/anthropics/claude-code/issues/84162) | 136 工作树 ~130GB;对比:`Remove-Item`(pwsh7.5.8/5.1)/`rm -rf`(git-bash)/`shutil.rmtree` 均**保留 junction**,仅 git 穿透 | 通用递归删除都 junction 安全,git 是例外 |+| [soldr #710](https://github.com/zackees/soldr/issues/710) | Windows 分层删除:inline rm → 重命名到同卷 trash → 释放句柄;`MoveFileEx` 对 mmap 后代失败;重命名在无 mmap 时可用作锁探测 | 印证 rename-to-trash 预检 + 同卷要求 |++---++## 5. Node 依赖选型调研++**结论:本仓库不新增运行时依赖**,以 Node 内建 `fs.rm` 为核心即可满足全部需求(junction 安全、自带 Windows 重试、可评估、零体积)。仓库现有 `git()` 是薄封装 `execFile`,够用;可选升级点用 catalog 已有的 `tinyexec` 而非引入 `execa`。++| 候选 | 维护/体积 | 定位 | 采用? | 理由 |+| --- | --- | --- | --- | --- |+| `node:fs/promises` `.rm()` | 内建 | 递归删除 + `recursive/force` | ✅ 核心 | 零依赖;junction 当链接删(不穿透);`maxRetries`/`retryDelay` 遇 `EBUSY/EMFILE/ENFILE/ENOTEMPTY/EPERM` 线性退避重试(TEST2/4 实测)。文档:<https://nodejs.org/api/fs.html#fspromisesrmpath-options> |+| `rimraf` v6 | ESM、零依赖库 | 删除封装(native=fs.rm / manual=Windows 专用实现),`maxRetries/backoff` | 可选兜底 | 仅当需要 Windows manual 实现或更细粒度 backoff 时引入;内置 `fs.rm` 已够。文档:<https://github.com/isaacs/rimraf> |+| `fs-extra` → `.remove()` | 慢性维护、CJS 包袱 | 历史 API | ❌ | `remove` 内部即 rimraf 行为,不再需要 |+| `del` | 面向 glob | 构建脚本删除 | ❌ | 面向 build,非运行时强删 |+| `simple-git` | steveukx/git-js | git CLI 封装、`raw()`、timeout | ❌ 可选 | worktree 只是 raw 命令;当前 `execFile` 薄封装足够,引入只是加一层。文档:<https://github.com/steveukx/git-js> |+| `execa` | sindresorhus | spawn 增强 | ❌ | 改用 catalog `tinyexec` 即可;`execFile` + `windowsHide:true` 已够 |+| `tinyexec` | 已在 catalog | 轻量 spawn | ✅ 可选升级 | 如需统一 spawn 边界、规避 `execFile` 无 `windowsHide` 问题,用已有的它,不引新包 |+| `graceful-fs` | isaacs | 仅救 EMFILE | ❌ | 不解决 EBUSY/EPERM/ junction |++**`git()` helper 需修的点**(`git.ts:18-31`):+- `execFile` 增 `windowsHide: true`(对应桌面壳 `CREATE_NO_WINDOW` 规范)。+- `timeout` 改为按命令覆盖:删除类命令传 `undefined`/大超时,其余保留 30s。+- 错误分类:超时(kill)与 `EBUSY/EPERM/ENOTEMPTY` 应转成可检索的错误前缀(规范要求 `Result<_, String>` 大写前缀)。++---++## 6. 优化方案(分层)++### P0 — 宿主删除流程重构(解决全部三个症状)++单点收敛:把 `operation.ts` 里所有 `git worktree remove --force` 调用(`ensureWorktree` 回滚、`checkoutToLocal:357`、`discardWorktree:388`)替换为统一的 `removeWorktreeOnDisk(root, binding)`,语义:**不删磁盘靠 git,git 只负责 admin + branch,磁盘删除走 fs**。++```ts+async function removeWorktreeOnDisk(ctx, binding, opts) {+ // 1) 先杀占用进程:停止绑定会话(agent/shell 进程 cwd 在树内),沿用 taskkill /T /F 模式。+ await stopSessionProcesses(ctx, binding.sessionId, binding.worktreePath)++ // 2) rename-to-trash 预检(同 root 内 ⇒ 同卷,O(1)):瞬时让路径消失;+ // rename 失败即判定「仍有句柄占用」(TEST4),直接走 4) 重试。+ const trash = join(worktreesRoot, '.trash', `${key}-${Date.now()}`)+ const renamed = await renameDir(binding.worktreePath, trash) // fs.promises.rename++ // 3) 后台/前台删除 trash:fs.rm 自带 maxRetries,再包一层外层退避重试(例 3×2s,+ // 参照 cmux 锁 1–8s 释放);失败保留 binding 供重试,返回剩余路径供复查。+ await rmRetry(trash ?? path) // rm(path, {recursive:true, force:true, maxRetries:10, retryDelay:100})++ // 4) admin 清理:目录已删 ⇒ git worktree prune 即可清 .git/worktrees/<id>;+ // 状态机三种残留态统一幂等(见 3.4),最后 branch -D(若 ownsBranch)。+ await git(['worktree','prune'], root)+ if (binding.ownsBranch && binding.branchName) await git(['branch','-D', binding.branchName], root)+}+```++要点:+- **POSIX 也走同一 fs 路径**,减少分叉(POSIX `fs.rm` 同样快且无锁问题);不必为 POSIX 保留 git 删除。+- **残留态幂等**:态 A(重跑 prune/rm)、态 B(`fs.rm` + `prune` 无对象即净删孤儿)、态 C(`prune`)。重试不再依赖 git 是否还认识该树。+- **`ensureWorktree` 残留分支**(`operation.ts:83-85`):`existsSync(path)` 时先 `fs.rm(path)` 再 `git worktree prune`,删除孤儿目录后即可重建,而非只 prune。+- **never junction 指向主仓库**:若启用依赖共享(P2),junction 目标必须是第三方缓存目录(如 `~/.dsh/deps-cache/<lockfile-hash>`),即使误删也不碰用户源码。++### P0 — 删除异步化(治「卡住」)++- host 路由 `/discard` 改为**立即返回成功/`jobId`**,删除在后台执行;`/status` 复用现有 hydration 复核循环汇报进度与结果。+- client `applyDiscard`(`store/index.ts:154-175`)改为**乐观态**:先 `patchSession` 为删除中,再轮询 `/status`,不再裸 `await` 阻塞。+- 对应 codemux 结论:**UI 状态先变,磁盘清理后台做**;同时规避 HTTP 层 30s+ 阻塞。++### P1 — 客户端与容错修复++- `cleanupArchivedWorktrees`(`hydration.ts:229-241`):失败即把 `sessionId` 从 `cleanedArchives` 移除(当前只从 `catch` 移除,`{ok:false}` 不抛错导致永不重试);并加退避重试。+- discard 在 in-flight 去重(`inFlight`/`queued` 模式同 hydration),防双击并发。+- 失败日志/提示按分类给出可操作文案(EBUSY→提示关闭占用进程;超时→提示文件过多)。++### P2 — 可选:依赖共享与版本提示++- **node_modules junction 共享**(解决「依赖太大」的创建/删除成本):前提是删除已走 junction 安全的 `fs.rm` 路径(TEST2 已证),且目标指向第三方缓存。文档化安全约束(见 claude-code #60604/#84162 事故)。+- **git 版本提示**:检测 <2.54.0 时提示升级(junction 穿透在 v2.54.0 修复),作为兜底缓解 `git clean` 等其他删除路径;删除主路径不依赖它。++---++## 7. 验收场景清单(回归 + 集成用例建议)++把这些场景补成 vitest 集成用例(复用 §3.3 实测脚本,临时目录):++- [ ] 删除含 `node_modules`(大量文件)的工作树:UI 瞬时响应、后台完成后 `/status` 归位、磁盘无残留、`git worktree list` 干净。+- [ ] 删除树内存在 junction(指向树外)的工作树:**目标目录内容完好**(junction 安全回归)。+- [ ] 某进程 `cwd` 在树内时删除:进程被杀后再删成功;全程不卡死 UI(异步)。+- [ ] 删除中途被锁失败:重试收敛到三种残留态中任意一种后最终删除干净、binding 清除。+- [ ] 捕获半删除残留(态 B)后重建同 hash 工作树:成功(不再 `already exists`)。+- [ ] 双击/并发触发删除:只执行一次(去重)。+- [ ] 归档会话的异步清理:失败后下次可重试,不再永久静默放弃。++---++## 8. 参考资料++- Git 官方:`git worktree(1)` <https://git-scm.com/docs/git-worktree>(`remove --force`/`prune` 仅清 admin 的语义)+- Node.js `fs.promises.rm`(`recursive/force/maxRetries/retryDelay`,Windows 重试错误集)<https://nodejs.org/api/fs.html#fspromisesrmpath-options>+- git-for-windows PR #6151「Don't traverse mount points in remove_dir_recurse()」(junction 修复,v2.54.0 里程碑,2026-03-31 merged)<https://github.com/git-for-windows/git/pull/6151>+- 业界对照:cmux #25 / codemux 3947e6c / claude-code #41740、#32747、#60604、#84162 / Auto-Claude #1539 / soldr #710(见 §4 表格内链接)+- 依赖文档:rimraf <https://github.com/isaacs/rimraf> · simple-git <https://github.com/steveukx/git-js> · execa <https://github.com/sindresorhus/execa> · tinyexec <https://github.com/antfu/tinyexec> · fs-extra <https://github.com/jprichardson/node-fs-extra> · del <https://github.com/sindresorhus/del> · graceful-fs <https://github.com/isaacs/node-graceful-fs>\ No newline at end of file