diff --git a/CHANGELOG.md b/CHANGELOG.md index a99e0824..40544047 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 镜片切换保留;第三个「提交图」镜头刻意未上线)。 diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md index 2343f933..67426e5d 100644 --- a/CHANGELOG_EN.md +++ b/CHANGELOG_EN.md @@ -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. diff --git a/src/active-worktree.ts b/src/active-worktree.ts index b6f76bb2..1f59203e 100644 --- a/src/active-worktree.ts +++ b/src/active-worktree.ts @@ -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 { 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) diff --git a/tests/active-worktree.spec.ts b/tests/active-worktree.spec.ts index c9d406fb..af8847c8 100644 --- a/tests/active-worktree.spec.ts +++ b/tests/active-worktree.spec.ts @@ -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() + return { + ...actual, + stat: async (...args: Parameters) => { + 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) + } + }) })