fix(active-worktree): 探测真实路径而非大小写折叠后的 identity key

#802 把 tool call 里的候选路径按 pathKeyOf()(小写 + 分隔符归一)当 map key 记账,
随后又把这个 key 本身交给 git rev-parse --show-toplevel 去探测。Linux 区分大小写,
…/iHpOqm 折叠成 …/ihpoqm 后 stat 与 git 全部失败,候选被静默丢弃,函数回退到会话
cwd——跨仓 linked worktree 永不跟随。macOS / Windows 的文件系统折叠大小写,所以本地
全绿;dev 上 b2599b3、9b97e6f、3bd5e19 三次 ci 全红在
"follows a linked worktree of a DIFFERENT repository named by the tool calls"。

现在候选以 { path, score } 记账:key 仍只用于身份比较,探测一律用 path。回归用例断言
探测入参里出现原始大小写的路径(旧代码是小写变体),因此在 macOS 上同样是红的,
不依赖宿主文件系统是否折叠大小写。

Refs #802
This commit is contained in:
Menghuan1918 committed 2026-10-05 02:35:18 +08:00
1 parent 3bd5e1947b
commit f02b0fa3d3
2 files changed
+66 -11

No files matched your search

+26 -10
View File
@@ -52,7 +52,14 @@ const activeWorktreeRootCache = new Map<string, { root: string; base: string; ex
const pathTopCache = new Map<string, string | undefined>()
const linkedWorktreeCache = new Map<string, boolean>()
/** Normalized identity of a path (case- and separator-insensitive). */
/**
* Normalized IDENTITY of a path (case- and separator-insensitive), for
* comparisons and cache keys only: it lowercases, so it must never be handed
* back to the filesystem. On Linux (case-sensitive) `…/iHpOqm` → `…/ihpoqm`
* is a different, usually non-existent path, and probing it silently drops
* the candidate; macOS and Windows mask that because their filesystems fold
* case. Keep the real path next to its key.
*/
function pathKeyOf(value: string): string {
return value.replace(/[\\/]+/g, '/').replace(/\/+$/, '').toLowerCase()
}
@@ -87,12 +94,21 @@ function normalizeActivePath(value: string): string {
return trimmed.replace(/[\\/]+/g, sep)
}
function addActivePath(map: Map<string, number>, value: unknown, weight: number): void {
/** One candidate path mentioned by a tool call, with its accumulated score. */
interface ActivePathEntry {
/** The real path (original case), the only form safe to probe. */
path: string
score: number
}
function addActivePath(map: Map<string, ActivePathEntry>, value: unknown, weight: number): void {
if (typeof value !== 'string') return
const normalized = normalizeActivePath(value)
if (normalized === '' || !isAbsolute(normalized)) return
const key = pathKeyOf(normalized)
map.set(key, (map.get(key) ?? 0) + weight)
const entry = map.get(key)
if (entry === undefined) map.set(key, { path: normalized, score: weight })
else entry.score += weight
}
/**
@@ -101,7 +117,7 @@ function addActivePath(map: Map<string, number>, value: unknown, weight: number)
* @param map - accumulator keyed by normalized path identity.
* @param structured - whether the current value sits in a cwd/workdir/path field.
*/
function collectActivePaths(value: unknown, map: Map<string, number>, structured: boolean): void {
function collectActivePaths(value: unknown, map: Map<string, ActivePathEntry>, structured: boolean): void {
if (typeof value === 'string') {
if (isAbsolute(value)) {
addActivePath(map, value, structured ? 8 : 1)
@@ -175,22 +191,22 @@ async function activeRootFromEvents(events: readonly SidebarSessionEvent[], base
for (let index = events.length - 1; index >= start; index -= 1) {
const event = events[index]
if (event === undefined || event.type !== 'tool/call') continue
const weights = new Map<string, number>()
const weights = new Map<string, ActivePathEntry>()
collectActivePaths(event.data, weights, false)
if (weights.size === 0) continue
const ordered = [...weights.entries()].sort((left, right) => right[1] - left[1])
const ordered = [...weights.values()].sort((left, right) => right.score - left.score)
const scores = new Map<string, { top: string; score: number }>()
for (const [value, weight] of ordered) {
for (const candidate of ordered) {
if (probes >= ACTIVE_ROOT_MAX_PROBES) break
probes += 1
const top = await topOfActivePath(value)
const top = await topOfActivePath(candidate.path)
if (top === undefined) continue
const topKey = pathKeyOf(top)
if (topKey === baseKey) continue
if (!(await isLinkedWorktree(top))) continue
const entry = scores.get(topKey)
if (entry === undefined) scores.set(topKey, { top, score: weight })
else entry.score += weight
if (entry === undefined) scores.set(topKey, { top, score: candidate.score })
else entry.score += candidate.score
}
if (scores.size > 0) {
let best: string | undefined
+40 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import { spawnSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
@@ -6,6 +6,22 @@ import { join } from 'node:path'
import { activeWorktreeRootOf } from '../src/active-worktree.ts'
import type { Context } from '../src/context-types.ts'
/** Every cwd handed to the plugin's own git probe, in call order. */
const probed = vi.hoisted(() => [] as string[])
// Records (and delegates to) the real spawn so the case-folding regression is
// visible on case-insensitive hosts too.
vi.mock('../src/git.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/git.ts')>()
return {
...actual,
runGitRaw: (cwd: string, args: string[], timeoutMs?: number) => {
probed.push(cwd)
return actual.runGitRaw(cwd, args, timeoutMs)
},
}
})
const IDENTITY = {
GIT_AUTHOR_NAME: 'dsh-better-sidebar-test',
GIT_AUTHOR_EMAIL: 'test@dsh.invalid',
@@ -78,4 +94,27 @@ describe('active worktree root', () => {
rmSync(root, { recursive: true, force: true })
}
})
it('probes the REAL path, never its case-folded identity (Linux is case-sensitive)', async () => {
// `addActivePath` keys candidates by a lowercased identity; probing that
// KEY instead of the path silently drops every candidate whose path has an
// uppercase letter. macOS and Windows fold case and never noticed it —
// `Repo-A` / `WorkTree-B` below make the difference visible on every host.
const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-'))
const repoA = join(root, 'Repo-A')
const repoB = join(root, 'Repo-B')
const worktreeB = join(root, 'WorkTree-B')
try {
initRepo(repoA, 'a.txt')
initRepo(repoB, 'b.txt')
git(repoB, ['worktree', 'add', '-q', '-b', 'agent', worktreeB])
probed.length = 0
const ctx = sessionCtx(repoA, [{ cwd: worktreeB, path: join(worktreeB, 'b.txt') }])
await expect(activeWorktreeRootOf(ctx, 's-case', repoA)).resolves.toBe(realpathSync.native(worktreeB))
expect(probed).toContain(worktreeB)
expect(probed).not.toContain(worktreeB.toLowerCase())
} finally {
rmSync(root, { recursive: true, force: true })
}
})
})