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 1/4] =?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 }) + } + }) }) From 6f2054a56c8d340d4989ed2b69bf9adb5dd827b9 Mon Sep 17 00:00:00 2001 From: ymac <707337118@qq.com> Date: Wed, 14 Oct 2026 23:18:08 +0800 Subject: [PATCH 2/4] =?UTF-8?q?fix(sidebar):=20=E4=BC=9A=E8=AF=9D=E5=9C=B0?= =?UTF-8?q?=E5=9D=80=E7=9A=84=E5=9F=BA=E5=87=86=E7=BB=9F=E4=B8=80=E5=88=B0?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=20header=20cwd=EF=BC=88#947=20/=20#950?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 会话地址 `dsh-resource://file/session//` 的相对路径,宿主构造端 (ui-chat 的 openFile)与解析端(api-workspace-files)都取会话存储的 header cwd; 插件自 #802 起让 fs 路由与原生 tab 体跟随活动 worktree 根,于是地址里的相对拼写 被活动根再拼一次:worktree 嵌在 header cwd 之下时路径翻倍(ENOENT,聊天链接与 改动页都中招),两个检出都有同名文件时静默读到另一份(可保存写回)。 规则:构造端与消费端共用同一个基准,并在地址被读到的边界把它解析成绝对路径—— 绝对路径在任何基准下都一样,下游再无可重定基的余地。 - 新增 src/client/address-base.ts 的 addressBaseOf(ctx, sessionId):会话列表里的 header cwd(宿主地址契约的基准),取不到返回 undefined 让调用方回退。 - 消费边界:fileParamsOf(info, base?) 在切 `path:line` 规格之前把地址路径解析成 绝对路径;native/index.ts 的 editor 类型注入 paramsOf: (info) => fileParamsOf(info, addressBaseOf(ctx, fileSessionIdOf(info)))。 - 构造边界:native/surface.ts 的 fileAddress 与 sidebar-file.ts 的 openClaimedNativeFile 都以 addressBaseOf 优先,调用方 cwd 只作回退——同一文件 只有一个地址(与宿主聊天路径的地址一致,页签照旧合并)。 - 意图侧:openSidebarFile(ctx, sessionId, path, { line?, cwd? }) 的 cwd 是调用方 手上的活根(EditorHost / 改动页 / markdown 面板传 useSessionRoot 的结果), 相对路径按它解析,缺省才回退 header cwd——同一相对路径在各入口不再落到不同检出。 - 测试:新增 tests/worktree-address.spec.ts(基准三态 / 绝对路径不可重定基 / 构造端基准 / 相对路径按活根解析),真 git worktree 夹具;file-open-claim 的 `line` 位置参数随之改为 `{ line }`(唯一签名变更点)。 --- src/client/EditorHost.tsx | 4 +- src/client/address-base.ts | 44 ++++++ src/client/builtins/tabs.tsx | 2 +- src/client/native/index.ts | 33 ++++- src/client/native/surface.ts | 11 +- src/client/sidebar-file.ts | 46 +++++-- src/client/use-markdown-surface.ts | 6 +- tests/file-open-claim.spec.ts | 2 +- tests/worktree-address.spec.ts | 209 +++++++++++++++++++++++++++++ 9 files changed, 333 insertions(+), 24 deletions(-) create mode 100644 src/client/address-base.ts create mode 100644 tests/worktree-address.spec.ts diff --git a/src/client/EditorHost.tsx b/src/client/EditorHost.tsx index cadcaced..d991fe43 100644 --- a/src/client/EditorHost.tsx +++ b/src/client/EditorHost.tsx @@ -235,13 +235,13 @@ export function EditorHost(props: { ctx.get('betterSidebar')?.updateTab(tab.id, { path: absolute, title: baseName(absolute) }, scope.sessionId) } } else { - openSidebarFile(ctx, scope.sessionId, absolute) + openSidebarFile(ctx, scope.sessionId, absolute, { cwd: scope.cwd }) } } /** The context menu's explicit "new tab" escape (per-path dedupe). */ const openFileNewTab = (absolute: string): void => { - openSidebarFile(ctx, scope.sessionId, absolute) + openSidebarFile(ctx, scope.sessionId, absolute, { cwd: scope.cwd }) } /** diff --git a/src/client/address-base.ts b/src/client/address-base.ts new file mode 100644 index 00000000..8a4d3f41 --- /dev/null +++ b/src/client/address-base.ts @@ -0,0 +1,44 @@ +/** + * The workspace root a session-scoped file ADDRESS is built and read with. + * + * DSH's address contract fixes that base to the session's STORED header cwd: + * the host chat builds every file link with + * `fileAddressFor(sessionId, ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd, path)` + * (DSH `ui-chat`), and the host's own file resolver reads the relative path + * back against `sessions.get(sessionId).header.cwd` (DSH `api-workspace-files`) + * — the same value, so the host round-trips perfectly. + * + * The plugin does not: since #802 its filesystem routes follow the ACTIVE git + * worktree, so an address's relative path re-resolved by a worktree-rooted + * reader lands somewhere else entirely — doubled when the worktree sits inside + * the stored cwd (`/frontend/.worktrees/wt/a.md` arrives as + * `frontend/.worktrees/wt/a.md` and becomes + * `/frontend/.worktrees/wt/a.md`, ENOENT — #947), or silently on the + * same-named file of another checkout (#950). + * + * The rule that removes the whole family: an address's base is THIS value, + * never the active worktree root, and an address's path is resolved to an + * absolute one at the boundary where the address is read, so no + * worktree-rooted code downstream ever sees a relative path it could re-base. + * Live relative paths the user or the plugin intends (file tree, typed + * paths, links inside a document) keep using the active root, which is what + * `useSessionRoot` is for. + * + * @param ctx - client context carrying the session list. + * @param sessionId - the session the address belongs to; `undefined` answers + * `undefined` so callers can fall back to their own cwd. + * @returns the stored header cwd, or `undefined` when it is unknown (a + * stripped-down host or a bare test context). + */ +import type { Context } from '../context-types.ts' + +export function addressBaseOf(ctx: Context, sessionId: string | undefined): string | undefined { + if (sessionId === undefined) return undefined + try { + return ctx.sessions?.list?.getSnapshot?.()?.byId?.[sessionId]?.cwd + } catch { + // A context without the session list (or with a broken one) keeps the + // caller's own cwd; the address is no worse than before this helper. + return undefined + } +} diff --git a/src/client/builtins/tabs.tsx b/src/client/builtins/tabs.tsx index b83804ae..ed836fb9 100644 --- a/src/client/builtins/tabs.tsx +++ b/src/client/builtins/tabs.tsx @@ -141,7 +141,7 @@ export function builtinTabs(ctx: Context): readonly TabDescriptor[] { scope={scope} tab={tab} visible={visible} - onOpenFile={(path) => { openSidebarFile(ctx, scope.sessionId, path) }} + onOpenFile={(path) => { openSidebarFile(ctx, scope.sessionId, path, { cwd: scope.cwd }) }} onOpenDiff={onOpenDiff} /> ), diff --git a/src/client/native/index.ts b/src/client/native/index.ts index 388220af..a95fa60b 100644 --- a/src/client/native/index.ts +++ b/src/client/native/index.ts @@ -23,9 +23,10 @@ * absent from the native guide and `openTab` refuses it. */ import type { Context } from '../../context-types.ts' +import { addressBaseOf } from '../address-base.ts' import { t } from '../locales.ts' import { splitTrailingLineSpec } from '../path-line.ts' -import { baseName } from '../paths.ts' +import { baseName, resolveSidebarPath } from '../paths.ts' import { parseFileAddress } from '../resource-address.ts' import type { BetterSidebarService, TabDescriptor } from '../service.ts' import type { SidebarStore } from '../state.ts' @@ -178,14 +179,29 @@ interface Registration { * {@link NativeTabParams.line}. The range end and the column are deliberately * dropped: {@link splitTrailingLineSpec} parses them, and a start line is all * the editor has anywhere to put a cursor. + * + * `base` is where an address-relative path is resolved, and it must be the + * base the ADDRESS was built with — the session's stored header cwd, see + * `src/client/address-base.ts` — never the tab body's worktree root. Without + * it the seed stays relative and every downstream reader (the viewer's + * `fs.read`, the editor, the directory watch) re-bases it on the ACTIVE + * worktree: a chat link to `/frontend/.worktrees/wt/a.md` arrives as + * `frontend/.worktrees/wt/a.md` and is joined onto the worktree root a second + * time (#947), or silently reads the same-named file of another checkout + * (#950). Omitted (a caller with no session context) keeps the historical + * relative seed. * @param info - the native tab record the body is drawing. + * @param base - the address's own base, when the caller knows it. * @returns the seed, or `undefined` when the tab is not a file address. */ -export function fileParamsOf(info: NativeTabInfo): NativeTabParams | undefined { +export function fileParamsOf(info: NativeTabInfo, base?: string): NativeTabParams | undefined { const address = parseFileAddress(info.tab.contentId) if (address === undefined) return undefined - const spec = splitTrailingLineSpec(address.path) - if (spec === undefined) return { path: address.path } + // Resolve BEFORE the trailing line spec is split off: the spec belongs to + // the file name, and a base can only be prepended to the path. + const path = base === undefined ? address.path : resolveSidebarPath(base, address.path) + const spec = splitTrailingLineSpec(path) + if (spec === undefined) return { path } return { path: spec.path, title: baseName(spec.path), line: spec.line } } @@ -381,7 +397,14 @@ export function registerNativeSurface(deps: NativeSurfaceDeps): () => void { slots = registerSlots( id, { ctx, store, service, records, descriptorId: descriptor.id }, - isEditor ? { paramsOf: fileParamsOf, sessionIdOf: fileSessionIdOf } : {}, + isEditor + ? { + // The address's own session, not the seat's: a file address + // carries the session whose workspace resolves its path. + paramsOf: (info: NativeTabInfo) => fileParamsOf(info, addressBaseOf(ctx, fileSessionIdOf(info))), + sessionIdOf: fileSessionIdOf, + } + : {}, ) } catch (error) { disposeSafely(disposeType, `native tab type "${id}"`) diff --git a/src/client/native/surface.ts b/src/client/native/surface.ts index 6d61b8ef..1300b4d9 100644 --- a/src/client/native/surface.ts +++ b/src/client/native/surface.ts @@ -21,6 +21,7 @@ * - layout state is memory-only, so a queued open is not durable either. */ import type { Context } from '../../context-types.ts' +import { addressBaseOf } from '../address-base.ts' import { fileAddressFor } from '../resource-address.ts' import type { NativePathTab, NativeTabParams, SidebarSurface } from '../service.ts' import type { NativeTabRecords } from './tab-adapter.tsx' @@ -257,7 +258,15 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na enqueue({ kind: 'resource', sessionId, address, line, revealIfOpened, preferNewPane: preferNewPane === true }) }, fileAddress(sessionId, cwd, path) { - return fileAddressFor(sessionId, cwd, path) + // The address's base is the session's stored header cwd — the value the + // HOST builds and reads its own addresses with — not whatever root the + // caller holds: `service.openTab` passes the scope the caller had, which + // after #802 is usually the ACTIVE worktree, and an address built on + // that base neither dedupes against the chat's own address for the same + // file nor re-resolves the same way. See `src/client/address-base.ts`; + // the caller's cwd stays as the fallback for a session whose cwd the + // list does not know. + return fileAddressFor(sessionId, addressBaseOf(ctx, sessionId) ?? cwd, path) }, tabTypeOf(sessionId, tabId) { // Read through the SESSION, like `close` above: one native id names a diff --git a/src/client/sidebar-file.ts b/src/client/sidebar-file.ts index 7c82fcd5..fc95013b 100644 --- a/src/client/sidebar-file.ts +++ b/src/client/sidebar-file.ts @@ -24,6 +24,7 @@ * editor path verbatim for every other file. */ import type { Context } from '../context-types.ts' +import { addressBaseOf } from './address-base.ts' import { resolveSidebarPath } from './paths.ts' import { fileAddressFor } from './resource-address.ts' @@ -82,20 +83,23 @@ export function claimingNativeKind(ctx: Context, address: string): string | unde * Open one file through the native surface when a type other than this * plugin's editor claims it. * - * The address is built WITH the session cwd (the same spelling the host's - * conversation file links produce), so a claimed file opened here dedupes - * against the tab the chat path already opened for the same file. + * The address is built WITH the session's stored header cwd — the base the + * host builds and reads its own addresses with, see + * `src/client/address-base.ts` — so a claimed file opened here dedupes against + * the tab the chat path already opened for the same file, and the address + * resolves the same way wherever it is read. * * @param ctx - client context (`sidebarRightTabs` for the probe, * `sidebarRight` for the open). * @param sessionId - the session whose workspace the path resolves in. - * @param cwd - that session's workspace root, when known. + * @param cwd - that session's workspace root, when known; used only when the + * session list cannot answer for `sessionId`. * @param path - absolute or session-relative file path. * @returns true when the claiming type was handed the file; false leaves the * caller on its editor path (unclaimed file, no registry, or no surface). */ export function openClaimedNativeFile(ctx: Context, sessionId: string, cwd: string | undefined, path: string): boolean { - const address = fileAddressFor(sessionId, cwd, path) + const address = fileAddressFor(sessionId, addressBaseOf(ctx, sessionId) ?? cwd, path) if (claimingNativeKind(ctx, address) === undefined) return false let opener: NativeResourceOpener | undefined try { @@ -119,18 +123,34 @@ export function openClaimedNativeFile(ctx: Context, sessionId: string, cwd: stri * * Routes through the sidebar service so the editor descriptor's dedupeKey * (per-path) applies; the id is path-derived so multiple editors coexist. + * + * A RELATIVE path resolves against the caller's live workspace root when it + * has one (`options.cwd`, what every internal caller takes from + * `useSessionRoot`), and only falls back to the session list's stored cwd: the + * stored value is the session HEADER cwd, which the agent may have left for a + * linked worktree, and resolving an intended-relative path against it while + * the file tree, the editor's own path input and every route resolve against + * the worktree is exactly the "same relative path, two files, no error" + * divergence of #950. An ABSOLUTE path is unaffected by either base. + * * @param ctx - client context carrying `betterSidebar`. - * @param sessionId - the session whose cwd resolves a relative path. + * @param sessionId - the session whose workspace resolves a relative path. * @param path - absolute or session-relative file path. - * @param line - the 1-based line a file reference named (`a.c#L131`, #826). - * Omitted on an ordinary open. It rides the open as a transient navigation: - * the editor lands on it once (leaving preview, which renders no source - * lines) and the record forgets it afterwards. + * @param options - `line`: the 1-based line a file reference named + * (`a.c#L131`, #826), omitted on an ordinary open — it rides the open as a + * transient navigation, the editor lands on it once (leaving preview, which + * renders no source lines) and the record forgets it afterwards; `cwd`: the + * caller's live workspace root for a relative path. * @returns nothing. */ -export function openSidebarFile(ctx: Context, sessionId: string, path: string, line?: number): void { +export function openSidebarFile( + ctx: Context, + sessionId: string, + path: string, + options: { line?: number; cwd?: string } = {}, +): void { const summary = ctx.sessions.list.getSnapshot().byId[sessionId] - const absolute = resolveSidebarPath(summary?.cwd, path) + const absolute = resolveSidebarPath(options.cwd ?? summary?.cwd, path) // A type that explicitly claims this file owns it: hand the address to the // native surface so that type's registered tab body renders instead of this // plugin's editor (#695). Every other file falls through to the editor. @@ -142,6 +162,6 @@ export function openSidebarFile(ctx: Context, sessionId: string, path: string, l title, path: absolute, id: `editor:${absolute}`, - ...(line === undefined ? {} : { line }), + ...(options.line === undefined ? {} : { line: options.line }), }) } diff --git a/src/client/use-markdown-surface.ts b/src/client/use-markdown-surface.ts index 2af281f7..12cdcb21 100644 --- a/src/client/use-markdown-surface.ts +++ b/src/client/use-markdown-surface.ts @@ -114,7 +114,11 @@ export function useMarkdownSurface(opts: MarkdownSurfaceOptions): MarkdownSurfac rememberMarkdownAnchor(sessionId, resolveCwd(), target.path, target.fragment) } try { - openSidebarFile(ctx, sessionId, target.path, line) + // The live root rides along: a destination that resolved to a RELATIVE + // path (neither the document's directory nor a cwd was known) must land + // on the same workspace the surrounding tree and routes use, not on the + // session's frozen header cwd (#950). + openSidebarFile(ctx, sessionId, target.path, { line, cwd: resolveCwd() }) } catch (error) { // A failed open leaves the reader where they are (the link was claimed); // the parked fragment expires on its own. diff --git a/tests/file-open-claim.spec.ts b/tests/file-open-claim.spec.ts index 1281bbec..690f8dc7 100644 --- a/tests/file-open-claim.spec.ts +++ b/tests/file-open-claim.spec.ts @@ -119,7 +119,7 @@ describe('openSidebarFile', () => { // present only when the open came from `#L42` / `a.c:42`. const harness = makeCtx({ candidates: () => [{ kind: 'editor' }] }) - openSidebarFile(harness.ctx, 'session-1', 'out/notes.md', 42) + openSidebarFile(harness.ctx, 'session-1', 'out/notes.md', { line: 42 }) expect(harness.opened).toEqual([ { type: 'editor', title: 'notes.md', path: '/ws/out/notes.md', id: 'editor:/ws/out/notes.md', line: 42 }, diff --git a/tests/worktree-address.spec.ts b/tests/worktree-address.spec.ts new file mode 100644 index 00000000..f0c266a8 --- /dev/null +++ b/tests/worktree-address.spec.ts @@ -0,0 +1,209 @@ +/** + * The worktree family of path bugs: #947 (a chat link into a worktree doubled + * its path into an ENOENT) and #950 (the same relative path resolving to two + * different checkouts, silently). + * + * Both come from ONE rule the plugin broke: a session-scoped file ADDRESS + * (`dsh-resource://file/session//`) is built and read against the + * session's stored header cwd — the host does it that way on both ends — while + * the plugin's own filesystem routes follow the ACTIVE git worktree (#802). + * A relative path in an address, re-resolved by a worktree-rooted reader, + * therefore lands on `/` + * (ENOENT) or on the same-named file of another checkout (silent). + * + * The fix this spec pins: the address's base is the stored cwd, and the + * address's path becomes ABSOLUTE at the boundary where the address is read, + * so no worktree-rooted code downstream can re-base it. + */ +import { describe, expect, it } from 'vitest' +import { spawnSync } from 'node:child_process' +import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { addressBaseOf } from '../src/client/address-base.ts' +import { fileParamsOf } from '../src/client/native/index.ts' +import { createNativeSurface } from '../src/client/native/surface.ts' +import { resolveSidebarPath } from '../src/client/paths.ts' +import { fileAddressFor, parseFileAddress } from '../src/client/resource-address.ts' +import { openClaimedNativeFile, openSidebarFile } from '../src/client/sidebar-file.ts' +import type { Context } from '../src/context-types.ts' + +const IDENTITY = { + GIT_AUTHOR_NAME: 'worktree-address-test', + GIT_AUTHOR_EMAIL: 'test@dsh.invalid', + GIT_COMMITTER_NAME: 'worktree-address-test', + GIT_COMMITTER_EMAIL: 'test@dsh.invalid', +} + +function git(cwd: string, args: string[]): string { + const result = spawnSync('git', ['-c', 'core.hooksPath=', '-C', cwd, ...args], { + encoding: 'utf8', + env: { ...process.env, ...IDENTITY }, + }) + if (result.status !== 0) throw new Error(result.stderr || `git ${args.join(' ')} failed`) + return result.stdout +} + +/** One scratch checkout pair: the main workspace and a worktree INSIDE it. */ +interface Fixture { + /** The session's stored header cwd (the main checkout). */ + readonly repo: string + /** The linked worktree the agent actually works in, nested under `repo`. */ + readonly worktree: string + readonly cleanup: () => void +} + +/** + * `git worktree add /frontend/.worktrees/wt` — the layout #947 was + * reported against, and the one that makes an address's stripped prefix + * collide with the worktree root. + */ +function makeFixture(): Fixture { + const root = mkdtempSync(join(tmpdir(), 'dsh-worktree-address-')) + const repoRaw = join(root, 'repo') + const worktreeRaw = join(repoRaw, 'frontend', '.worktrees', 'wt') + mkdirSync(join(repoRaw, 'src'), { recursive: true }) + // A same-named file in both checkouts: the silent half of the bug (#950). + writeFileSync(join(repoRaw, 'src', 'a.ts'), 'main checkout\n') + git(repoRaw, ['init', '-q']) + git(repoRaw, ['checkout', '-q', '-b', 'main']) + git(repoRaw, ['add', '-A']) + git(repoRaw, ['commit', '-q', '-m', 'base']) + mkdirSync(join(repoRaw, 'frontend', '.worktrees'), { recursive: true }) + git(repoRaw, ['worktree', 'add', '-q', '-b', 'agent', worktreeRaw]) + writeFileSync(join(worktreeRaw, 'src', 'a.ts'), 'worktree checkout\n') + const repo = realpathSync.native(repoRaw) + const worktree = realpathSync.native(worktreeRaw) + return { repo, worktree, cleanup: () => rmSync(root, { recursive: true, force: true }) } +} + +interface Harness { + readonly ctx: Context + /** Seeds handed to `ctx.betterSidebar.openTab`. */ + readonly opened: Record[] + /** Addresses handed to `ctx.sidebarRight.openResource`. */ + readonly resources: string[] +} + +/** + * A client context with one session at `cwd` plus the optional native faces. + * @param cwd - the session list's stored header cwd. + * @param claiming - whether a type other than this plugin's editor claims files. + */ +function makeCtx(cwd: string, claiming = false): Harness { + const opened: Record[] = [] + const resources: string[] = [] + const byId = { s1: { cwd } } + const ctx = { + // `subscribe` is what `createNativeSurface` keeps for its session pulse. + sessions: { list: { getSnapshot: () => ({ byId }), subscribe: () => () => {} } }, + get: (name: string) => { + if (name === 'sidebarRightTabs') { + return claiming ? { candidates: () => [{ kind: 'drawio' }] } : { candidates: () => [{ kind: 'editor' }] } + } + if (name === 'sidebarRight') return { openResource: (address: string) => void resources.push(address) } + if (name === 'betterSidebar') return { openTab: (seed: Record) => void opened.push(seed) } + return undefined + }, + } + return { ctx: ctx as unknown as Context, opened, resources } +} + +/** + * The native tab record a file address renders as. Typed through the seed + * function's own parameter so this spec needs no un-exported host type. + */ +function infoOf(address: string): Parameters[0] { + return { + tab: { id: 'tab1', kind: 'editor', title: 'a.ts', contentId: address, navigation: { params: {} } }, + } as unknown as Parameters[0] +} + +describe('address base (worktree sessions)', () => { + it('addressBaseOf answers the stored session cwd, or nothing it does not know', () => { + const { ctx } = makeCtx('/repo') + expect(addressBaseOf(ctx, 's1')).toBe('/repo') + expect(addressBaseOf(ctx, 'unknown-session')).toBeUndefined() + expect(addressBaseOf(ctx, undefined)).toBeUndefined() + expect(addressBaseOf({} as never, 's1')).toBeUndefined() + }) + + it('seeds an absolute path for an address whose base is the header cwd (#947)', () => { + const fixture = makeFixture() + try { + const absolute = join(fixture.worktree, 'src', 'a.ts') + // Exactly what the host builds for a chat link that names the worktree + // file by its absolute path: the header cwd prefix is stripped and the + // address carries a path relative to THAT base. + const address = `dsh-resource://file/session/s1/frontend/.worktrees/wt/src/a.ts` + expect(fileAddressFor('s1', fixture.repo, absolute)).toBe(address) + expect(parseFileAddress(address)!.path).toBe('frontend/.worktrees/wt/src/a.ts') + + const seeded = fileParamsOf(infoOf(address), fixture.repo) + expect(seeded).toEqual({ path: absolute }) + const seededPath = seeded?.path as string + // The seed is absolute, so the tab body's worktree root cannot re-base + // it — this is the whole fix. + expect(resolveSidebarPath(fixture.worktree, seededPath)).toBe(absolute) + expect(existsSync(seededPath)).toBe(true) + // What the plugin used to do with the bare relative path: join it onto + // the worktree root again and miss. + expect(existsSync(join(fixture.worktree, 'frontend', '.worktrees', 'wt', 'src', 'a.ts'))).toBe(false) + } finally { + fixture.cleanup() + } + }) + + it('keeps the address-relative spelling when no base is known (no session context)', () => { + const address = 'dsh-resource://file/session/s1/frontend/.worktrees/wt/src/a.ts?x=1' + expect(fileParamsOf(infoOf(address))?.path).toBe('frontend/.worktrees/wt/src/a.ts') + // The `path:line` spec still splits off the resolved path (#826). + expect(fileParamsOf(infoOf('dsh-resource://file/session/s1/src/a.ts:42'), '/repo')) + .toEqual({ path: '/repo/src/a.ts', title: 'a.ts', line: 42 }) + }) + + it('builds every plugin address on the session base, never on the caller root', () => { + const fixture = makeFixture() + try { + const absolute = join(fixture.worktree, 'src', 'a.ts') + const expected = fileAddressFor('s1', fixture.repo, absolute) + const harness = makeCtx(fixture.repo, true) + + // `openSidebarFile` hands the claiming type the address … + openSidebarFile(harness.ctx, 's1', absolute, { cwd: fixture.worktree }) + expect(harness.resources).toEqual([expected]) + // … and the seed its body derives from that address is the real file. + expect(fileParamsOf(infoOf(harness.resources[0]!), fixture.repo)?.path).toBe(absolute) + + // A caller passing the worktree root (what `service.openTab` does after + // #802) must not move the base: the same file keeps ONE address. + expect(openClaimedNativeFile(harness.ctx, 's1', fixture.worktree, absolute)).toBe(true) + expect(harness.resources[1]).toBe(expected) + + // The surface's own address builder follows the same rule. + const surface = createNativeSurface(harness.ctx, {} as never) + expect(surface.fileAddress('s1', fixture.worktree, absolute)).toBe(expected) + expect(surface.fileAddress('s1', undefined, absolute)).toBe(expected) + } finally { + fixture.cleanup() + } + }) + + it('resolves a relative path against the live root, and the stored cwd only as a fallback (#950)', () => { + const fixture = makeFixture() + try { + // The tree, the routes and the editor's path input all use the live + // worktree root, so a relative open from a plugin surface must too. + const live = makeCtx(fixture.repo) + openSidebarFile(live.ctx, 's1', 'src/a.ts', { cwd: fixture.worktree }) + expect(live.opened[0]!.path).toBe(join(fixture.worktree, 'src', 'a.ts')) + + // Without a caller root the stored cwd remains the documented fallback. + const fallback = makeCtx(fixture.repo) + openSidebarFile(fallback.ctx, 's1', 'src/a.ts') + expect(fallback.opened[0]!.path).toBe(join(fixture.repo, 'src', 'a.ts')) + } finally { + fixture.cleanup() + } + }) +}) From f826e6365865b327841003f2241247a7ff9d2fb2 Mon Sep 17 00:00:00 2001 From: ymac <707337118@qq.com> Date: Wed, 14 Oct 2026 23:18:15 +0800 Subject: [PATCH 3/4] =?UTF-8?q?docs:=20=E5=9C=B0=E5=9D=80=E5=9F=BA?= =?UTF-8?q?=E5=87=86=E4=B8=8E=20worktree=20=E6=A0=B9=E9=80=89=E6=8B=A9?= =?UTF-8?q?=E7=9A=84=E8=A7=84=E5=88=99=E4=B8=8E=E8=AE=BE=E8=AE=A1=EF=BC=88?= =?UTF-8?q?#947=20/=20#950=20/=20#952=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - AGENTS §3.4 新增第 13 条:会话地址的基准是会话 header cwd,构造端与消费端都 经 addressBaseOf 取基准、在消费边界解析成绝对路径;工作区内部的 linked worktree 只有同一仓库(--git-common-dir 相等)才算「会话搬走了」。 - 接入指南 §10 新增同名条目(消费插件自己也解析文件地址时照同一条规则),并补上 openSidebarFile 的新签名 `{ line?, cwd? }`。 - 新增 docs/plans/2026-10-14-worktree-root-and-address-base.md:三个症状、根因 (宿主两端自洽 / 插件换基准 / 判定只看拓扑)、口径 A/B 决策表与实测真值表、 逐文件实施、复现与正式用例、残留(裸相对路径聊天链接属上游 worktree 无感)。 --- AGENTS.md | 1 + docs/external-plugin-guide.md | 3 +- ...26-10-14-worktree-root-and-address-base.md | 114 ++++++++++++++++++ 3 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 docs/plans/2026-10-14-worktree-root-and-address-base.md diff --git a/AGENTS.md b/AGENTS.md index e5cec8e4..bc89e1f4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,6 +102,7 @@ 10. **自定义种子必须带 fork 标记对(`meta.isSeeded: true` + `inheritedEventCount`),且 create 后必须 `inbox.clear()`、冷恢复必须按 id 精确清扫——标记对必要但不充分**:dsh-session 契约「只给 seed 不标 isSeeded,种子算重放历史而非继承前缀」——缺标记时 `Session.ownEvents()` 含整个种子,子会话的 inbox 折重放种子里的 `agent/inbox/spliced`,**继承父会话切割时刻未领取的 inbox 输入**。**但运行时 inbox 不走 `ownEvents()`**:`ReactLoopInbox.current()` → `ctx.sessionProjections.stateOf()` → `SessionProjectionRegistry.cellFor` 折的是 `snapshotEvents()` **全量日志(含继承种子前缀)**,且标准 inbox 投影的 `init` 忽略 `inheritedEventCount`、注册表 `session/created` 急切初始化跳过一切种子会话(seq ≠ 0)——种子里的 `agent/inbox/spliced` 会原样重放进子会话 live inbox。因此 sidechat 宿主 `agents.create` 成功后、任何 inject/followup 之前必须 `handle.agent.inbox.clear()`(durable 补偿 splice 是 own 事件,冷恢复折存储日志同样归零)。**幽灵的来源比「父会话排队」更宽(2026-10-12 真机复现确证)**:父会话 mid-turn 且工具有未返回调用时,种子被截断在 `turn/start` 之前,而 inbox 的「领取」splice 发生在 `turn/start` **之后** → **父会话本轮开头已领取的输入**在种子折叠里仍是 pending;`clear()` 是唯一能一次清干净的硬围栏(create 时本线程自己不可能有排队输入)。**冷恢复不能沿用 `clear()`**(会误杀「用户在线程里排队、宿主重启后尚未领取」的合法输入):改为 `dropInheritedGhosts` —— `inheritedPendingIds(log, inheritedEventCount)` 只折继承前缀得到幽灵 id 集合,再逐个 `agent.inbox.remove(id)`,精确且幂等(`src/sidechat-core.ts` 纯函数,`tests/sidechat-core.spec.ts` / `tests/sidechat-routes.spec.ts` 守护)。宿主 `session.fork`(api-session-controller)的调用即规范形态(注意:宿主自己的 `fork` **没有**这一步补偿,同窗口有同样的暴露面);回归由 `tests/sidechat-seed-validation.spec.ts`(真实 `Session.create` + 对 `ownEvents()` 跑 inbox 折 + **真实 `SessionProjectionRegistry`** 折全量日志钉住上游洞与 clear 补偿)守护。**模型选择同为 agent 作用域**:`sidechat.model` 必须同时落 `session.append('model/selection', …)`(宿主 `selectForNextRequest` 的同一形状)与 `installModelSelection(agent.ctx, ref)`(`@deepseek-ai/dsh-agent` 公开导出),否则控制器缓存的 per-agent selection 永不回读投影;resume 后也要按日志里的有效选择重装(`src/sidechat-routes.ts` 的 `ensureModelSelection`)。**0.2.0-rc.2 复查:`Session.create` 的五个参数与函数体逐字相同**;上游新增了 `buildForkSeed(events, boundary)` 导出,与本插件手工的 `buildSidechatInheritance` 职责重叠但**收益不明确**(插件还有 dangling-tool-call 退回结构化快照的自有需求),暂不替换。 11. **`dsh.plugin.json` 从来不是 DSH 契约**:0.1.7 全树 grep 仍 **0 命中**。DSH 真正读的是 `package.json` 的 `dsh.bundle.patch` + `dsh.client`(`platform`/`inject`/`immediately`/`external`)+ `exports["./client"]`。`dsh.plugin.json` 只服务第三方 registry(社区市场)通道,`lib/client-registry.js` 同理;`tests/manifest-consistency.spec.ts` 守护的是这条通道的形状,不是 DSH 契约。**`dsh.manifestVersion` 也仍是「只声明、零读」**(0.1.7 的 `package-manifest` README 自己写明「Current installers and loaders do not enforce `dsh.manifestVersion` or `engines.dsh`」)。0.1.7 的官方管控面新增:`plugin-manager` 的**多 registry 回退**(`registryPlan()`:配置源 → `fallbackRegistries`(默认含 `registry.npmmirror.com`),`network`/`timeout`/`not-found`/`no-matching-version` 会自动问下一个源;`registry` 入参只存在于 Web 对话框与 `plugin_manager` 工具,**CLI 没有 registry flag**)、`waitForInstall`、以及**插件展示元数据**:`package.json#icon`(36×36、纯填充无描边、**双色渐变**——与 DSH 自带的 `PluginArtwork*` 同风格:它们「carry their own brand colors instead of riding currentColor」,且每个都是多色,单色版在 30px 行内尺寸下会读成一块纯色板)+ `locale/.json` 的 `meta.title`/`description`。本插件**已采纳**(v0.21.1):`icon.svg` + `locale/en.json` + `locale/zh.json`,并由 `tests/plugin-meta.spec.ts` 守护「声明了就必须发布出去」。**rc.1 复查:`packages/boot/app-boot/src/package-meta.ts` 与 `scripts/verify-package-meta.ts` 在两个 tag 上逐字相同**(`ui-plugin-manager/src/client/presentation.ts` 只多了一段 `incompatible-version` 文案),所以上面三条硬规则与「**没有任何尺寸/渐变校验**」都仍然成立。三条硬规则:icon 必须是**包内相对路径**且写进 `files`;`locale/en.json` 是发现基线(缺它整个目录都不读);`exports` 必须暴露 `./locale/*.json` 与 `./package.json`。**所有失败都是静默的**——元数据有问题只会退化成一行纯文字,没有任何报错。`dsh.bundle.patch` 现在多了形状校验(非法值会 `throw`,引导期跳过该 bundle),本插件是合法的单字符串。 12. **peer 声明是启动期硬约束(rc.1 起;本版最容易静默失效的一处)**:`packages/boot/app-boot/src/plugin-compatibility.ts`(rc.1 **新文件**)只做一件事——遍历 profile 行的 `peerDependencies`,对**名字为 `@deepseek-ai/dsh` 或以 `@deepseek-ai/dsh-` 开头**的条目跑 `semver.satisfies(宿主版本, range, { includePrerelease: true })`,不满足就把整行 `row.disabled = true`(group 行连 `group` 一起关掉),只在 stderr 留一行 `disabling profile plugin