From cf52fed79181f8a828373313d06f2abe0b70d6b3 Mon Sep 17 00:00:00 2001 From: ymac <707337118@qq.com> Date: Wed, 14 Oct 2026 23:11:10 +0800 Subject: [PATCH] =?UTF-8?q?fix(active-worktree):=20=E5=B7=A5=E4=BD=9C?= =?UTF-8?q?=E5=8C=BA=E5=86=85=E7=9A=84=20linked=20worktree=20=E5=8F=AA?= =?UTF-8?q?=E5=9C=A8=E5=90=8C=E4=BB=93=E5=BA=93=E6=97=B6=E9=87=87=E7=BA=B3?= =?UTF-8?q?=EF=BC=88#952=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 采纳判定原先只看「top ≠ base 且是 linked worktree」,于是容器工作区里嵌套仓库 的 worktree(bare 仓库的 main/local 检出、子项目自己的 .worktrees)也被当成 「会话搬到了别处」,explorer 被静默重定根到那个子目录,工作区其余兄弟目录全部 消失(报告者离线重放 27 个真实会话,20 个中招,最长的一次触发后 466 分钟仍生效)。 判定改为按仓库身份:`git rev-parse --git-common-dir` 相等才是同一个仓库。 - 工作区之外:任何 linked worktree 照旧采纳(PR #802 的跨仓库场景不变)。 - 工作区之内:只有与会话仓库同 common dir 的才采纳 —— 同一仓库的 `.worktrees/` 仍然跟随,嵌套仓库的 worktree 不再抢根。 - base 是文件系统根(pathKey 为空)时跳过该判定,避免整条跟随功能被关掉。 - 身份探测复用一次 spawn 与进程级缓存,`--absolute-git-dir` / `--git-common-dir` 的相对拼写按被探测目录归一化。 tests/active-worktree.spec.ts:新增 4 例(嵌套普通仓库不采纳、嵌套 bare 仓库 不采纳、同仓库工作区内仍采纳、同仓库工作区外仍采纳);既有 3 例(跨仓库采纳、 无证据保持 cwd、真实路径探测)逐字未改。 --- src/active-worktree.ts | 110 ++++++++++++++++++++++++++++------ tests/active-worktree.spec.ts | 71 ++++++++++++++++++++++ 2 files changed, 164 insertions(+), 17 deletions(-) diff --git a/src/active-worktree.ts b/src/active-worktree.ts index a3ecff12..7380a49f 100644 --- a/src/active-worktree.ts +++ b/src/active-worktree.ts @@ -13,7 +13,13 @@ * `git rev-parse --show-toplevel` (falling back to its directory for files), * and only top levels whose `--absolute-git-dir` differs from their * `--git-common-dir` (i.e. real LINKED worktrees, not the main checkout and - * not submodules) are adopted. The highest-scoring linked worktree of the + * not submodules) are adopted. A linked worktree that sits INSIDE the session + * workspace is adopted only when it belongs to the SAME repository — a + * `git worktree add .worktrees/x` of the session's own repo is the session + * moving, while a nested repository's worktree is ordinary content of the + * workspace: re-rooting the explorer into it hides every sibling directory + * (#952). Outside the workspace any linked worktree is adopted, which is PR + * #802's cross-repository case. The highest-scoring adoptable worktree of the * newest event that has one wins; when there is no evidence the session cwd is * kept (lifted to the repository top level for subdirectory sessions). * @@ -50,7 +56,7 @@ const ACTIVE_ROOT_PATH_PATTERN = /[A-Za-z]:(?:\\|\/)[^\\/\s"'\x60,;|)<>*?]+(?:[\ */ const activeWorktreeRootCache = new Map() const pathTopCache = new Map() -const linkedWorktreeCache = new Map() +const gitIdentityCache = new Map() /** * Normalized IDENTITY of a path (case- and separator-insensitive), for @@ -158,28 +164,98 @@ async function topOfActivePath(value: string): Promise { } /** - * Whether a git top level is a LINKED worktree: its git dir lives under the - * common dir (`
/.git/worktrees/`) instead of being it. Submodules - * report the same dir for both, so they are excluded. + * The git identity of one checkout, as `git rev-parse` reports it: the + * checkout's OWN git dir and the COMMON dir every checkout of that repository + * shares. Two paths belong to the same repository exactly when their common + * dirs match, which is the only reliable way to tell "the session moved into a + * worktree of its own repo" from "the workspace contains another repo's + * worktree" (#952) — a bare repo's checkouts and a container workspace's + * sub-projects are indistinguishable by path alone. + * + * `main checkout: gitDir === commonDir === /.git`; `linked worktree: + * gitDir = /.git/worktrees/, commonDir = /.git`; `submodule: + * both are /.git/modules/`. */ -async function isLinkedWorktree(top: string): Promise { - const key = pathKeyOf(top) - const cached = linkedWorktreeCache.get(key) - if (cached !== undefined) return cached - let linked = false +interface GitIdentity { + /** The checkout's own git dir (`--absolute-git-dir`). */ + gitDir: string + /** The repository's shared git dir (`--git-common-dir`). */ + commonDir: string +} + +/** + * `git rev-parse` identity of one directory, cached process-wide (a probe is a + * spawn). `undefined` for a directory that is not in a repository, or whose + * answer is unusable — callers treat that as "no identity", never as a match. + * @param dir - an existing directory (or any path inside one). + * @returns the identity, or undefined. + */ +async function gitIdentityOf(dir: string): Promise { + const key = pathKeyOf(dir) + if (gitIdentityCache.has(key)) return gitIdentityCache.get(key) + let identity: GitIdentity | undefined try { - const out = (await runGit(top, ['rev-parse', '--absolute-git-dir', '--git-common-dir'])).trim().split(/\r?\n/) + const out = (await runGit(dir, ['rev-parse', '--absolute-git-dir', '--git-common-dir'])).trim().split(/\r?\n/) const gitDir = out[0] const commonRaw = out[1] ?? '' if (gitDir !== undefined && gitDir !== '' && commonRaw !== '') { - const common = isAbsolute(commonRaw) ? commonRaw : join(top, commonRaw) - linked = pathKeyOf(requireAbsolute(gitDir)) !== pathKeyOf(requireAbsolute(common)) + // The common dir comes back relative when the checkout is the main one + // (`.git`); resolve it against the probed directory, not the process cwd. + identity = { + gitDir: requireAbsolute(gitDir), + commonDir: requireAbsolute(isAbsolute(commonRaw) ? commonRaw : join(dir, commonRaw)), + } } } catch { - linked = false + identity = undefined } - linkedWorktreeCache.set(key, linked) - return linked + gitIdentityCache.set(key, identity) + return identity +} + +/** + * Whether a git top level is a LINKED worktree: its git dir lives under the + * common dir (`
/.git/worktrees/`) instead of being it. Submodules + * report the same dir for both, so they are excluded. + * + * The two dirs are compared through {@link gitIdentityOf}, which returns the + * COMMON dir as well: the same value identifies the repository a checkout + * belongs to, which is what {@link isAdoptableTop} compares against the + * session workspace. + */ +async function isLinkedWorktree(top: string): Promise { + const identity = await gitIdentityOf(top) + return identity !== undefined && pathKeyOf(identity.gitDir) !== pathKeyOf(identity.commonDir) +} + +/** + * Whether a linked worktree is the session MOVING there, rather than ordinary + * content of the workspace it already roots (#952). + * + * Outside the workspace any linked worktree counts — that is exactly PR #802's + * case (the session's header cwd points at one repository and the agent works + * in a worktree of another). Inside the workspace the answer depends on the + * repository: `.worktrees/` of the session's OWN repo is the session + * working on a branch, which the explorer should follow; the linked worktrees + * of a repository NESTED in the workspace (a bare repo's checkouts, a + * container workspace's sub-projects) are ordinary content, and adopting one + * re-roots the explorer into that single subdirectory and hides every sibling + * — the reported 20-of-27-sessions bug. + * + * @param top - a candidate's `git rev-parse --show-toplevel`. + * @param base - the session's effective workspace root. + * @returns whether the candidate may become the active root. + */ +async function isAdoptableTop(top: string, base: string): Promise { + if (!(await isLinkedWorktree(top))) return false + // A base of `/` (or of another filesystem root) puts everything "inside"; + // keeping the check would switch the whole feature off, so treat it as no + // workspace at all. + if (pathKeyOf(base) === '' || !pathUnderOf(base, top)) return true + const candidate = await gitIdentityOf(top) + const workspace = await gitIdentityOf(base) + return candidate !== undefined && workspace !== undefined + && pathKeyOf(candidate.commonDir) === pathKeyOf(workspace.commonDir) } /** The newest linked worktree the session's tool/call paths resolve to. */ @@ -203,7 +279,7 @@ async function activeRootFromEvents(events: readonly SidebarSessionEvent[], base if (top === undefined) continue const topKey = pathKeyOf(top) if (topKey === baseKey) continue - if (!(await isLinkedWorktree(top))) continue + if (!(await isAdoptableTop(top, base))) continue const entry = scores.get(topKey) if (entry === undefined) scores.set(topKey, { top, score: candidate.score }) else entry.score += candidate.score diff --git a/tests/active-worktree.spec.ts b/tests/active-worktree.spec.ts index 73d4c407..9ce69b5d 100644 --- a/tests/active-worktree.spec.ts +++ b/tests/active-worktree.spec.ts @@ -117,4 +117,75 @@ describe('active worktree root', () => { rmSync(root, { recursive: true, force: true }) } }) + + it('does not adopt a nested repository worktree that lives INSIDE the workspace (#952)', async () => { + // A container workspace (itself a repo) holding sub-projects is normal + // content: re-rooting the explorer into `W/nested/wt` hides every sibling. + const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-')) + const container = join(root, 'W') + const nested = join(container, 'nested') + const nestedWt = join(nested, 'wt') + try { + initRepo(container, 'a.txt') + initRepo(nested, 'b.txt') + git(nested, ['worktree', 'add', '-q', '-b', 'feat', nestedWt]) + const ctx = sessionCtx(container, [{ cwd: nestedWt, file_path: join(nestedWt, 'b.txt') }]) + // The workspace root is the answer, not the nested checkout. + await expect(activeWorktreeRootOf(ctx, 's-nested', container)).resolves.toBe(realpathSync.native(container)) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + it('does not adopt the worktrees of a nested BARE repository (#952, reported layout)', async () => { + // The reporter's real shape: `W/paper_downloader` is a bare repo and + // `W/paper_downloader/{main,local}` are its linked worktrees. + const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-')) + const container = join(root, 'W') + const seed = join(root, 'seed') + const bare = join(container, 'paper_downloader') + const bareMain = join(bare, 'main') + try { + initRepo(container, 'a.txt') + initRepo(seed, 'b.txt') + git(root, ['clone', '--bare', '-q', seed, bare]) + // `-b wt`: the bare clone's own HEAD already owns `main`, and one branch + // cannot be checked out in two worktrees. + git(bare, ['worktree', 'add', '-q', bareMain, '-b', 'wt']) + const ctx = sessionCtx(container, [{ cwd: bareMain, path: join(bareMain, 'b.txt') }]) + await expect(activeWorktreeRootOf(ctx, 's-bare', container)).resolves.toBe(realpathSync.native(container)) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + it('still follows the SAME repository worktree inside the workspace (#802 / #947 layout)', async () => { + // `.worktrees/` of the session's own repo IS the session moving. + const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-')) + const repo = join(root, 'repo') + const worktree = join(repo, 'frontend', '.worktrees', 'wt') + try { + initRepo(repo, 'a.txt') + mkdirSync(join(repo, 'frontend', '.worktrees'), { recursive: true }) + git(repo, ['worktree', 'add', '-q', '-b', 'agent', worktree]) + const ctx = sessionCtx(repo, [{ cwd: worktree, path: join(worktree, 'a.txt') }]) + await expect(activeWorktreeRootOf(ctx, 's-same-repo', repo)).resolves.toBe(realpathSync.native(worktree)) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + it('still follows a worktree of the same repository OUTSIDE the workspace', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-')) + const repo = join(root, 'repo') + const worktree = join(root, 'outside-wt') + try { + initRepo(repo, 'a.txt') + git(repo, ['worktree', 'add', '-q', '-b', 'agent', worktree]) + const ctx = sessionCtx(repo, [{ cwd: worktree, path: join(worktree, 'a.txt') }]) + await expect(activeWorktreeRootOf(ctx, 's-outside', repo)).resolves.toBe(realpathSync.native(worktree)) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) })