merge review/path-roots: #1079 UNC prefix, #1070 subdirectory session root

This commit is contained in:
Menghuan1918 committed 2026-10-29 23:42:13 +08:00
commit ac8fcd5516
6 files changed
+119 -10

No files matched your search

+7
View File
@@ -2,6 +2,13 @@
> 本文档收录 dsh-better-sidebar 的完整发布历史(最新版摘要见 [README](README_ZH.md);同步发布于 [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases))。
### Unreleased
- 🪟 **Windows + WSL 工作区:UNC 路径不再被折叠成盘符相对路径**:`resolveAddressPath` 在 Windows 基址下重排分隔符时把每段连续 `\` 折成一个,`\\wsl.localhost\<distro>\...` 的 UNC 前缀也因此被折成 `\wsl.localhost\...`;宿主随后用 `path.resolve()` 把它锚定到自己的当前盘(`C:\wsl.localhost\...`),侧边栏打开 WSL 工作区里任何文件都报 `ENOENT`。现在 UNC 前缀原样保留、只折叠其后的部分(盘符路径行为不变)。
- 🧪 测试:`tests/worktree-address.spec.ts` 新增 1 例(UNC 绝对路径、工作区相对路径、正斜杠写法都保持双前导分隔符)。
- 🗂 **会话 cwd 是 Git 仓库子目录时不再被上抬到仓库顶层**([#1024](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1024) / [#1080](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1080);贡献者 PR [#1070](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1070) @hy5424):侧边栏根此前被替换成 `git rev-parse --show-toplevel`,聊天里的相对路径文件链接因此解析成 `<repo>/<file>` 而不是 `<repo>/<subdir>/<file>`(ENOENT),文件搜索也搜错根。现在会话 cwd 本身即根,只有会话自己的工具调用证据指向 linked worktree 时才替换;基址先按真实路径规范化,`/var` 与 `/private/var` 这类符号链接拼写不会让嵌套 worktree 被误判到工作区之外(#952)。
- 🧪 测试:`tests/active-worktree.spec.ts` 新增英文 / 中文子目录两例(修复前均为红)。
### v0.29.0
- **侧边对话接入 GenUI**:通过现有 `ctx.betterSidebar` 服务新增可选的 `registerSidechatSurfaceAdapter`,支持 GenUI 0.15.0 渲染已结算的助手回复;未注册消费方时保持原 Markdown。
+7
View File
@@ -4,6 +4,13 @@
>
> 📝 The Chinese [CHANGELOG](./CHANGELOG.md) is the authoritative, item-by-item record; this file carries the English summaries and has historically lagged behind it. Where the two disagree, the Chinese one is current.
### Unreleased
- 🪟 **Windows + WSL workspaces: a UNC path is no longer folded into a drive-relative one.** Re-spelling paths on a Windows base folded every run of separators into one `\`, which also folded the UNC prefix of `\\wsl.localhost\<distro>\...` into `\wsl.localhost\...`; the host's `path.resolve()` then anchored that on its own process drive (`C:\wsl.localhost\...`), so every file opened from a WSL workspace failed with ENOENT. The UNC prefix now survives and only the rest is folded (drive paths are unchanged).
- 🧪 `tests/worktree-address.spec.ts` adds one case: UNC absolute, workspace-relative, and forward-slash spellings all keep the two leading separators.
- 🗂 **A session cwd that is a Git repository subdirectory is no longer lifted to the repository top** ([#1024](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1024), [#1080](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1080); contributor PR [#1070](https://github.com/omdsh-dev/DSH-better-sidebar/pull/1070) @hy5424): the sidebar root was replaced with `git rev-parse --show-toplevel`, so a relative file link in chat resolved to `<repo>/<file>` instead of `<repo>/<subdir>/<file>` (ENOENT) and file search used the wrong root. The session cwd is now the root as it stands; only linked-worktree evidence from the session's own tool calls replaces it. The cwd is canonicalized first, so symlinked spellings (`/var` vs `/private/var`) cannot make a nested worktree look outside the workspace (#952).
- 🧪 `tests/active-worktree.spec.ts` adds one ASCII and one Chinese subdirectory case (both red before the fix).
### v0.29.0
- **GenUI in side chats**: the existing `ctx.betterSidebar` service exposes the opt-in `registerSidechatSurfaceAdapter` for GenUI 0.15.0 to render settled assistant replies. Without a consumer, Markdown rendering stays unchanged.
+32 -8
View File
@@ -22,8 +22,9 @@
* (#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).
* working-directory/change is eligible. With no such evidence the session cwd
* itself is kept, a session living in a subdirectory of its repository
* included: the repository top level is never a root on its own.
*
* Resolutions are cached process-wide ({@link ACTIVE_ROOT_TTL_MS}), concurrent
* callers share one in-flight resolution AND one in-flight base probe, and
@@ -33,7 +34,7 @@
* answered with its base (the workspace address) and never folds the stored
* log — see {@link activeWorktreeRootOf}.
*/
import { stat } from 'node:fs/promises'
import { realpath, stat } from 'node:fs/promises'
import { dirname, isAbsolute, join, sep } from 'node:path'
import type { Context, SidebarSessionEvent } from './context-types.ts'
import { requireAbsolute } from './fs-tree.ts'
@@ -459,7 +460,8 @@ async function sessionEventsOf(ctx: Context, sessionId: string): Promise<readonl
* @param ctx - host plugin context.
* @param sessionId - session whose tool calls are inspected.
* @param base - the authoritative session cwd (already resolved by the caller).
* @returns the active linked worktree, the repository top level, or `base`.
* @returns the linked worktree the session moved into, or the session cwd's
* own (real) path — never the repository top level.
*/
export async function activeWorktreeRootOf(ctx: Context, sessionId: string, base: string): Promise<string> {
if (base === '') return base
@@ -512,6 +514,29 @@ export async function activeWorktreeRootOf(ctx: Context, sessionId: string, base
return promise
}
/**
* The session cwd as the filesystem spells it, without ever substituting the
* repository top level.
*
* This value is the base a relative link path resolves against, so lifting a
* subdirectory session to `<repo>` would resolve `<subdir>/tools/a.md` as
* `<repo>/tools/a.md` (#1024 / #1080). Canonicalizing instead of returning the
* caller's spelling keeps the value comparable with the canonical paths
* `git rev-parse` reports: the workspace-containment decision in
* {@link isAdoptableTop} must still see a nested worktree as INSIDE the
* workspace when the cwd was reached through a symlink (macOS's `/var` vs
* `/private/var` is the #952 layout).
*/
async function sessionRootOf(base: string): Promise<string> {
try {
return await realpath(base)
} catch {
// A cwd deleted between the git probe and this syscall keeps its spelling;
// that answer is no worse than the pre-existing one.
return base
}
}
/** One uncached resolution (see {@link activeWorktreeRootOf}). */
async function resolveActiveWorktreeRoot(ctx: Context, sessionId: string, base: string, directoryEpoch: number | undefined): Promise<string> {
// Read the cursor BEFORE the scan: if an event lands mid-resolution the
@@ -525,10 +550,9 @@ async function resolveActiveWorktreeRoot(ctx: Context, sessionId: string, base:
cachePut(activeWorktreeRootCache, sessionId, { root: base, base, directoryEpoch, eventSeq, gitResolved: false, expires: Date.now() + ACTIVE_ROOT_TTL_MS }, ACTIVE_ROOT_CACHE_MAX)
return base
}
const canonicalTop = requireAbsolute(top)
const effectiveBase = pathUnderOf(base, canonicalTop) ? base : canonicalTop
const active = await activeRootFromEvents(await sessionEventsOf(ctx, sessionId), effectiveBase)
const root = active ?? effectiveBase
const canonicalBase = await sessionRootOf(base)
const active = await activeRootFromEvents(await sessionEventsOf(ctx, sessionId), canonicalBase)
const root = active ?? canonicalBase
cachePut(activeWorktreeRootCache, sessionId, { root, base, directoryEpoch, eventSeq, gitResolved: true, expires: Date.now() + ACTIVE_ROOT_TTL_MS }, ACTIVE_ROOT_CACHE_MAX)
return root
}
+11 -1
View File
@@ -57,11 +57,21 @@ export function addressBaseOf(ctx: Context, sessionId: string | undefined): stri
* POSIX keeps the path verbatim: there `\` is a legal file-name character, not
* a separator (the same reason `resolveSidebarPath` never folds on POSIX).
*
* A UNC prefix is NOT a separator run to fold: `\\server\share` is one path
* root, and folding its two leading separators into one turns an absolute
* network path into a drive-root-relative one. On Windows the host then runs
* `path.resolve()` on it, anchoring `\wsl.localhost\...` on the host process
* drive (`C:\wsl.localhost\...`, ENOENT) — every file opened from a
* `\\wsl.localhost\<distro>\...` workspace failed that way. Keep exactly the
* two leading separators and fold only the rest.
*
* @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
if (base === undefined || !base.includes('\\')) return resolved
const folded = resolved.replace(/[/\\]+/g, '\\')
return /^[\\/]{2}/.test(resolved) ? `\\\\${folded.replace(/^\\+/, '')}` : folded
}
+48 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { spawnSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { activeWorktreeRootOf } from '../src/active-worktree.ts'
@@ -162,6 +162,53 @@ describe('active worktree root', () => {
}
})
// A workspace registered at `<repo>/<subdir>` (a plain subdirectory, not a
// linked worktree) must keep that subdirectory as the root: a relative link
// such as `tools/a.md` is resolved against it, so lifting the root to
// `<repo>` opens `<repo>/tools/a.md` and ENOENTs (#1024 / #1080). The ASCII
// and Chinese names are separate cases on purpose: a Unicode normalization
// artifact can move a spelling, but it cannot drop a whole path segment.
for (const [label, subdirectory, sessionId] of [
['an ASCII', 'sub-en', 's-subdir-en'],
['a Chinese', '社媒运营', 's-subdir-zh'],
] as const) {
it(`keeps ${label} subdirectory session cwd instead of lifting it to the repository top level`, async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-'))
const repo = join(root, 'repo')
const base = join(repo, subdirectory)
try {
initRepo(repo, 'a.txt')
mkdirSync(join(base, 'tools'), { recursive: true })
writeFileSync(join(base, 'tools', 'a.md'), '# a\n')
const ctx = sessionCtx(base, [])
const resolved = await activeWorktreeRootOf(ctx, sessionId, base)
expect(resolved).toBe(realpathSync.native(base))
// The reported symptom, asserted on a real read through the root: the
// file exists one level below the repository top level.
expect(readFileSync(join(resolved, 'tools', 'a.md'), 'utf8')).toBe('# a\n')
} finally {
removeTree(root)
}
})
}
it('keeps a session cwd that is a SUBDIRECTORY of the repository', async () => {
// A workspace registered at `<repo>/workspace` (a plain subdirectory, not a
// linked worktree) must stay the root: replacing it with the repository
// toplevel makes every relative path resolve one level too high.
const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-'))
const repo = join(root, 'repo')
const subdir = join(repo, 'workspace')
try {
initRepo(repo, 'a.txt')
mkdirSync(subdir)
const ctx = sessionCtx(subdir, [])
await expect(activeWorktreeRootOf(ctx, 's-subdir', subdir)).resolves.toBe(realpathSync.native(subdir))
} finally {
removeTree(root)
}
})
it('answers a detached session with its base and never reads the stored log', async () => {
// A detached session has no live events; folding the STORED log would decode
// the whole artifact for a follow-the-agent nicety the workspace address
+14
View File
@@ -180,6 +180,20 @@ describe('address base (worktree sessions)', () => {
expect(resolveAddressPath('/repo', 'a\\b.ts')).toBe('/repo/a\\b.ts')
})
it('keeps a UNC prefix when folding separators (Windows + WSL workspace)', () => {
// A UNC root is ONE path root, not a separator run: folding its `\\` into
// `\` left a drive-root-relative path, which the host then re-anchored on
// its process drive with `path.resolve()` (`C:\wsl.localhost\...`), so
// every file opened from a `\\wsl.localhost\<distro>\...` workspace failed
// with ENOENT. The prefix must survive, only the body is re-spelled.
const root = '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo'
const file = '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo\\src\\a.ts'
expect(resolveAddressPath(root, file)).toBe(file)
expect(resolveAddressPath(root, 'src/a.ts')).toBe(file)
// A forward-slash UNC spelling folds to the base style, prefix intact.
expect(resolveAddressPath(root, '//wsl.localhost/Ubuntu/home/me/repo/src/a.ts')).toBe(file)
})
it('builds every plugin address on the session base, never on the caller root', () => {
const fixture = makeFixture()
try {