Files
apes-sidebar/tests/active-worktree.spec.ts
T
unsc9 ebc5d0b6b7 refactor: 精简 dev 相对 main 新增代码里的重复与白干(行为不变)
dev 分支的新增代码过了一轮「代码精简」审查(复用 / 简化 / 效率 / 修在哪一层四个角度,
分宿主侧、客户端外壳、客户端功能面板三片,另加测试与脚本),这里只落地行为完全不变的那批:

- `runGitRaw` 是 `runGit` 的纯转发别名(三个角度都点到):导出 `runGit`、删掉别名,
  `active-worktree.ts` 与它的 `vi.mock` 键同步改名。
- `open-external.ts` 的 `messageOf` 与 `fs-tree.ts` 的导出逐字相同:删本地实现改 import。
- `fs-operations.ts` 的单段名校验抄了三遍(注释却自称 shared rule):提成
  `assertSingleSegmentName`,rename / mkdir / 新建文件三处共用。
- `fs-tree.ts` 两个探测函数各抄一遍有界并发池:提成 `forEachRow`。
- `index.ts` 自己复刻了一遍 `request/header` 的 provider/model 读取:改调
  `collectModelRoutes(events, 1)[0]`;`lowestReasoningEffortOf` 的三态循环收成
  best/bestRank;`formatModelRoute` 零调用点,删掉(连带自测)。
- `state.ts`:`markUnread` / `clearUnread` 的当前会话路径改走已有的 `reduce`
  (「归约器返回同引用即 no-op」本来就在 reduce 里),删掉私有的 `replaceCurrent`;
  非当前会话那条仍只写内存不落盘,行为未动。
- `editor-dirty.ts`:`DirtyEntry.sessionId` 只服务一个没有生产调用者的
  `dirtyCountForSession`,会话隔离已由 `sessionId::tabId` 这个键承载,两个一起删,
  用例改断 `isEditorDirty(tabId, sessionId)`。
- `FileTree.tsx`:同一批行原先 `renderLevel` 与 `visibleRows` 各排一次,收进按
  `(data, sort)` 记忆的 `entriesFor`(照 `chainFor` 的形状)。
- `dock-fallback.tsx`:500ms 重测出的坐标没变就不换 state 对象(省掉一次无意义重渲染)。
- 其余同形收口:`DiffPane` 的死分支、`terminal-client` 的 `bottomTerminalKey`
  (与 `bottomTerminalContentId` 同值,调用点复用同一个 id)、`SideChatView` 的
  O(线程×目录) 排序扫描降为 Map、`conversation-draft` 的末段路径复用 `paths.baseName`、
  `TreePanel` 的目录命中集按 results 记忆。

验证:`tsc --noEmit` 只剩改动前那 3 条缺 `@xterm/*` 的既有报错;eslint 干净;
全套 vitest 与改动前的失败集合逐条一致(13 条,均为环境原因:缺 xterm 的构建/转换类
3 条、Windows 符号链接权限 3 条、语言字典串味 4 条、真起 git 的冒烟 1 条、文件级 1 条)。
2026-10-09 16:04:24 +08:00

121 lines
4.9 KiB
TypeScript

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'
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,
runGit: (cwd: string, args: string[], timeoutMs?: number) => {
probed.push(cwd)
return actual.runGit(cwd, args, timeoutMs)
},
}
})
const IDENTITY = {
GIT_AUTHOR_NAME: 'dsh-better-sidebar-test',
GIT_AUTHOR_EMAIL: 'test@dsh.invalid',
GIT_COMMITTER_NAME: 'dsh-better-sidebar-test',
GIT_COMMITTER_EMAIL: 'test@dsh.invalid',
}
function git(cwd: string, args: string[]): string {
// `core.hooksPath=` keeps a developer's global commit-msg hook out of the scratch repos.
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
}
function initRepo(path: string, file: string): void {
mkdirSync(path, { recursive: true })
git(path, ['init', '-q'])
git(path, ['checkout', '-q', '-b', 'main'])
writeFileSync(join(path, file), 'base\n')
git(path, ['add', '-A'])
git(path, ['commit', '-q', '-m', 'base'])
}
/** A minimal live-session face: header cwd plus the tool/call events to scan. */
function sessionCtx(cwd: string, calls: Array<Record<string, unknown>>): Context {
return {
sessions: {
get: () => ({
header: { cwd },
snapshotEvents: () => calls.map((data, index) => ({ type: 'tool/call', seq: index, time: index, data })),
}),
},
get: () => undefined,
} as never
}
describe('active worktree root', () => {
it('follows a linked worktree of a DIFFERENT repository named by the tool calls', async () => {
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])
// The session's header cwd is repo A, but its newest tool call works in
// a linked worktree of repo B the sidebar must follow that worktree.
const ctx = sessionCtx(repoA, [{ cwd: worktreeB, path: join(worktreeB, 'b.txt') }])
// The roots come back from `git rev-parse --show-toplevel`, i.e. already
// canonical: compare against the real path (macOS tmpdirs live under the
// `/var` → `/private/var` symlink; same convention as git-worktree.spec).
await expect(activeWorktreeRootOf(ctx, 's-cross-repo', repoA)).resolves.toBe(realpathSync.native(worktreeB))
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('keeps the session cwd when no tool call points at a linked worktree', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-'))
const repo = join(root, 'repo')
try {
initRepo(repo, 'a.txt')
const ctx = sessionCtx(repo, [{ cwd: join(repo, 'src') }])
await expect(activeWorktreeRootOf(ctx, 's-no-worktree', repo)).resolves.toBe(realpathSync.native(repo))
} finally {
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 })
}
})
})