diff --git a/AGENTS.md b/AGENTS.md index 6495c88f..b8dba35b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # dsh-better-sidebar 仓库规则(AGENTS) -> 本文只含**每次都要遵守的规则**。深度参考不放在这里:接入 API → [docs/external-plugin-guide.md](docs/external-plugin-guide.md);宿主契约(原 §3.4 第 1–12 条)与历史线沿用至今的约束 → [docs/host-contracts.md](docs/host-contracts.md);逐特性设计史与历次 DSH 适配记录 → [docs/plans/](docs/plans/);用户可见变更 → [CHANGELOG.md](CHANGELOG.md)。 +> 本文只含**每次都要遵守的规则**。深度参考不放在这里:接入 API → [docs/external-plugin-guide.md](docs/external-plugin-guide.md);宿主契约(原 §3.4 第 1–13 条)与历史线沿用至今的约束 → [docs/host-contracts.md](docs/host-contracts.md);逐特性设计史与历次 DSH 适配记录 → [docs/plans/](docs/plans/);用户可见变更 → [CHANGELOG.md](CHANGELOG.md)。 --- @@ -48,7 +48,7 @@ - **沿用 alpha.5 的删除契约**:不再依赖 `@deepseek-ai/dsh-invariants`、`ctx.invariants` 或上游 `/invariant` 子路径,也不发布本插件的 invariant companion;HTTP/WS 准入统一调用 `ctx.connection.requestRejection(req)`,仅 `undefined` 放行,不恢复 `webRuntime` / 自建信任例外。 - **v0.28.0 正式版接管 npm `latest`**:宿主 npm `latest` 此时仍指向 `0.2.0-rc.2`,不满足本插件 RC 基线;用户已明确接受这一分离,所有安装文档必须显著提醒旧宿主固定 `v0.26.1`,不要用浮动 `latest`。发布 workflow 沿用现有版本号规则,无需改动。 - **本次 RC 适配不改功能实现**:alpha.5 → rc.1 上游完整树差异共 355 项,全部为 `package.json`,源码零变化;同步版本、peer、伴随依赖与文档,重新获取 RC 验证证据,不沿用 alpha 测试数字。 -- 动设置面 / sidechat / 原生 tab 之前,先读 [docs/host-contracts.md](docs/host-contracts.md)(原 §3.4 的 1–12 条按原编号都在那里)。 +- 动设置面 / sidechat / 原生 tab 之前,先读 [docs/host-contracts.md](docs/host-contracts.md)(原 §3.4 的 1–13 条按原编号都在那里)。 --- @@ -78,7 +78,7 @@ v0.28.0 正式版沿用现有发布规则进入 npm `latest`,无需修改 work ## 6. 去哪找什么 - **接入 API 全参考**:[docs/external-plugin-guide.md](docs/external-plugin-guide.md)(§0 承载面 / §4 Tab / §5 FileViewer / §7 服务 / §10 平台陷阱 / §12 皮肤契约 / §15 案例)。 -- **宿主契约与沿用至今的适配约束**:[docs/host-contracts.md](docs/host-contracts.md)(编号与旧 §3.4 第 1–12 条一致)。 +- **宿主契约与沿用至今的适配约束**:[docs/host-contracts.md](docs/host-contracts.md)(编号与旧 §3.4 第 1–13 条一致)。 - **设计史 / 历次版本适配**:[docs/plans/](docs/plans/);**用户可见变更**:[CHANGELOG.md](CHANGELOG.md)。 - **Issue / PR 分诊**:[.agents/skills/issue-triage/SKILL.md](.agents/skills/issue-triage/SKILL.md)(脚本在同目录 `scripts/`)。 - **测试**:契约写在每个 spec 的**头注释**里——改哪个子系统就跑对应 spec(注册表 `service` / `builtins` / `market-manifest`;原生承载面 `native-surface` / `native-registration`;文件树 `fs-tree-*` / `file-tree-*` / `fs-watch`;编辑器与文件路由 `file-stream-route` / `fs-read-page` / `text-encoding` / `fs-write-route`;Git `git-status-poll` / `git-scm` / `git-graph*`)。 diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index 67118708..1f03179e 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -475,7 +475,7 @@ ctx.effect(() => { | `terminal` | 宿主自带 `kind: 'terminal'`(`@deepseek-ai/dsh-client-ui-sidebar-terminal`) | 不要再注册同名 kind。插件侧 API(`api.ptyClose` / `agentPtyClose` / `agentSkipWait` / `terminalDeps` / `shellGet`)与 `SidebarTab.pin` / `SidebarState.nextTerminal` / `agentWaits` / `isAgentTabId` / `agentUuidOf` / `reconcileAgentTerminals` / `mirrorAgentWaits` / `setTabPin` 全部**已删除** | | `browser` | 宿主自带 `kind: 'browser'`(`@deepseek-ai/dsh-client-ui-sidebar-browser`),**但 DSH 0.1.7 起只在 desktop profile 挂载**(`web-app` 的 patch 里 `disabled: ctx.get('profileContext')?.name !== 'desktop'`)——Web profile 上**没有这个 kind**,`openTab('browser', …)` 必然失败 | 不要再注册同名 kind。要打开网页:desktop profile 走 `ctx.sidebarRight.openTab('browser', { params: { url } })`(务必 try/catch 兜底,宿主未装该包时 `openTab` 会抛);Web profile 只能自己提供页面,或把链接交回宿主(正文链接由宿主的 `linkOpening` 设置决定去向)。插件侧的 `api.browserProbe` / `SidebarPrefs.browserNoSandbox` / `browserAllowedLoopback` **以及三个「按协议分流」的外链接管偏好键全部已删除**;`urlTarget` 机制保留,但不再有接管总闸(见 §4.1) | -**同时删除的还有**:轮尾产物行接管。DSH 0.1.6 把 `conversation.chat.turnTail` 从 `chain` 改成 `list`(list 槽要求 `options.id`,且只能**追加**,不能替换宿主的产物行),插件因此整体移除了 `registerTurnTailInterception` 与 `selectProducedFiles`。要往那个位置加东西,按 list 契约注册 `{ name: 'conversation.chat.turnTail', id: '<你的 id>', order }`;`openSidebarFile` 作为通用打开工具留在 `dsh-better-sidebar/src/client/sidebar-file.ts`(`resolveSidebarPath` 移到 `src/client/paths.ts`)。 +**同时删除的还有**:轮尾产物行接管。DSH 0.1.6 把 `conversation.chat.turnTail` 从 `chain` 改成 `list`(list 槽要求 `options.id`,且只能**追加**,不能替换宿主的产物行),插件因此整体移除了 `registerTurnTailInterception` 与 `selectProducedFiles`。要往那个位置加东西,按 list 契约注册 `{ name: 'conversation.chat.turnTail', id: '<你的 id>', order }`;`openSidebarFile(ctx, sessionId, path, { line?, cwd? })` 作为通用打开工具留在 `dsh-better-sidebar/src/client/sidebar-file.ts`(`resolveSidebarPath` 移到 `src/client/paths.ts`)——`cwd` 是调用方手上的**活**工作区根(`useSessionRoot`),只在 `path` 为相对路径时生效,缺省回退到会话列表里的 header cwd。 --- @@ -1129,6 +1129,7 @@ interface SettingsDescriptor { | **第三语言覆盖(ja 等)** | 可选 peer `@huanlin/dsh-plugin-better-locale`(optional)提供 ja/ko 覆盖,**借用 DSH 英文槽位**(仅 DSH=en 时生效,zh 下惰性)。经 `ctx.get('betterLocale')` 注入 `t()`;未安装整段 no-op | | **懒加载 chunk** | 重依赖(CodeMirror / mermaid / 19 份第三语言词典)在独立 bundle(`lib/client-.js`,现存 `editor` / `mermaid` / `locale` 三个),经 `/sidebar/bundle` 按需下发;factory 赋到 `globalThis.__dshChunks__[]`,由 `src/client/chunk-loader.ts` 物化,**不经** `__ModuleLoader__`。对消费插件透明 | | **聊天文件打开漏斗(0.1.5 宿主)** | 聊天里一切文件打开(工具行 / 产物行 / 正文提及 / 行内代码路径)统一走 DSH 原生右侧栏的 `ctx.sidebarRight.openResource(fileAddressFor(sessionId, cwd, path))`(`packages/client/ui-chat/src/client/apply.ts` 是唯一调用点);`remote.session.openWorkspacePath` 在 0.1.5 客户端**已无调用者**,better-sidebar 的 openpath 拦截随之删除。你的插件若要观测/旁路聊天文件打开,注册原生 tab 类型认领 `dsh-resource://file/**`(见 [AGENTS.md §3](AGENTS.md) 第 10 条);不要假设 `ctx.workspaces.openPath`(已删除)或旧 `remote.session` 漏斗存在 | +| **会话地址的基准是会话 header cwd(#947 / #950 的根因)** | `dsh-resource://file/session//` 里的路径总是相对**会话存储的 header cwd**:宿主构造端(`ui-chat` 的 `openFile` → `fileAddressFor(sessionId, sessions.list.byId[sid].cwd, path)`)与解析端(`api-workspace-files` 的 `resolve()` → `sessions.get(sid).header.cwd`)用的就是同一个值。本插件的 fs 路由自 #802 起跟随**活动 worktree 根**,两者在「会话 header cwd 是主检出、agent 在 linked worktree 里干活」时不同,于是地址里的相对路径被活动根**再拼一次**:路径翻倍 → ENOENT(#947),或在两个检出都存在同名文件时**静默**读到另一份(#950,可保存写回)。所以**构造端**(`native/surface.ts` 的 `fileAddress`、`sidebar-file.ts` 的 `openClaimedNativeFile`)与**消费端**(`native/index.ts` 的 `fileParamsOf(info, base)`)都经 `src/client/address-base.ts` 的 `addressBaseOf(ctx, sessionId)` 取基准,并在边界处把地址路径解析成**绝对路径**(绝对路径在任何基准下都一样,下游再无可重定基的余地);只有用户/插件**意图**的相对路径(文件树、编辑器路径输入框、文档内相对链接)才走活根(`useSessionRoot`)。你的插件若自己解析文件地址,请照同一条规则做 | | **原生 tab 体的高度契约** | 你的 tab 组件被挂在**全高列 flex 宿主**里:native 适配层给每个 tab 体(含 orphaned 回退)包一层 `height:100%` 的 `sidebar.module.css` `.nativeTabHost`(带 `data-dsh-native-tab-host`)——根用 `flex: 1` / `height: 100%` 并加 `min-height: 0` 填满面板。宿主的面板体 `.paneBody`(`dsh-client-ui-dockkit`)是**有确定高度的块级滚动容器,不是 flex 容器**,因此只靠外层 flex 容器支撑的根会塌成内容高度(sidechat 的输入框就贴不到面板底);DSH 自己的 tab 体(`ui-sidebar-documentpreview` 的文档预览、`ui-sidebar-files` 的 FilesBody)正是因此在根上声明 `height: 100%` | --- diff --git a/docs/host-contracts.md b/docs/host-contracts.md index 9c46a630..ac508526 100644 --- a/docs/host-contracts.md +++ b/docs/host-contracts.md @@ -1,6 +1,6 @@ # 宿主契约与沿用至今的适配约束 -> 从 `AGENTS.md` §3 移出的深度参考(原 §3.4 第 1–12 条与 0.1.5–0.1.7 历史线中仍然生效的部分)。 +> 从 `AGENTS.md` §3 移出的深度参考(原 §3.4 第 1–13 条与 0.1.5–0.1.7 历史线中仍然生效的部分)。 > **编号保持不变**:代码、测试与文档里写的「AGENTS.md §3.4 第 N 条」就是本文第 N 条。 > 历史版本已不在支持线内(当前基线 DSH 0.2.1-rc.1,见 [AGENTS.md](../AGENTS.md) §3);逐条适配过程见 [docs/plans/](plans/) 与 [CHANGELOG.md](../CHANGELOG.md)。 @@ -25,7 +25,7 @@ - **会话当前执行目录**:文件 / Git / 终端及新建 sidechat 跟随 `working_directory`,不把 session header cwd 当成当前值。live 读 `ctx.workingDirectory.get(session)`;cold 经 `ctx.sessionQuery.observeSession(..., { projectionMode: 'all' })` 读取,lease 在 `finally` 中释放。同一 base 的 live 目录增量通过 epoch 失效缓存;cold 外进程同 base 变化仍沿用既有 15 s TTL。linked worktree 选择仍按 base 目录记账,不把选中的 worktree 反写为 base。sidechat 继承 seed 尾部盖章当前 cwd,避免旧 seed 的目录事件覆盖新线程的初始目录。 - **终端 label**:alpha.5 的 `TerminalBlockLabels` 新增必填 `commandLine(line)`,两个消费者都要提供,21 份词典同步对应 key。 -## B. 宿主契约(原 AGENTS.md §3.4 第 1–12 条) +## B. 宿主契约(原 AGENTS.md §3.4 第 1–13 条) 1. **一次性 token 鉴权**:就绪行 `dsh web: http://127.0.0.1:/?token=<43字符>`(导航换签名 cookie,干净 URL 401)。`e2e-mount.sh` 的 URL grep 必须延伸到空白(`[^ ]*`,否则在 `/` 截断丢 token);e2e 统一走 `tests/e2e/host.ts`(`parseLaunchUrl` 对裸 origin 直接抛错),带 stamps 导航走 `gotoPage()`(先 addCookies 再直达——token 换 cookie 的 303 会丢弃同 URL 其它 query 参数)。插件 `/sidebar/*` 路由不受影响,同源 fetch 照旧。 2. **Remote gateway 斜杠 RPC(唯一方言)**:`POST /api/workspace/create`,payload 恰为 `{args: {...}}`,**args 按控制器 TS 参数名包装**(`workspace/create`、`session/create` → `{args:{request:{...}}}`;`session/list` 的参数名 `_request` **不可省略**——`{}` 也被拒 `args fields do not match the descriptor`);envelope `method` 与路径一致,点分路径 404。构造由 `tests/e2e/host-protocol.ts` 的 `rpcAttempt` 提供、`tests/e2e-host-protocol.spec.ts` 锁定。 @@ -45,3 +45,4 @@ 11. **`dsh.plugin.json` 从来不是 DSH 契约**(全树 grep 0 命中):DSH 真正读的是 `package.json` 的 `dsh.bundle.patch` + `dsh.client`(`platform`/`inject`/`immediately`/`external`)+ `exports["./client"]`。`dsh.plugin.json` 与 `lib/client-registry.js` 只服务第三方 registry(社区市场)通道,`tests/manifest-consistency.spec.ts` 守护的是这条通道的形状,不是 DSH 契约。**不要混淆两个 manifest 的 `engines.dsh`**:当前宿主的兼容性检查优先读取 `package.json#engines.dsh`,存在时由它独立裁决;本插件未声明此字段,仍由 13 条 DSH peer 决定兼容性。`dsh.plugin.json#engines.dsh` 只是第三方 registry 元数据,不能替代 package 字段;`dsh.manifestVersion` 也不是版本兼容性开关。`dsh.bundle.patch` 有形状校验(非法值会 `throw`,引导期跳过该 bundle),本插件是合法的单字符串。 **插件展示元数据**(Plugins 页与 `plugin_manager` 列表,v0.21.1 起已采纳)三条硬规则:`package.json#icon` 必须是**包内相对路径**且写进 `files`(36×36、纯填充无描边、**双色渐变**——与 DSH 自带 `PluginArtwork*` 同风格,单色版在 30px 行内尺寸下会读成一块纯色板);`locale/en.json` 是发现基线(缺它整个目录都不读,`meta.title` / `description` 在这里);`exports` 必须暴露 `./locale/*.json` 与 `./package.json`。**所有失败都是静默的**——元数据有问题只会退化成一行纯文字,没有任何报错;`tests/plugin-meta.spec.ts` 守护「声明了就必须发布出去」。plugin-manager 侧另有**多 registry 回退**(配置源 → `fallbackRegistries`,默认含 `registry.npmmirror.com`;`network`/`timeout`/`not-found`/`no-matching-version` 会自动问下一个源;`registry` 入参只存在于 Web 对话框与 `plugin_manager` 工具,**CLI 没有 registry flag**)。 12. **宿主版本兼容性是启动期硬约束**:当前宿主先读插件 `package.json#engines.dsh`;字段存在时只按该范围判定,DSH peer 不再拓宽或收窄结果。字段缺席时回退检查名字为 `@deepseek-ai/dsh` 或以 `@deepseek-ai/dsh-` 开头的 peer,按 `semver.satisfies(宿主版本, range, { includePrerelease: true })` 判定。本插件刻意不新增该字段,仍由 13 条 DSH peer 的 `^0.2.1-rc.1` 支持线约束,optional peer 没有豁免。`engines` 非对象或 `engines.dsh` 非字符串会导致兼容性清单不可读并拒绝加载;`workspace:` 仅在 peer 中有效。安装与 profile 启动拒绝可能禁用整行,需读 `disabling profile plugin` 日志;拒绝记录字段已由 `peers` 改为 `requirements`,其中 key 为 `engines.dsh` 或回退检查的 peer 包名。`pnpm peers check` 校验的是 dev 依赖树,不能证明宿主启动预检通过。[官方升级指南](https://github.com/deepseek-ai/deepseek-harness/blob/dsh-v0.2.1-alpha.5/docs/upgrade-guide/v0.2.1-alpha.3/plugin-engines-dsh/guide.md)。 +13. **会话地址的基准是会话 header cwd,相对路径不得中途换基准(#947 / #950;同族 #952)**:`dsh-resource://file/session//` 的相对路径,宿主构造端(`ui-chat` 的 `fileAddressFor(sessionId, sessions.list.byId[sid].cwd, path)`)与解析端(`api-workspace-files` → `sessions.get(sid).header.cwd`)都取会话存储的 header cwd;插件自 #802 起让 fs 路由跟随**活动 worktree 根**,两者在「会话 header cwd 是主检出、agent 在 linked worktree 里干活」时不同 → 地址路径被活动根**再拼一次**:翻倍 ENOENT(#947),或静默读到另一检出的同名文件(#950,可保存写回、更危险)。规则:**构造端**(`native/surface.ts` 的 `fileAddress`、`sidebar-file.ts` 的 `openClaimedNativeFile`)与**消费端**(`fileParamsOf(info, base)`)都经 `src/client/address-base.ts` 的 `addressBaseOf(ctx, sessionId)` 取基准,并在消费边界把地址路径解析成**绝对路径**(绝对路径在任何基准下都一样);只有用户/插件**意图**的相对路径(文件树、路径输入框、文档内链接、`openSidebarFile` 的 `options.cwd`)才走活动根(`useSessionRoot`)。同族第二处是**采纳判定**:工作区**内部**的 linked worktree 只有属于**同一仓库**(`--git-common-dir` 相等)才算「会话搬走了」,嵌套仓库(含 bare 仓库的 main/local 检出)的 worktree 不再抢根(#952)。判定与基准都按**新增可选入参**向前兼容:`activeWorktreeRootOf` 多一个 `ignorePin` 选项(给「显式根」的读取路径用,见 `src/session-root.ts`),既有调用方零改动。回归 `tests/worktree-address.spec.ts` / `tests/active-worktree.spec.ts`;设计与实测见 [docs/plans/2026-10-14-worktree-root-and-address-base.md](plans/2026-10-14-worktree-root-and-address-base.md)。 diff --git a/docs/plans/2026-10-14-worktree-root-and-address-base.md b/docs/plans/2026-10-14-worktree-root-and-address-base.md new file mode 100644 index 00000000..50e76ed3 --- /dev/null +++ b/docs/plans/2026-10-14-worktree-root-and-address-base.md @@ -0,0 +1,114 @@ +# worktree 根选择与地址基准(#947 / #950 / #952) + +> 一次修掉三条同源 issue:都在「会话 header cwd 是主检出、agent 在 linked git worktree 里干活」时出现, +> 由同一段代码的两个方向造成——**根选择判定过宽**(#952),以及**地址基准与读取基准不一致**(#947 / #950)。 +> 分支 `fix/worktree-root-address-base`,两条 commit:判定(#952)、基准(#947 #950)。 + +## 1. 三个症状 + +| # | 触发 | 症状 | 失败模式 | +|---|---|---|---| +| #947 | 聊天链接/改动页打开 worktree 内文件 | 路径被二次拼接 → `cannot read "…/wt/frontend/.worktrees/wt/CLAUDE.md": ENOENT` | 响亮 | +| #950 | 同一相对路径经不同入口 | 两个检出的同名文件,两次都成功、无提示 | **静默**,且可保存写回 | +| #952 | 工作区**内部**嵌套仓库的 linked worktree | explorer 被静默重定根到那个子目录,兄弟目录全消失(报告者离线重放 27 个真实会话,20 个中招) | **静默** | + +三者的共同前提:`git worktree add /frontend/.worktrees/wt` 这类**工作区内部**的 linked worktree 是常态(DSH 自己的约定就是 `.worktrees/`),而容器工作区里还有「bare 仓库 + 它的 main/local 检出」这种普通内容。 + +## 2. 根因 + +**2.1 地址的基准是会话 header cwd,宿主两端一致。** 宿主构造端 `ui-chat` 的 `openFile` 用 +`fileAddressFor(sessionId, ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd, path)`,解析端 `api-workspace-files` 的 +`resolve()` 用 `sessions.get(sessionId).header.cwd`——同一个值,所以宿主自洽。地址里的相对路径**只在那个基准下成立**。 + +**2.2 插件读的一端换成了活动 worktree 根。** #802 让插件的 fs 路由(`activeWorktreeRootOf`)与原生 tab 体 +(`useSessionRoot`)跟随活动 worktree,于是同一会话有两个基准。地址里 header 相对的拼写(`frontend/.worktrees/wt/a.md`) +被活动根**再拼一次**: + +``` +/repo ← header cwd(宿主构造地址用) +/repo/frontend/.worktrees/wt ← 活动根(插件读文件用) +地址 path: frontend/.worktrees/wt/a.md ← 被 header cwd 剥过前缀 +插件解析: /repo/frontend/.worktrees/wt/frontend/.worktrees/wt/a.md → ENOENT +``` + +只在「worktree 嵌在 header cwd 之下」时翻倍;**工作区外**的 worktree 其地址保留绝对路径,所以不翻倍——这正是 #802 的跨仓库场景没暴露问题的原因。 + +**2.3 同一插件里还有第三、第四个基准。** `openSidebarFile` 用冻结的 `summary?.cwd`(header), +`service.openTab` → `surface.fileAddress` 用调用方手上的 `scope?.cwd`(多数是活动根);于是同一个文件可能拿到**两个地址** +(页签不合并),同一相对路径在不同入口落到不同检出。**相对路径不携带基准信息,跨边界时必须还原成绝对路径。** + +**2.4 根选择判定只看拓扑。** `activeRootFromEvents` 判据是「`top ≠ base` 且 `--absolute-git-dir ≠ --git-common-dir`(linked worktree)」, +不区分「会话搬到别的检出」与「工作区里本来就有另一个仓库的 worktree」。裸仓库的 `main`/`local`、容器工作区里的子项目 worktree +都会被采纳,explorer 随即被重定根到一个子目录。 + +## 3. 口径决策(A / B) + +| 口径 | 含义 | #952 | #947/#950 | #802(工作区内 `.worktrees/` 跟随) | +|---|---|---|---|---| +| A | 工作区内的 linked worktree 一律不采纳 | 修好 | **顺带消失**(in-workspace 两基准合一) | **失效** | +| **B(采纳)** | 工作区**外** 或与 base **同一 `--git-common-dir`** 才采纳 | 修好 | 仍需修基准 | 保留 | + +选 B:`.worktrees/` 是 DSH 自己的约定,#947 报告者的三个建议修法里有两个假设它继续跟随; +而「嵌套仓库的 worktree」是工作区普通内容,不该抢根。判据用 `--git-common-dir` 相等 —— 同一个仓库的所有检出共享它, +submodule(`gitDir == commonDir`)本来就被排除,与插件既有判据同源。 + +**实测真值表**(`tests/active-worktree.spec.ts`,真 `git worktree`): + +| 布局 | 现状(修前) | 口径 A | 口径 B(本实现) | +|---|---|---|---| +| `W/nested/wt`(嵌套仓库的 worktree) | 抢根 ❌ | 不抢 ✅ | 不抢 ✅ | +| `W/paper_downloader/main`(嵌套 bare 仓库的检出) | 抢根 ❌ | 不抢 ✅ | 不抢 ✅ | +| `/frontend/.worktrees/wt`(同仓库、工作区内) | 跟随 | **不跟随** ⚠️ | 跟随 ✅ | +| `/outside-wt`(工作区外) | 跟随 ✅ | 跟随 ✅ | 跟随 ✅ | +| 跨仓库、工作区外(#802 的原始场景) | 跟随 ✅ | 跟随 ✅ | 跟随 ✅ | + +## 4. 实施 + +### 4.1 判定(commit 1,`src/active-worktree.ts`) + +- 新增 `gitIdentityOf(dir)`:`git rev-parse --absolute-git-dir --git-common-dir` → `{ gitDir, commonDir }`,进程级缓存; + common dir 的相对拼写(主检出返回 `.git`)按**被探测目录**归一化。 +- `isLinkedWorktree` 改走该身份(`gitDir ≠ commonDir`),`isAdoptableTop(top, base)` 在其上加仓库身份比较: + 工作区外一律采纳;工作区内只有 `commonDir` 与 base 相等才采纳;`pathKeyOf(base) === ''`(文件系统根)时跳过该判定, + 免得整条跟随功能被关掉。 +- `activeRootFromEvents` 的候选取舍从 `isLinkedWorktree` 换成 `isAdoptableTop`。 + +### 4.2 基准(commit 2) + +- 新增 `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)))`。 + 下游(viewer 的 `fs.read`、编辑器、目录 watch)只见绝对路径,活动根再无法重定基。 +- **构造边界**:`native/surface.ts` 的 `fileAddress` 与 `sidebar-file.ts` 的 `openClaimedNativeFile` 都用 `addressBaseOf` 优先, + 调用方给的 cwd 只作为回退 —— 同一文件因此只有一个地址(与宿主聊天路径的地址一致,页签照旧合并)。 +- **意图侧**:`openSidebarFile(ctx, sessionId, path, { line?, cwd? })` 的 `cwd` 是调用方的**活**根 + (`EditorHost` / 改动页 / markdown 面板都传 `useSessionRoot` 的结果),相对路径按它解析,缺省才回退 header cwd。 + 文件树、编辑器路径输入框本来就走活根,改后各处一致(#950)。 + +## 5. 实测与回归 + +复现(真 `git worktree` + 真函数,修前全绿复现、修后钉住): + +- `.scratch/repro-947.spec.ts`:宿主地址构造 → 插件解析 → 路由/原生 tab 体;含真实 `/sidebar/api/fs.read` 的 + `ENOENT … .worktrees/947-click-demo/.worktrees/947-click-demo/IN-WORKTREE.md`。 +- `.scratch/repro-952.spec.ts`:三种布局 × 三种口径的真值表。 +- 真机点击验证(本机 3080 + 真 worktree 会话):绝对路径链接 → 翻倍 ENOENT;相对链接 → 打到 worktree 根; + `[README.md](README.md)` → 静默打开 worktree 的副本(首行标记可辨);文件树里的同名文件正常打开。 + +正式用例: + +- `tests/active-worktree.spec.ts`:新增 4 例(嵌套普通仓库不采纳、嵌套 bare 仓库不采纳、同仓库工作区内仍采纳、工作区外仍采纳), + 既有 3 例(跨仓库采纳、无证据保持 cwd、真实路径探测)逐字未改。 +- `tests/worktree-address.spec.ts`(新):`addressBaseOf` 的三态;地址路径解析成绝对路径后任何基都不能重定基; + 地址构造/`surface.fileAddress` 一律用会话基准;相对路径按活根解析、缺省回退 header cwd。 +- `tests/file-open-claim.spec.ts`:`openSidebarFile` 的 `line` 从位置参数改为 `{ line }`(唯一签名变更点)。 + +## 6. 残留与后续 + +- **裸相对路径的聊天链接**:worktree 会话里一条 `[x](docs/README.md)` 由宿主按 header cwd 构造并解析 → 打主检出的同名文件。 + 宿主两端一致,插件无法在不猜的前提下区分「agent 指的是 worktree」。本版不做启发式(绝对路径修复后不再有 ENOENT 与 + 静默重定基),若要可见性,后续可在页签标题/提示里显示解析后的绝对路径;根因属上游 worktree 无感的聊天漏斗。 +- **`DSH_SIDEBAR_WORKTREE_ROOT`** 仍是全局硬覆盖(应急用),不受本次改动影响。 +- 工作区是文件系统根、或 base 不在任何仓库里的会话:工作区内的候选一律不采纳(与 B 的「同一仓库才算搬家」一致), + 工作区外的照旧采纳。 diff --git a/src/active-worktree.ts b/src/active-worktree.ts index d8b3670c..94e65cc8 100644 --- a/src/active-worktree.ts +++ b/src/active-worktree.ts @@ -14,7 +14,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, but only evidence after the last committed * working-directory/change is eligible. When there is no evidence the cwd is * kept (lifted to the repository top level for subdirectory sessions). @@ -51,7 +57,7 @@ const ACTIVE_ROOT_MAX_EVENTS = 4_000 const ACTIVE_ROOT_MAX_PROBES = 24 /** Bounds of the three process-wide caches below (LRU, oldest evicted first). */ const PATH_TOP_CACHE_MAX = 512 -const LINKED_WORKTREE_CACHE_MAX = 512 +const GIT_IDENTITY_CACHE_MAX = 512 const ACTIVE_ROOT_CACHE_MAX = 256 /** Explicit override, mainly for tests and manual pinning. */ const ACTIVE_ROOT_OVERRIDE_ENV = 'DSH_SIDEBAR_WORKTREE_ROOT' @@ -83,11 +89,13 @@ const ACTIVE_ROOT_PATH_PATTERN = /[A-Za-z]:(?:\\|\/)[^\\/\s"'\x60,;|)<>*?]+(?:[\ * sidebar that keeps asking about every session it has ever shown) would * otherwise grow them forever. `pathTopCache` caches negative answers too * (`undefined` = "no git top level here"), which is what keeps a non-repo - * session cheap; those entries are evictable like any other. + * session cheap; `gitIdentityCache` does the same for "not in a repository", + * and `activeWorktreeRootCache` the same for a session with no evidence — + * those entries are evictable like any other. */ const activeWorktreeRootCache = new Map() const pathTopCache = new Map() -const linkedWorktreeCache = new Map() +const gitIdentityCache = new Map() /** * In-flight de-duplication, mirroring `git.ts`'s `repoRootsInFlight`. @@ -283,34 +291,104 @@ 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) { - cachePut(linkedWorktreeCache, key, cached, LINKED_WORKTREE_CACHE_MAX) +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)) { + const cached = gitIdentityCache.get(key) + // A cached `undefined` ("not in a repository") is a real answer that keeps + // a subdirectory session from re-probing the same directory, so a hit is + // re-inserted like any other — which also refreshes its LRU recency. + cachePut(gitIdentityCache, key, cached, GIT_IDENTITY_CACHE_MAX) return cached } - let linked = false + 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 } - // `false` is a real answer ("the main checkout", "a submodule", "not a - // repo") and is cached: the negative is what keeps a subdirectory session - // from re-probing the same top level on every scan. - cachePut(linkedWorktreeCache, key, linked, LINKED_WORKTREE_CACHE_MAX) - return linked + cachePut(gitIdentityCache, key, identity, GIT_IDENTITY_CACHE_MAX) + 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. + * + * Both questions are answered from ONE {@link gitIdentityOf} probe: the same + * identity also names 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. */ @@ -337,7 +415,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/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..e88d2c0b --- /dev/null +++ b/src/client/address-base.ts @@ -0,0 +1,67 @@ +/** + * 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' +import { resolveSidebarPath } from './paths.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 + } +} + +/** + * Resolve an address's path against its base, spelled the way the base is. + * + * The address grammar is `/`-separated on every platform, so joining one onto + * a Windows base with `resolveSidebarPath` alone leaves a MIXED spelling: + * `C:\repo` + `src/a.ts` → `C:\repo\src/a.ts`, while the file tree, the git + * panel and every `join`-based producer spell the same file + * `C:\repo\src\a.ts`. Two spellings of one file is two tab identities (the + * editor's `dedupeKey`/id is path-derived) and two answers to "is it the same + * path", so the address boundary folds the separators to the base's style. + * POSIX keeps the path verbatim: there `\` is a legal file-name character, not + * a separator (the same reason `resolveSidebarPath` never folds on POSIX). + * + * @param base - the workspace root whose separator style decides the answer. + * @param path - an address path (relative to `base`) or an absolute path. + * @returns the resolved path in `base`'s separator style. + */ +export function resolveAddressPath(base: string | undefined, path: string): string { + const resolved = resolveSidebarPath(base, path) + return base !== undefined && base.includes('\\') ? resolved.replace(/[/\\]+/g, '\\') : resolved +} diff --git a/src/client/builtins/tabs.tsx b/src/client/builtins/tabs.tsx index 4472dc32..7d15786d 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 5c2ad291..20943697 100644 --- a/src/client/native/index.ts +++ b/src/client/native/index.ts @@ -23,6 +23,7 @@ * absent from the native guide and `openTab` refuses it. */ import type { Context } from '../../context-types.ts' +import { addressBaseOf, resolveAddressPath } from '../address-base.ts' import { t } from '../locales.ts' import { splitTrailingLineSpec } from '../path-line.ts' import { baseName } from '../paths.ts' @@ -179,14 +180,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 : resolveAddressPath(base, address.path) + const spec = splitTrailingLineSpec(path) + if (spec === undefined) return { path } return { path: spec.path, title: baseName(spec.path), line: spec.line } } @@ -394,7 +410,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..b8149e8c 100644 --- a/src/client/sidebar-file.ts +++ b/src/client/sidebar-file.ts @@ -24,7 +24,7 @@ * editor path verbatim for every other file. */ import type { Context } from '../context-types.ts' -import { resolveSidebarPath } from './paths.ts' +import { addressBaseOf, resolveAddressPath } from './address-base.ts' import { fileAddressFor } from './resource-address.ts' /** The kind this plugin's own file editor registers its tab type under. */ @@ -82,20 +82,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 +122,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 = resolveAddressPath(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 +161,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/active-worktree.spec.ts b/tests/active-worktree.spec.ts index de27c986..97ad289b 100644 --- a/tests/active-worktree.spec.ts +++ b/tests/active-worktree.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { spawnSync } from 'node:child_process' -import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { activeWorktreeRootOf } from '../src/active-worktree.ts' @@ -414,4 +414,75 @@ describe('active worktree root', () => { removeTree(root) } }) + + 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 }) + } + }) }) 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..90501da3 --- /dev/null +++ b/tests/worktree-address.spec.ts @@ -0,0 +1,227 @@ +/** + * 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, resolveAddressPath } 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('spells the resolved path in the base separator style (one spelling per file)', () => { + // The address grammar is `/`-separated on EVERY platform, so joining it + // onto a Windows base must not leave `C:\repo\src/a.ts`: the file tree and + // every `join`-based producer spell the same file `C:\repo\src\a.ts`, and + // two spellings of one file are two tab identities (the editor's id and + // dedupeKey are path-derived). CI caught exactly this on the Windows lane. + expect(fileParamsOf(infoOf('dsh-resource://file/session/s1/src/a.ts'), 'C:\\repo')) + .toEqual({ path: 'C:\\repo\\src\\a.ts' }) + expect(fileParamsOf(infoOf('dsh-resource://file/session/s1/src/a.ts'), '/repo')) + .toEqual({ path: '/repo/src/a.ts' }) + // Relative intent resolves through the same rule; POSIX keeps the path + // verbatim, because there `\` is a legal file-name character, not a + // separator (`resolveSidebarPath` never folds on POSIX either). + expect(resolveAddressPath('C:\\repo', 'src\\a.ts')).toBe('C:\\repo\\src\\a.ts') + expect(resolveAddressPath('/repo', 'src/a.ts')).toBe('/repo/src/a.ts') + expect(resolveAddressPath('/repo', 'a\\b.ts')).toBe('/repo/a\\b.ts') + }) + + 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() + } + }) +})