Files
apes-sidebar/tests/git-status-poll.spec.tsx
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

249 lines
9.5 KiB
TypeScript

/**
* The shared git-status store's CADENCE contract.
*
* One fetch here is `git status --untracked-files=all` plus two `--numstat`
* diffs, so an automatic poll is real work — and it used to run every 2.5 s for
* as long as any consumer was on screen, notified on every tick whether or not
* anything had changed. Four behaviours are pinned:
*
* - OWNERSHIP: only a `poll: true` consumer starts the timer. A `poll: false`
* consumer (the editor's gutter) reads the shared answer and refreshes on
* its own events, so it can never keep git running in the background.
* - ORDER: a non-polling consumer that arrives FIRST must not stop a polling
* consumer that arrives later from starting the timer.
* - SILENCE: an idle poll that returns an equal status notifies nobody — the
* version counter is the `useSyncExternalStore` snapshot, and bumping it
* re-rendered every consumer (the file tree's rows included) once per
* cadence for nothing.
* - THE LADDER: the baseline is 30 s, a slow round trip drops the slot to
* 60 s then 180 s, and a really slow one stops the automatic timer
* altogether; a fast answer climbs straight back to the baseline.
*/
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createElement, useEffect, type ReactNode } from 'react'
import { act } from 'react-dom/test-utils'
import type { GitStatusResult, SessionScope } from '../src/client/api.ts'
const { gitStatus } = vi.hoisted(() => ({ gitStatus: vi.fn() }))
vi.mock('../src/client/api.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/client/api.ts')>()
return { ...actual, api: { ...actual.api, gitStatus } }
})
import { renderRoot, setupReactAct } from './test-utils.ts'
import { useGitStatus, type GitStatusView } from '../src/client/ui/git-status.ts'
setupReactAct()
const REPO: GitStatusResult = {
isRepo: true,
root: '/tmp',
entries: [{ path: 'a.ts', xy: ' M' }],
}
/** The scope of one test; a fresh sessionId mints a fresh slot. */
const scopeFor = (id: string): SessionScope => ({ sessionId: id, cwd: '/tmp' })
/** Commits observed for the probe component (not renders — see Probe). */
interface Counter { value: number }
/** The view the probe most recently received, for the event-driven cases. */
let latest: GitStatusView | null = null
function Probe(props: { scope: SessionScope; poll?: boolean; visible?: boolean; commits: Counter }): ReactNode {
const view = useGitStatus(props.scope, { poll: props.poll, visible: props.visible })
// One per COMMIT: the store's only observable is the version counter behind
// `useSyncExternalStore`, so a commit is exactly "the store notified".
useEffect(() => { props.commits.value += 1 })
latest = view
return createElement('span')
}
/** Let the store's in-flight fetch settle (inside act — it notifies React). */
async function flush(): Promise<void> {
await act(async () => {
await Promise.resolve()
await Promise.resolve()
})
}
/** Advance the fake clock, letting the store's promises settle inside act. */
async function tick(ms: number): Promise<void> {
await act(async () => { await vi.advanceTimersByTimeAsync(ms) })
}
let mounted: ReturnType<typeof renderRoot> | null = null
afterEach(() => {
mounted?.unmount()
mounted = null
latest = null
gitStatus.mockReset()
vi.useRealTimers()
})
describe('the shared git status store cadence', () => {
it('never starts a timer for a poll:false consumer', async () => {
vi.useFakeTimers()
gitStatus.mockResolvedValue(REPO)
const commits: Counter = { value: 0 }
mounted = renderRoot(createElement(Probe, { scope: scopeFor('poll-off'), poll: false, commits }))
await tick(0)
await flush()
// The one reading a non-polling consumer is entitled to.
expect(gitStatus).toHaveBeenCalledTimes(1)
await tick(120_000)
expect(gitStatus).toHaveBeenCalledTimes(1)
})
it('polls a poll:true consumer on the 30 s baseline', async () => {
vi.useFakeTimers()
gitStatus.mockResolvedValue(REPO)
const commits: Counter = { value: 0 }
mounted = renderRoot(createElement(Probe, { scope: scopeFor('poll-on'), commits }))
await tick(0)
await flush()
expect(gitStatus).toHaveBeenCalledTimes(1)
// Still inside the first interval: the old 2.5 s cadence would already
// have fired ten times here.
await tick(29_000)
expect(gitStatus).toHaveBeenCalledTimes(1)
await tick(2_000)
expect(gitStatus).toHaveBeenCalledTimes(2)
})
it('starts the timer even when the non-polling consumer arrived first', async () => {
vi.useFakeTimers()
gitStatus.mockResolvedValue(REPO)
const commits: Counter = { value: 0 }
const scope = scopeFor('mixed-order')
// Both mount in one commit; effects run in tree order, so the non-polling
// consumer retains the slot first.
const tree = (withPolling: boolean): ReactNode => createElement('div', null,
createElement(Probe, { scope, poll: false, commits }),
withPolling ? createElement(Probe, { scope, poll: true, commits }) : null,
)
mounted = renderRoot(tree(true))
await tick(0)
await flush()
expect(gitStatus).toHaveBeenCalledTimes(1)
// The polling consumer owns the timer...
await tick(31_000)
expect(gitStatus).toHaveBeenCalledTimes(2)
// ...and when it leaves, the timer goes with it while the non-polling one
// keeps its answer.
mounted.rerender(tree(false))
await flush()
const afterLeave = gitStatus.mock.calls.length
await tick(120_000)
expect(gitStatus).toHaveBeenCalledTimes(afterLeave)
expect(latest?.snapshot).not.toBeNull()
})
it('stays silent when an idle poll returns the same status', async () => {
vi.useFakeTimers()
gitStatus.mockResolvedValue(REPO)
const commits: Counter = { value: 0 }
mounted = renderRoot(createElement(Probe, { scope: scopeFor('idle-silent'), commits }))
await tick(0)
await flush()
const settled = commits.value
expect(settled).toBeGreaterThan(0)
// One full cadence: the poll runs (a NEW object every time), the status is
// equal, so no consumer may be told anything. Without the guard this bumps
// the version and the probe commits again.
await tick(30_000)
await flush()
expect(gitStatus).toHaveBeenCalledTimes(2)
expect(commits.value).toBe(settled)
// A real change still lands.
gitStatus.mockResolvedValue({ ...REPO, entries: [{ path: 'a.ts', xy: ' M' }, { path: 'b.ts', xy: '??' }] })
await tick(30_000)
await flush()
expect(commits.value).toBeGreaterThan(settled)
})
it('drops to 60 s when a round trip is slow, and climbs back when it is fast', async () => {
vi.useFakeTimers()
gitStatus.mockImplementation(() => new Promise((resolve) => {
setTimeout(() => { resolve(REPO) }, 1_000)
}))
const commits: Counter = { value: 0 }
mounted = renderRoot(createElement(Probe, { scope: scopeFor('ladder-down'), commits }))
// The first answer takes 1 s of (fake) wall clock: tier 1, i.e. 2x.
await tick(1_000)
await flush()
expect(gitStatus).toHaveBeenCalledTimes(1)
// Past the OLD cadence and past the baseline, but inside 60 s: no tick.
await tick(30_000)
expect(gitStatus).toHaveBeenCalledTimes(1)
// Past 60 s from the moment the slow answer landed: one tick.
await tick(31_000)
expect(gitStatus).toHaveBeenCalledTimes(2)
// A fast answer now resets the ladder to the baseline.
gitStatus.mockResolvedValue(REPO)
// t=122s: the deferred 60 s tick lands and comes back instantly.
await tick(60_000)
await flush()
const recovered = gitStatus.mock.calls.length
expect(recovered).toBeGreaterThan(2)
// Inside a 30 s window: nothing yet...
await tick(20_000)
expect(gitStatus).toHaveBeenCalledTimes(recovered)
// ...but 40 s on, the baseline cadence must have fired (a 60 s one would
// still be waiting, which is what makes this the ladder-down check).
await tick(20_000)
expect(gitStatus).toHaveBeenCalledTimes(recovered + 1)
})
it('stops the automatic timer after a very slow round trip, until an event refreshes', async () => {
vi.useFakeTimers()
gitStatus.mockImplementation(() => new Promise((resolve) => {
setTimeout(() => { resolve(REPO) }, 6_000)
}))
const commits: Counter = { value: 0 }
mounted = renderRoot(createElement(Probe, { scope: scopeFor('ladder-stop'), commits }))
await tick(6_000)
await flush()
expect(gitStatus).toHaveBeenCalledTimes(1)
// Tier 3: no timer at all, so ten minutes of idling cost nothing.
await tick(600_000)
expect(gitStatus).toHaveBeenCalledTimes(1)
// An event-driven refresh still runs — and a fast answer restores polling.
gitStatus.mockResolvedValue(REPO)
await tick(1_000)
await act(async () => { latest?.refresh() })
await flush()
expect(gitStatus).toHaveBeenCalledTimes(2)
await tick(30_000)
expect(gitStatus).toHaveBeenCalledTimes(3)
})
it('does not fetch at all for a hidden consumer, and starts when it shows', async () => {
vi.useFakeTimers()
gitStatus.mockResolvedValue(REPO)
const commits: Counter = { value: 0 }
const scope = scopeFor('visibility')
mounted = renderRoot(createElement(Probe, { scope, visible: false, commits }))
await tick(0)
await flush()
expect(gitStatus).toHaveBeenCalledTimes(0)
await tick(120_000)
expect(gitStatus).toHaveBeenCalledTimes(0)
mounted.rerender(createElement(Probe, { scope, visible: true, commits }))
await tick(0)
await flush()
expect(gitStatus).toHaveBeenCalledTimes(1)
})
})