fix(active-worktree): stop serving a cached root whose directory is gone (#960)

active-worktree.ts 的三个进程级缓存只存路径、从不校验存在性:

- pathTopCache(path → git 顶层)与 linkedWorktreeCache(top → 是否 linked worktree)永不过期;
- activeWorktreeRootCache 虽有 15s TTL,但每次过期重扫时,候选路径仍会从上面两个缓存里拿回同一个
  已删除的顶层目录,TTL 形同虚设。

结果是:侧栏跟随某个 linked worktree 之后,如果该 worktree 被外部删除(git worktree remove,或直接
在编辑器里删目录),侧栏根目录会永久钉在已删除的路径上 —— 文件树报「文件夹不存在」、git 面板报
「不是 git 仓库」,主仓库明明还健在,却只能重启 DSH 进程才能恢复(#960)。

改动(每次缓存命中多一次 stat(),相比它要避免的 ~7ms git 进程开销可以忽略;不新增任何 git 探测):

- 新增 directoryPresence():**三态**判断,只有 ENOENT / ENOTDIR 才算「已消失」;EACCES / EPERM /
  EBUSY / EIO / EMFILE(被占用的句柄、杀软扫描、卡住的网络路径)一律按「无法判定」处理 —— 把这类
  瞬时错误当成「已消失」会因为一次抖动就把侧栏改到仓库顶层,比它要修的那个陈旧答案更糟;
- topOfActivePath():命中缓存且缓存的是路径时校验它,已消失才失效;失效后的**重新探测结果(负答案)
  deliberately 不写回缓存** —— pathTopCache 没有 TTL,一个由「消失」产生的负答案会把会话永久钉在
  仓库顶层,连「worktree 删掉后又建回来」都再也跟不上了;
- activeWorktreeRootOf():命中 TTL 缓存时同样校验 root(root === base 时跳过)。

测试(tests/active-worktree.spec.ts,共 11 例):

- 原有 #960 用例:跟随 worktree → 删掉 → 同一会话回落到仓库(TTL 层)+ 新会话不被内层缓存污染;
- 复核补的两例:① 目录还在、但 stat 连续报 EPERM/EBUSY/EACCES/EIO(整趟 ask 都失败,模拟被占用的
  句柄/杀软/卡死的网络路径)必须继续跟随 worktree,不许改根;② 删掉后**原地重建**的 worktree 必须被
  重新跟随(用新会话验证,因为旧会话按文档语义要等 15s TTL 过期)。
  两例都按「先破坏实现再跑」验证过:把三态退化成「任何错误=消失」→ ①红;把失效产生的负答案写回缓存
  → ②红。

变异实测:还原 src/active-worktree.ts → #960 用例红在 Received "…\\worktree"(已删除目录);
三态退化 → 瞬时错误用例红;负答案回写 → 重建用例红。

验证(本机 Windows / Node 22):
- pnpm exec vitest run tests/active-worktree.spec.ts → 11/11;pnpm typecheck / pnpm lint → 通过
- pnpm test(全量)对照干净 dev:失败集合为子集,无新增失败(详见 PR 描述;两条既有失败在各树上
  单独复跑时只剩 plugin-meta —— 那是 Windows tar 输出 CRLF 导致的确定性失败,不是超时)
未做:真机侧栏复现(本机没有装该插件的 DSH profile)。
This commit is contained in:
m4ku1337 committed 2026-10-17 05:27:49 +08:00
1 parent 693b4850e3
commit d5853da9d2
4 files changed
+167 -5

No files matched your search

+4
View File
@@ -2,6 +2,10 @@
> 本文档收录 dsh-better-sidebar 的完整发布历史(最新版摘要见 [README](README_ZH.md);同步发布于 [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases))。
### Unreleased
- 🐞 **侧栏不再被钉死在已删除的 linked worktree 上**([#960](https://github.com/omdsh-dev/DSH-better-sidebar/issues/960)):worktree 被外部删除(`git worktree remove`、或直接删目录)后,进程级的路径/顶层缓存仍会把它当作活跃根目录返回,文件树报「文件夹不存在」、git 面板报「不是 git 仓库」,主仓库完好却只能重启恢复。现在缓存命中时会校验目标目录是否仍在(一次 `stat()`,相比它要避免的 ~7ms git 进程开销可忽略),已消失即失效并回落到会话 cwd 对应的仓库顶层。
### v0.27.0
- 🌿 **Git 页面重做:VS Code Source Control 结构 + 只读提交图(同一页签)**([#941](https://github.com/omdsh-dev/DSH-better-sidebar/issues/941),贡献者 PR [#944](https://github.com/omdsh-dev/DSH-better-sidebar/pull/944) @hairyf + [#969](https://github.com/omdsh-dev/DSH-better-sidebar/pull/969) @vlln):「文件变动 > Git」的内容区改为 Source Control 结构——可折叠的 Changes(多行 Message + 仅填草稿的 Generate、Merge / Staged / Changes 三组各自独立折叠与计数、整行 hover)与 Graph 区、常驻底栏(可点击分支 + `*`/`+`/`!` 标记、upstream 的 `↓`/`↑` 与安全 Pull-then-Push);Push/Pull 与 worktree·子仓库选择移入 More Actions;提交只消费已暂存项,冲突 / 空消息 / 无暂存时禁止,草稿按会话·仓库·worktree 隔离。Graph 区由 **#969 的有界只读引擎**渲染(专用 `git.graph` 路由:子先于父的拓扑序、分支筛选、游标失效显式返回 `graph-stale`、每页 200 / 偏移 10000 / 分支 1000 / 进程 10 s / 输出 8 MiB 上限,超限报错不静默截断;泳道连线与引用徽章用主题状态色,hover 卡片与提交详情卡;**纯读取**——不 checkout / fetch / 改任何 ref)。底部预览面板改为固定三签 `提交详情 / 内容 / 差异`(有内容才有差异,读操作落在内容签)。**设计取舍与实施偏差见 [docs/plans/2026-10-16-git-page-vscode-scm-merge.md](docs/plans/2026-10-16-git-page-vscode-scm-merge.md)**(贡献者 PR [#939](https://github.com/omdsh-dev/DSH-better-sidebar/pull/939) @hairyf 的官方下划线 Tabs 镜片切换保留;第三个「提交图」镜头刻意未上线)。
+4
View File
@@ -4,6 +4,10 @@
>
> 📝 The Chinese [CHANGELOG](./CHANGELOG.md) is the authoritative, item-by-item record; this file carries the English summaries and has historically lagged behind it. Where the two disagree, the Chinese one is current.
### Unreleased
- 🐞 **The sidebar no longer pins itself to a deleted linked worktree** ([#960](https://github.com/omdsh-dev/DSH-better-sidebar/issues/960)): once a worktree was deleted externally (`git worktree remove`, or a plain folder delete), the process-wide path / top-level caches kept answering with it, so the file tree reported a missing folder and every git command reported "not a git repository" — with no recovery short of a restart. Cache hits now verify the directory still exists (one `stat()`, negligible next to the ~7ms git spawn these caches exist to avoid) and otherwise invalidate, falling back to the session cwd's repository.
### v0.27.0
- **One Git page with Source Control and a read-only commit graph**: collapsible Changes and Graph sections, independent Merge / Staged / Changes groups, commit-message drafts, and a persistent branch/sync footer. The bounded graph reader supports branch filtering, lane connections, reference badges, hover details and commit inspection without checking out branches or changing refs. The shared preview keeps three tabs: Commit details / Content / Diff. Based on [#944](https://github.com/omdsh-dev/DSH-better-sidebar/pull/944) by @hairyf and [#969](https://github.com/omdsh-dev/DSH-better-sidebar/pull/969) by @vlln; the official lens tabs from [#939](https://github.com/omdsh-dev/DSH-better-sidebar/pull/939) by @hairyf remain, with no third graph lens.
+50 -5
View File
@@ -118,6 +118,24 @@ function pathKeyOf(value: string): string {
return value.replace(/[\\/]+/g, '/').replace(/\/+$/, '').toLowerCase()
}
/**
* Whether a cached path is still there, as a THREE-way answer.
*
* Only ENOENT / ENOTDIR prove the directory is gone. Any other failure — EACCES /
* EPERM / EBUSY / EIO / EMFILE: a locked handle, an antivirus pass holding the
* directory, a hung SMB/UNC worktree — says nothing about existence. Treating those
* as "gone" would re-root the sidebar because of one transient error, which is worse
* than the stale answer this whole check exists to remove (issue #960 review).
*/
async function directoryPresence(path: string): Promise<'live' | 'gone' | 'unknown'> {
try {
return (await stat(path)).isDirectory() ? 'live' : 'gone'
} catch (error) {
const code = String((error as { code?: unknown } | null)?.code ?? '')
return code === 'ENOENT' || code === 'ENOTDIR' ? 'gone' : 'unknown'
}
}
/** Whether `target` is `base` itself or lives under it. */
function pathUnderOf(base: string, target: string): boolean {
const b = pathKeyOf(base)
@@ -230,9 +248,29 @@ async function topOfActivePath(value: string): Promise<string | undefined> {
const cached = pathTopCache.get(key)
// A cached `undefined` ("not in a repository") is the answer that keeps a
// non-repo session cheap, so it is re-inserted like any other hit — which
// also refreshes its recency in the bounded LRU.
cachePut(pathTopCache, key, cached, PATH_TOP_CACHE_MAX)
return cached
// also refreshes its recency in the bounded LRU. A cached PATH is only
// reusable while the directory is still there: a followed worktree the user
// deletes would otherwise be handed to every route forever (issue #960).
if (cached === undefined) {
cachePut(pathTopCache, key, cached, PATH_TOP_CACHE_MAX)
return cached
}
if (await directoryPresence(cached) !== 'gone') {
cachePut(pathTopCache, key, cached, PATH_TOP_CACHE_MAX)
return cached
}
// Gone for real: drop the entry and probe again. A NEGATIVE from this
// re-probe is deliberately NOT cached — `pathTopCache` has no TTL, so a
// negative produced by a disappearance would pin the session away from a
// path that can come back (`git worktree add` again, a restored folder).
// Both the deletion and the re-creation are then self-healing.
pathTopCache.delete(key)
const again = await topLevelOf(value)
const top = again === undefined ? await topLevelOf(dirname(value)) : again
if (top === undefined) return undefined
const result = requireAbsolute(top)
cachePut(pathTopCache, key, result, PATH_TOP_CACHE_MAX)
return result
}
let top = await topLevelOf(value)
if (top === undefined) top = await topLevelOf(dirname(value))
@@ -346,8 +384,15 @@ export async function activeWorktreeRootOf(ctx: Context, sessionId: string, base
// one's root.
const cached = activeWorktreeRootCache.get(sessionId)
if (cached !== undefined && cached.expires > Date.now() && cached.base === base) {
cachePut(activeWorktreeRootCache, sessionId, cached, ACTIVE_ROOT_CACHE_MAX)
return cached.root
// Same existence rule as topOfActivePath: serving a root that no longer
// exists keeps the sidebar pinned to a deleted directory for another TTL
// window (issue #960). `root === base` is the one case with nothing better
// to fall back to, so it skips the stat.
if (cached.root === base || await directoryPresence(cached.root) !== 'gone') {
cachePut(activeWorktreeRootCache, sessionId, cached, ACTIVE_ROOT_CACHE_MAX)
return cached.root
}
activeWorktreeRootCache.delete(sessionId)
}
const flightKey = `${sessionId}\0${base}`
const pending = activeRootInFlight.get(flightKey)
+109
View File
@@ -35,6 +35,25 @@ vi.mock('../src/git.ts', async (importOriginal) => {
}
})
/** The plugin's stat seam: fail the NEXT n stat() calls with a chosen errno. */
const statSeam = vi.hoisted(() => ({ failNext: 0, code: 'EPERM' }))
vi.mock('node:fs/promises', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs/promises')>()
return {
...actual,
stat: async (...args: Parameters<typeof actual.stat>) => {
if (statSeam.failNext > 0) {
statSeam.failNext -= 1
const error = new Error(statSeam.code + ': injected by the spec') as NodeJS.ErrnoException
error.code = statSeam.code
throw error
}
return actual.stat(...args)
},
}
})
const IDENTITY = {
GIT_AUTHOR_NAME: 'dsh-better-sidebar-test',
GIT_AUTHOR_EMAIL: 'test@dsh.invalid',
@@ -288,4 +307,94 @@ describe('active worktree root', () => {
removeTree(root)
}
})
/**
* A followed worktree can be deleted out from under a RUNNING session
* (`git worktree remove`, or a plain folder delete). Both process-wide maps
* used to answer from a cached path forever, so the sidebar stayed pinned to
* a directory that no longer existed — file tree "folder not found", git
* panel "not a git repository" — with no recovery short of a host restart
* (issue #960).
*/
it('falls back to the repository when the followed worktree is deleted (#960)', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-'))
const repo = join(root, 'repo')
const worktree = join(root, 'worktree')
try {
initRepo(repo, 'a.txt')
git(repo, ['worktree', 'add', '-q', '-b', 'agent', worktree])
const calls = [{ cwd: worktree, path: join(worktree, 'a.txt') }]
const ctx = sessionCtx(repo, calls)
await expect(activeWorktreeRootOf(ctx, 's-deleted', repo)).resolves.toBe(realpathSync.native(worktree))
// The worktree disappears while the session keeps running.
removeTree(worktree)
// (1) the root TTL cache must not keep serving the dead path…
await expect(activeWorktreeRootOf(ctx, 's-deleted', repo)).resolves.toBe(realpathSync.native(repo))
// (2) …and a fresh session must not resurrect it through the inner caches.
await expect(activeWorktreeRootOf(ctx, 's-deleted-fresh', repo)).resolves.toBe(realpathSync.native(repo))
} finally {
removeTree(root)
}
})
/**
* Two cases the first revision of the #960 fix got wrong (found in review):
*
* · a TRANSIENT stat failure on a directory that still exists (a locked handle,
* an antivirus pass, a hung SMB/UNC worktree: EPERM/EACCES/EBUSY/EIO) must not
* re-root the session — only ENOENT/ENOTDIR prove the directory is gone;
* · a worktree that is deleted and then CREATED AGAIN must be followed again: a
* negative produced by the invalidation re-probe must not be cached, because
* `pathTopCache` has no TTL and would pin the session away for good.
*/
it('a transient stat failure on a live directory does not re-root the session (#960 review)', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-'))
const repo = join(root, 'repo')
const worktree = join(root, 'worktree')
try {
initRepo(repo, 'a.txt')
git(repo, ['worktree', 'add', '-q', '-b', 'agent', worktree])
const calls = [{ cwd: worktree, path: join(worktree, 'a.txt') }]
const ctx = sessionCtx(repo, calls)
await expect(activeWorktreeRootOf(ctx, 's-flaky', repo)).resolves.toBe(realpathSync.native(worktree))
// The directory is still there; its stat fails for the WHOLE ask the way a locked
// handle, an antivirus pass or a hung SMB/UNC worktree behaves. Only
// ENOENT/ENOTDIR may be read as "gone": anything else must leave the session where
// it is, instead of re-rooting it (and, with the old rule, for good).
for (const code of ['EPERM', 'EBUSY', 'EACCES', 'EIO']) {
statSeam.code = code
statSeam.failNext = 50
await expect(activeWorktreeRootOf(ctx, 's-flaky', repo)).resolves.toBe(realpathSync.native(worktree))
statSeam.failNext = 0
}
} finally {
statSeam.failNext = 0
removeTree(root)
}
})
it('re-follows a worktree that comes back after being deleted (#960 review)', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-'))
const repo = join(root, 'repo')
const worktree = join(root, 'worktree')
try {
initRepo(repo, 'a.txt')
git(repo, ['worktree', 'add', '-q', '-b', 'agent', worktree])
const calls = [{ cwd: worktree, path: join(worktree, 'a.txt') }]
const ctx = sessionCtx(repo, calls)
await expect(activeWorktreeRootOf(ctx, 's-back', repo)).resolves.toBe(realpathSync.native(worktree))
removeTree(worktree)
await expect(activeWorktreeRootOf(ctx, 's-back', repo)).resolves.toBe(realpathSync.native(repo))
// `git worktree prune` because the directory was deleted by hand, not by git.
git(repo, ['worktree', 'prune'])
git(repo, ['worktree', 'add', '-q', '-b', 'agent2', worktree])
// The session that fell back keeps the repository until its 15 s TTL expires
// (documented behaviour), but a FRESH ask must pick the worktree up again: the
// invalidation re-probe deliberately does not cache its negative.
await expect(activeWorktreeRootOf(ctx, 's-back-fresh', repo)).resolves.toBe(realpathSync.native(worktree))
} finally {
removeTree(root)
}
})
})