Files
apes-sidebar/tests/git-worktree.spec.ts
T
Menghuan1918 751720f4f0 perf(git): 状态轮询基线降到 30 s 并按实测退档;编辑器 gutter 不再持有轮询
一次抓取是 `git status --untracked-files=all` 加两条全仓库 `--numstat`(4 个
进程)。在未忽略的大目录上(嵌套 node_modules、pnpm store——根锚定
`/node_modules` 盖不住子目录那种仓库)实测 59,631 条 / 9.24 MB / 0.131 s,
而 `GIT_STATUS_LIMIT = 2000` 是在整份输出产出、拼进字符串、切成五万多个对象
之后才截断的。三处一起收:

- **编辑器 gutter 不再持有轮询**:它此前把功能开关当作页签可见性传进共享
  store,而那个参数正是启动定时器的开关;原生页签 `keepMounted` 又让编辑器
  切走不卸载,于是打开过任何一个 `code` / `jsonl` 文件之后,整页生命周期都在
  每 2.5 s 跑一次那个扫描。现在订阅改为 `{ visible: active, poll: false }`,
  只在换文件或保存时各 `refresh()` 一次,页签不可见时连订阅都不建立。
- **基线 30 s + 按实测退档**:往返超 750 ms / 2 s / 5 s 依次退到 60 s /
  180 s / 停止自动轮询;tier 是最近一次耗时的纯函数,快响应自动回落,事件
  驱动刷新(暂存、提交、丢弃、保存、手动刷新)永远即时,也是恢复通道。
- **空闲轮询不再通知**:`notify()` 原先无条件自增 `slot.version`,而它就是
  `useSyncExternalStore` 的 snapshot,于是每个消费者每 tick 整体重渲染一次
  (文件树那一列逐行重算 git 状态也在其中),即便数据一字未变。
- **linked-checkout 清单改单命令计数**:变动页的 worktree 选择器每 30 s 为
  每个 checkout 跑一次完整 `status()` 只为读条目数,现为一条轻量
  `status --untracked-files=normal`。一处刻意的语义变化:未跟踪目录计 1
  (此前展开计入每个文件,且数字被 2000 上限悄悄截断)。

消费方 API 零变化;`FileViewerProps` / `ctx.betterSidebar` 均未动。文件树与
文件变动页的条目与配色语义不变,只是刷新节奏变慢。

测试:新增 `tests/git-status-poll.spec.tsx`(7 例,含「非轮询消费者不得启动
定时器」「空闲同结果不通知(snapshot 恒等)」「慢往返退档与快响应回落」);
`tests/editor-git-gutter.spec.tsx` +3;`tests/git-worktree.spec.ts` +1;
`tests/git-view-worktree.spec.tsx` 的计数重发布用例跟着新节奏推进假时钟。
判别性已逐条实测:回退空闲守卫、`poll` 归属、gutter 的 `poll: false`,
对应用例当场红。

设计、实测数据与普查后续项见
docs/plans/2026-10-13-git-poll-ladder-and-idle-notify.md。
2026-10-13 13:12:00 +08:00

136 lines
5.9 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import { spawnSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { parseWorktreeList, resolveWorktree, status, worktrees } from '../src/git.ts'
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 {
const result = spawnSync('git', ['-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
}
describe('linked Git worktrees', () => {
it('parses porcelain records with spaces in checkout paths', () => {
expect(parseWorktreeList([
'worktree C:/repo/main checkout',
'HEAD abc',
'branch refs/heads/main',
'',
'worktree C:/repo/agent checkout',
'HEAD def',
'detached',
'',
].join('\n'))).toEqual([
{ path: 'C:/repo/main checkout', branch: 'main', locked: false, prunable: false },
{ path: 'C:/repo/agent checkout', branch: 'HEAD', locked: false, prunable: false },
])
})
it('preserves locked metadata and marks stale records prunable', () => {
expect(parseWorktreeList([
'worktree C:/repo/locked',
'HEAD abc',
'branch refs/heads/locked',
'locked in use',
'',
'worktree C:/repo/missing',
'HEAD def',
'prunable gitdir file points to non-existent location',
'',
].join('\0'))).toEqual([
{ path: 'C:/repo/locked', branch: 'locked', locked: true, prunable: false },
{ path: 'C:/repo/missing', branch: 'HEAD', locked: false, prunable: true },
])
})
it('discovers dirty linked checkouts and fences selected targets', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-worktrees-'))
const main = join(root, 'main')
const agent = join(root, 'agent worktree')
try {
git(root, ['init', '-q', main])
git(main, ['checkout', '-q', '-b', 'main'])
writeFileSync(join(main, 'tracked.txt'), 'base\n')
git(main, ['add', '-A'])
git(main, ['commit', '-q', '-m', 'base'])
git(main, ['worktree', 'add', '-q', '-b', 'agent', agent])
writeFileSync(join(agent, 'tracked.txt'), 'changed by agent\n')
// macOS tmpdir() keeps the /var symlink while git reports the resolved
// /private/var prefix; on Windows TEMP is often the 8.3 short form
// (C:\Users\RUNNER~1\...) while git reports the long path. The NATIVE
// realpath resolves both aliasings (libuv's GetFinalPathNameByHandle
// expands 8.3 names) — canonicalize every path handed to git APIs.
const agentPath = realpathSync.native(agent)
const listed = await worktrees(main)
expect(listed).toHaveLength(2)
expect(listed.find(entry => entry.current)).toMatchObject({ branch: 'main', changes: 0 })
expect(listed.find(entry => !entry.current)).toMatchObject({ branch: 'agent', changes: 1 })
expect(resolve(await resolveWorktree(main, agentPath))).toBe(resolve(agentPath))
// The line counts ride the same status answer (#131): 'base' →
// 'changed by agent' is exactly one line replaced.
expect((await status(await resolveWorktree(main, agentPath))).entries).toEqual([
{ path: 'tracked.txt', xy: ' M', counts: { additions: 1, deletions: 1 } },
])
await expect(resolveWorktree(main, root)).rejects.toThrow('unknown linked worktree')
// Git retains administrative metadata after a checkout directory is
// deleted, reporting the record as prunable. It must disappear from both
// the selector inventory and the accepted command-target allowlist.
rmSync(agent, { recursive: true, force: true })
const remaining = await worktrees(main)
expect(remaining).toHaveLength(1)
expect(resolve(remaining[0]!.path)).toBe(resolve(realpathSync.native(main)))
expect(remaining[0]!.current).toBe(true)
await expect(resolveWorktree(main, agentPath)).rejects.toThrow('unknown linked worktree')
} finally {
try { git(main, ['worktree', 'remove', '--force', agent]) } catch { /* fixture may not be fully initialized */ }
rmSync(root, { recursive: true, force: true })
}
})
it('counts an untracked directory as ONE entry in the inventory', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-worktree-count-'))
const main = join(root, 'main')
try {
git(root, ['init', '-q', main])
git(main, ['checkout', '-q', '-b', 'main'])
writeFileSync(join(main, 'tracked.txt'), 'base\n')
git(main, ['add', '-A'])
git(main, ['commit', '-q', '-m', 'base'])
// A large untracked tree. The inventory used to answer this by calling
// the full `status()` — FOUR processes per linked checkout, including the
// `--untracked-files=all` walk — on a 30 s poll, only to read
// `.entries.length`. "Does this checkout have changes" is the question,
// and one directory row is its answer: cheaper, and not silently capped
// at GIT_STATUS_LIMIT the way the expanded count was.
mkdirSync(join(main, 'vendor/nested'), { recursive: true })
for (let index = 0; index < 50; index += 1) {
writeFileSync(join(main, `vendor/nested/f${index}.txt`), 'x\n')
}
const listed = await worktrees(main)
expect(listed).toHaveLength(1)
expect(listed[0]!.changes).toBe(1)
// The per-file answer is untouched: the tree's ink and the changes page
// still expand the same tree file by file.
expect((await status(main)).entries).toHaveLength(50)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
})