Display total lines of code change in branch header (#12771)

* Add branch line total chip to source control header

Display the total lines added and removed across a branch from its fork point, measured via `git diff <mergeBase>`. Only computed when the chip is visible (request gate on merge base OID), with 500ms soft deadline to protect status latency and 15s hard timeout. Deduplicated across concurrent pollers and cached alongside line stats. Omitted on failure — always shows exact or nothing, never a partial estimate. Updates throughout the stack: native git status, relay, renderer store/API, and UI components.

* Pin branch line total to app locale

Format line counts using the app's configured locale instead of the system
locale, ensuring consistent cross-platform display and test reliability.

* test: wait for coalescer joins instead of fixed sleep

Hold the diff until the second status pass actually takes the
branch-total coalescer lease instead of using a fixed 400ms sleep.
Fixes timing-dependent flakiness on slow machines.
This commit is contained in:
Jinjing
2026-08-05 14:46:00 -07:00
committed by GitHub
parent 73cd4c3f46
commit debf4affe7
48 changed files with 4112 additions and 194 deletions
@@ -0,0 +1,62 @@
import { describe, expect, it, vi } from 'vitest'
import {
beginGitStatusLineStatsCacheWrite,
clearGitStatusLineStatsCache,
readCachedGitBranchLineTotal,
reuseOrRecomputeGitStatusLineStats
} from './git-status-line-stats-cache'
const MERGE_BASE = 'a'.repeat(40)
const CACHE_KEY = 'native\0/repo'
const entries = [{ path: 'a.txt', area: 'unstaged', status: 'M', added: 1, removed: 0 }]
async function runPass(diffDelayMs: number): Promise<{ elapsed: number; total: unknown }> {
const cacheKey = CACHE_KEY
const started = Date.now()
const result = await reuseOrRecomputeGitStatusLineStats({
cacheKey,
head: 'head-1',
entries,
writeToken: beginGitStatusLineStatsCacheWrite(cacheKey),
reuse: false,
isAborted: () => false,
recompute: async () => true,
branchLineTotal: {
mergeBase: MERGE_BASE,
compute: () =>
new Promise((resolve) =>
setTimeout(() => resolve({ added: 5, removed: 5, mergeBase: MERGE_BASE }), diffDelayMs)
)
}
})
return { elapsed: Date.now() - started, total: result.branchLineTotal }
}
describe('branch line total never blocks the status response', () => {
it('returns fast when the ranged diff is slow, then publishes it on the next pass', async () => {
clearGitStatusLineStatsCache()
const slow = await runPass(3000)
expect(slow.total).toBeUndefined()
expect(slow.elapsed).toBeLessThan(1200)
// Why: poll the cache rather than run another pass — a second recompute
// stores, which retires the first pass's still-pending late-arrival token.
await vi.waitFor(
() => {
expect(
readCachedGitBranchLineTotal({ cacheKey: CACHE_KEY, mergeBase: MERGE_BASE })
).toEqual({ added: 5, removed: 5, mergeBase: MERGE_BASE })
},
{ timeout: 15000, interval: 50 }
)
const next = await runPass(3000)
expect(next.total).toEqual({ added: 5, removed: 5, mergeBase: MERGE_BASE })
}, 20000)
it('still returns the total inline when the diff is fast', async () => {
clearGitStatusLineStatsCache()
const fast = await runPass(10)
expect(fast.total).toEqual({ added: 5, removed: 5, mergeBase: MERGE_BASE })
expect(fast.elapsed).toBeLessThan(400)
})
})
+434
View File
@@ -0,0 +1,434 @@
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import * as path from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
buildGitBranchLineTotalDiffArgs,
invalidateGitBranchLineTotalInFlight,
computeGitBranchLineTotal,
GIT_BRANCH_LINE_TOTAL_SOFT_DEADLINE_MS,
GIT_BRANCH_LINE_TOTAL_TIMEOUT_MS,
isGitBranchLineTotalMergeBase,
readGitBranchLineTotalMergeBaseParam,
sumGitBranchLineTotal
} from './git-branch-line-total'
import type { GitLineStats } from './git-uncommitted-line-stats'
const MERGE_BASE = 'a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4'
const OTHER_MERGE_BASE = '0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c'
function statsMap(entries: Record<string, GitLineStats>): ReadonlyMap<string, GitLineStats> {
return new Map(Object.entries(entries))
}
function createAbortError(): Error {
const error = new Error('The operation was aborted.')
error.name = 'AbortError'
return error
}
const tempRoots: string[] = []
async function createWorktreeDir(files: Record<string, string> = {}): Promise<string> {
const root = await mkdtemp(path.join(tmpdir(), 'orca-branch-line-total-'))
tempRoots.push(root)
for (const [relativePath, contents] of Object.entries(files)) {
await writeFile(path.join(root, relativePath), contents)
}
return root
}
beforeEach(() => {
invalidateGitBranchLineTotalInFlight()
})
afterEach(async () => {
invalidateGitBranchLineTotalInFlight()
await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('sumGitBranchLineTotal', () => {
it('counts binary entries as zero rather than NaN', () => {
expect(
sumGitBranchLineTotal({
mergeBase: MERGE_BASE,
tracked: statsMap({
'blob.bin': { added: undefined, removed: undefined },
'src/a.ts': { added: 4, removed: 1 }
}),
untracked: statsMap({})
})
).toEqual({ added: 4, removed: 1, mergeBase: MERGE_BASE })
})
it('counts a half-binary entry on the side git did report', () => {
expect(
sumGitBranchLineTotal({
mergeBase: MERGE_BASE,
tracked: statsMap({ 'odd.txt': { added: 3 } }),
untracked: statsMap({ 'new.bin': {} })
})
).toEqual({ added: 3, removed: 0, mergeBase: MERGE_BASE })
})
it('adds untracked additions on top of the tracked range and echoes the merge base', () => {
expect(
sumGitBranchLineTotal({
mergeBase: MERGE_BASE,
tracked: statsMap({ 'src/a.ts': { added: 10, removed: 2 } }),
untracked: statsMap({ 'src/new.ts': { added: 7, removed: 0 }, 'src/also.ts': { added: 1 } })
})
).toEqual({ added: 18, removed: 2, mergeBase: MERGE_BASE })
})
it('returns an all-zero total for a pure rename rather than omitting it', () => {
expect(
sumGitBranchLineTotal({
mergeBase: MERGE_BASE,
tracked: statsMap({ 'g.txt': { added: 0, removed: 0 } }),
untracked: statsMap({})
})
).toEqual({ added: 0, removed: 0, mergeBase: MERGE_BASE })
})
})
describe('merge base param validation', () => {
it('accepts abbreviated and full object names', () => {
for (const value of ['abc1234', MERGE_BASE, 'f'.repeat(64)]) {
expect(isGitBranchLineTotalMergeBase(value)).toBe(true)
expect(readGitBranchLineTotalMergeBaseParam(value)).toBe(value)
}
})
it('rejects anything that is not an object name, notably flag-shaped input', () => {
const rejected: unknown[] = [
'--upload-pack=x',
'-M',
'HEAD',
'',
'origin/main',
'A1B2C3D',
'abc123',
'f'.repeat(65),
'abc1234 --output=/tmp/x',
undefined,
null,
42,
{ toString: () => MERGE_BASE }
]
for (const value of rejected) {
expect(isGitBranchLineTotalMergeBase(value)).toBe(false)
expect(readGitBranchLineTotalMergeBaseParam(value)).toBeUndefined()
}
})
})
describe('buildGitBranchLineTotalDiffArgs', () => {
it('diffs the merge base against the working tree with -M only', () => {
expect(buildGitBranchLineTotalDiffArgs(MERGE_BASE)).toEqual([
'-c',
'core.quotePath=false',
'diff',
'-z',
'--numstat',
'-M',
MERGE_BASE,
'--'
])
})
it('never asks for --cached or -C, which would change the measured range', () => {
const args = buildGitBranchLineTotalDiffArgs(MERGE_BASE)
expect(args).not.toContain('--cached')
expect(args).not.toContain('-C')
expect(args.at(-1)).toBe('--')
})
it('exposes a finite timeout budget so a huge branch cannot block the status response', () => {
expect(GIT_BRANCH_LINE_TOTAL_TIMEOUT_MS).toBeGreaterThan(0)
expect(Number.isFinite(GIT_BRANCH_LINE_TOTAL_TIMEOUT_MS)).toBe(true)
})
})
describe('computeGitBranchLineTotal', () => {
it('never invokes git for a merge base that is not an object name', async () => {
const runDiffNumstat = vi.fn()
for (const mergeBase of ['--upload-pack=x', 'HEAD', '', 'origin/main']) {
await expect(
computeGitBranchLineTotal({
worktreePath: '/repo',
hostKey: 'native',
mergeBase,
untrackedPaths: [],
runDiffNumstat
})
).resolves.toBeUndefined()
}
expect(runDiffNumstat).not.toHaveBeenCalled()
})
it('includes untracked additions the ranged diff cannot see', async () => {
const worktreePath = await createWorktreeDir({ 'new.txt': 'one\ntwo\nthree\n' })
await expect(
computeGitBranchLineTotal({
worktreePath,
hostKey: 'native',
mergeBase: MERGE_BASE,
untrackedPaths: ['new.txt'],
runDiffNumstat: async () => '4\t1\tsrc/a.ts\0'
})
).resolves.toEqual({ added: 7, removed: 1, mergeBase: MERGE_BASE })
})
it('omits the total when the ranged numstat fails instead of publishing untracked-only zeros', async () => {
const worktreePath = await createWorktreeDir({ 'new.txt': 'one\ntwo\n' })
await expect(
computeGitBranchLineTotal({
worktreePath,
hostKey: 'native',
mergeBase: MERGE_BASE,
untrackedPaths: ['new.txt'],
runDiffNumstat: async () => {
throw new Error('fatal: bad object')
}
})
).resolves.toBeUndefined()
})
it('coalesces concurrent callers sharing a host, worktree and merge base into one exec', async () => {
let release = (): void => {}
const gate = new Promise<void>((resolve) => {
release = resolve
})
const runDiffNumstat = vi.fn(async () => {
await gate
return '4\t1\tsrc/a.ts\0'
})
const input = {
worktreePath: '/repo',
hostKey: 'native',
mergeBase: MERGE_BASE,
untrackedPaths: [],
runDiffNumstat
}
const both = Promise.all([computeGitBranchLineTotal(input), computeGitBranchLineTotal(input)])
release()
expect(await both).toEqual([
{ added: 4, removed: 1, mergeBase: MERGE_BASE },
{ added: 4, removed: 1, mergeBase: MERGE_BASE }
])
expect(runDiffNumstat).toHaveBeenCalledTimes(1)
})
it('keeps separate execs for a different merge base, worktree or host', async () => {
const runDiffNumstat = vi.fn(async () => '1\t0\tsrc/a.ts\0')
const base = {
worktreePath: '/repo',
hostKey: 'native',
mergeBase: MERGE_BASE,
untrackedPaths: [],
runDiffNumstat
}
await Promise.all([
computeGitBranchLineTotal(base),
computeGitBranchLineTotal({ ...base, mergeBase: OTHER_MERGE_BASE }),
computeGitBranchLineTotal({ ...base, worktreePath: '/other-repo' }),
computeGitBranchLineTotal({ ...base, hostKey: 'Ubuntu' })
])
expect(runDiffNumstat).toHaveBeenCalledTimes(4)
})
it('re-execs once the shared lease has settled', async () => {
const runDiffNumstat = vi.fn(async () => '1\t0\tsrc/a.ts\0')
const input = {
worktreePath: '/repo',
hostKey: 'native',
mergeBase: MERGE_BASE,
untrackedPaths: [],
runDiffNumstat
}
await computeGitBranchLineTotal(input)
await computeGitBranchLineTotal(input)
expect(runDiffNumstat).toHaveBeenCalledTimes(2)
})
it('rejects when the shared diff is aborted instead of resolving a partial total', async () => {
const controller = new AbortController()
const runDiffNumstat = vi.fn(
(_args: string[], signal: AbortSignal) =>
new Promise<string>((_resolve, reject) => {
signal.addEventListener('abort', () => reject(createAbortError()), { once: true })
})
)
const pending = computeGitBranchLineTotal({
worktreePath: '/repo',
hostKey: 'native',
mergeBase: MERGE_BASE,
untrackedPaths: [],
runDiffNumstat,
signal: controller.signal
})
const assertion = expect(pending).rejects.toMatchObject({ name: 'AbortError' })
controller.abort()
await assertion
})
it('rejects immediately for a signal that is already aborted', async () => {
const runDiffNumstat = vi.fn(async () => '1\t0\tsrc/a.ts\0')
await expect(
computeGitBranchLineTotal({
worktreePath: '/repo',
hostKey: 'native',
mergeBase: MERGE_BASE,
untrackedPaths: [],
runDiffNumstat,
signal: AbortSignal.abort()
})
).rejects.toMatchObject({ name: 'AbortError' })
expect(runDiffNumstat).not.toHaveBeenCalled()
})
it('passes the built argv straight through to the runner', async () => {
const runDiffNumstat = vi.fn(async () => '')
await computeGitBranchLineTotal({
worktreePath: '/repo',
hostKey: 'native',
mergeBase: MERGE_BASE,
untrackedPaths: [],
runDiffNumstat
})
expect(runDiffNumstat).toHaveBeenCalledWith(
buildGitBranchLineTotalDiffArgs(MERGE_BASE),
expect.anything()
)
})
it('invalidateGitBranchLineTotalInFlight stops a later pass joining a pre-mutation diff', async () => {
let release = (): void => {}
const gate = new Promise<void>((resolve) => {
release = resolve
})
const runDiffNumstat = vi.fn(async () => {
await gate
return '1\t0\tsrc/a.ts\0'
})
const input = {
worktreePath: '/repo',
hostKey: 'native',
mergeBase: MERGE_BASE,
untrackedPaths: [],
runDiffNumstat
}
const first = computeGitBranchLineTotal(input)
invalidateGitBranchLineTotalInFlight()
const second = computeGitBranchLineTotal(input)
release()
await Promise.all([first, second])
expect(runDiffNumstat).toHaveBeenCalledTimes(2)
})
})
describe('computeGitBranchLineTotal ranged-diff cooldown', () => {
let nowMs = 0
function diffTaking(durationMs: number): () => Promise<string> {
return vi.fn(async () => {
nowMs += durationMs
return '10\t2\tsrc/a.ts\0'
})
}
function inputFor(
runDiffNumstat: () => Promise<string>,
worktreePath = '/repo'
): Parameters<typeof computeGitBranchLineTotal>[0] {
return {
worktreePath,
hostKey: 'native',
mergeBase: MERGE_BASE,
untrackedPaths: [],
runDiffNumstat
}
}
const TOTAL = { added: 10, removed: 2, mergeBase: MERGE_BASE }
beforeEach(() => {
nowMs = 0
vi.spyOn(performance, 'now').mockImplementation(() => nowMs)
})
afterEach(() => {
vi.restoreAllMocks()
})
it('skips a rerun for as long as the overrunning diff itself took', async () => {
const runDiffNumstat = diffTaking(900)
const input = inputFor(runDiffNumstat)
await expect(computeGitBranchLineTotal(input)).resolves.toEqual(TOTAL)
await expect(computeGitBranchLineTotal(input)).resolves.toBeUndefined()
expect(runDiffNumstat).toHaveBeenCalledTimes(1)
nowMs += 900
await expect(computeGitBranchLineTotal(input)).resolves.toEqual(TOTAL)
expect(runDiffNumstat).toHaveBeenCalledTimes(2)
})
it('leaves a diff inside the soft deadline uncooled, so ordinary repos are untouched', async () => {
const runDiffNumstat = diffTaking(GIT_BRANCH_LINE_TOTAL_SOFT_DEADLINE_MS - 1)
const input = inputFor(runDiffNumstat)
await expect(computeGitBranchLineTotal(input)).resolves.toEqual(TOTAL)
await expect(computeGitBranchLineTotal(input)).resolves.toEqual(TOTAL)
expect(runDiffNumstat).toHaveBeenCalledTimes(2)
})
it('arms the cooldown on a failing diff too, since a timeout is the costliest outcome', async () => {
const runDiffNumstat = vi.fn(async () => {
nowMs += GIT_BRANCH_LINE_TOTAL_TIMEOUT_MS
throw new Error('timed out')
})
const input = inputFor(runDiffNumstat)
await expect(computeGitBranchLineTotal(input)).resolves.toBeUndefined()
await expect(computeGitBranchLineTotal(input)).resolves.toBeUndefined()
expect(runDiffNumstat).toHaveBeenCalledTimes(1)
})
it('clears the cooldown on a git mutation, when a fresh total matters most', async () => {
const runDiffNumstat = diffTaking(900)
const input = inputFor(runDiffNumstat)
await expect(computeGitBranchLineTotal(input)).resolves.toEqual(TOTAL)
invalidateGitBranchLineTotalInFlight()
await expect(computeGitBranchLineTotal(input)).resolves.toEqual(TOTAL)
expect(runDiffNumstat).toHaveBeenCalledTimes(2)
})
it('cools down per worktree, so one slow branch cannot mute another', async () => {
const slow = diffTaking(900)
const other = diffTaking(900)
await expect(computeGitBranchLineTotal(inputFor(slow, '/repo'))).resolves.toEqual(TOTAL)
await expect(computeGitBranchLineTotal(inputFor(slow, '/repo'))).resolves.toBeUndefined()
await expect(computeGitBranchLineTotal(inputFor(other, '/other'))).resolves.toEqual(TOTAL)
expect(slow).toHaveBeenCalledTimes(1)
expect(other).toHaveBeenCalledTimes(1)
})
})
+214
View File
@@ -0,0 +1,214 @@
import { GitStatusReadLeaseOwner } from './git-status-read-lease-owner'
import type { GitBranchLineTotal } from './git-status-types'
import {
collectUntrackedAdditions,
parseNumstat,
type GitLineStats
} from './git-uncommitted-line-stats'
export type { GitBranchLineTotal }
// Why: a mergeBase→worktree diff on a very large branch over SSH is unbounded
// work. Past this budget the chip is dropped rather than the status response
// blocked — an absent total is the documented "not known exact" rendering.
export const GIT_BRANCH_LINE_TOTAL_TIMEOUT_MS = 15_000
// Why: the hard timeout bounds the git process, not the wait. The status
// response carries the file list and staging state, so it must never sit behind
// a ranged diff — past this budget the pass publishes without the total and the
// diff keeps running to backfill the cache for the next pass.
export const GIT_BRANCH_LINE_TOTAL_SOFT_DEADLINE_MS = 500
const BRANCH_LINE_TOTAL_PENDING = Symbol('branch-line-total-pending')
/**
* Resolves with the total only if it lands inside the soft budget; otherwise
* resolves undefined and hands the still-running diff to `onLateArrival`.
*/
export async function settleGitBranchLineTotalWithinSoftDeadline(input: {
total: Promise<GitBranchLineTotal | undefined>
onLateArrival: (total: GitBranchLineTotal) => void
softDeadlineMs?: number
}): Promise<GitBranchLineTotal | undefined> {
let timer: ReturnType<typeof setTimeout> | undefined
const deadline = new Promise<typeof BRANCH_LINE_TOTAL_PENDING>((resolve) => {
timer = setTimeout(
() => resolve(BRANCH_LINE_TOTAL_PENDING),
input.softDeadlineMs ?? GIT_BRANCH_LINE_TOTAL_SOFT_DEADLINE_MS
)
// Why: a pending status timer must not hold the process open at shutdown.
timer.unref?.()
})
const settled = await Promise.race([input.total, deadline])
clearTimeout(timer)
if (settled !== BRANCH_LINE_TOTAL_PENDING) {
return settled
}
void input.total.then((late) => {
if (late) {
input.onLateArrival(late)
}
})
return undefined
}
/**
* `git diff <mergeBase>` with no second rev and no `--cached` compares that
* commit to the working tree, so committed + staged + unstaged collapse into one
* correctly-deduplicated result. Summing the per-area status rows instead would
* double-count any line touched in two areas.
*
* `-M` only (not `-M -C`): matches the working-tree numstat the CHANGES rows are
* built from, and avoids `-C`'s cost on wide diffs. The trailing `--` keeps the
* OID parsed as a rev even if a path of the same name exists.
*/
export function buildGitBranchLineTotalDiffArgs(mergeBase: string): string[] {
return ['-c', 'core.quotePath=false', 'diff', '-z', '--numstat', '-M', mergeBase, '--']
}
/**
* The merge base reaches the host as untrusted RPC input and is spliced into a
* git argv. Only an object name shape is ever legitimate here, so anything else
* (notably a leading `-`) is rejected before it can act as a flag.
*/
export function isGitBranchLineTotalMergeBase(value: unknown): value is string {
return typeof value === 'string' && /^[0-9a-f]{7,64}$/.test(value)
}
/** Reads the request param without trusting its type; undefined disables the work entirely. */
export function readGitBranchLineTotalMergeBaseParam(value: unknown): string | undefined {
return isGitBranchLineTotalMergeBase(value) ? value : undefined
}
export function sumGitBranchLineTotal(input: {
mergeBase: string
tracked: ReadonlyMap<string, GitLineStats>
untracked: ReadonlyMap<string, GitLineStats>
}): GitBranchLineTotal {
let added = 0
let removed = 0
for (const stats of input.tracked.values()) {
// Binary files parse to undefined in numstat and contribute nothing, matching
// the per-file rows.
added += stats.added ?? 0
removed += stats.removed ?? 0
}
for (const stats of input.untracked.values()) {
added += stats.added ?? 0
removed += stats.removed ?? 0
}
return { added, removed, mergeBase: input.mergeBase }
}
// Why: one shared exec per (host, worktree, mergeBase). The renderer's own
// in-flight refs only dedupe a single renderer's calls; a second window or an
// fs-watcher burst would otherwise run the ranged diff twice concurrently.
const rangedNumstatLeaseOwner = new GitStatusReadLeaseOwner<Map<string, GitLineStats> | null>()
// Why: the soft deadline hides this diff's cost from the poller's duration-aware
// backoff, so an overrunning one would restart the moment it finished. Make it
// wait out its own measured cost; the cache carry-forward keeps the chip up.
const GIT_BRANCH_LINE_TOTAL_MAX_COOLDOWN_MS = 30_000
const GIT_BRANCH_LINE_TOTAL_COOLDOWN_MAX_KEYS = 256
const rangedNumstatCooldownUntilMs = new Map<string, number>()
const monotonicNowMs = (): number => performance.now()
function isRangedNumstatCoolingDown(leaseKey: string, nowMs: number): boolean {
const readyAtMs = rangedNumstatCooldownUntilMs.get(leaseKey)
if (readyAtMs === undefined) {
return false
}
if (nowMs >= readyAtMs) {
rangedNumstatCooldownUntilMs.delete(leaseKey)
return false
}
return true
}
function recordRangedNumstatDuration(leaseKey: string, durationMs: number, nowMs: number): void {
if (durationMs <= GIT_BRANCH_LINE_TOTAL_SOFT_DEADLINE_MS) {
rangedNumstatCooldownUntilMs.delete(leaseKey)
return
}
rangedNumstatCooldownUntilMs.delete(leaseKey)
rangedNumstatCooldownUntilMs.set(
leaseKey,
nowMs + Math.min(durationMs, GIT_BRANCH_LINE_TOTAL_MAX_COOLDOWN_MS)
)
while (rangedNumstatCooldownUntilMs.size > GIT_BRANCH_LINE_TOTAL_COOLDOWN_MAX_KEYS) {
const oldestKey = rangedNumstatCooldownUntilMs.keys().next().value
if (oldestKey === undefined) {
return
}
rangedNumstatCooldownUntilMs.delete(oldestKey)
}
}
/**
* Call from every path that clears the other git read caches: without it a pass
* beginning after a discard/stash/checkout joins the pre-mutation lease.
*/
export function invalidateGitBranchLineTotalInFlight(): void {
rangedNumstatLeaseOwner.invalidate()
rangedNumstatCooldownUntilMs.clear()
}
/**
* Computes the branch total, or undefined when it cannot be known exact.
* Rejects only on abort — every other failure hides the chip instead of
* publishing a partial number.
*/
export async function computeGitBranchLineTotal(input: {
worktreePath: string
/** Distinguishes hosts that can map the same path to different filesystems (WSL distro, relay). */
hostKey: string
mergeBase: string
untrackedPaths: readonly string[]
runDiffNumstat: (args: string[], signal: AbortSignal) => Promise<string>
signal?: AbortSignal
}): Promise<GitBranchLineTotal | undefined> {
if (!isGitBranchLineTotalMergeBase(input.mergeBase)) {
return undefined
}
const leaseKey = `${input.hostKey}\0${input.worktreePath}\0${input.mergeBase}`
// Safe before the lease: a cooldown is only armed once a diff settled, so there
// is never an in-flight one to join while it is active.
if (isRangedNumstatCoolingDown(leaseKey, monotonicNowMs())) {
return undefined
}
const [tracked, untracked] = await Promise.all([
rangedNumstatLeaseOwner.lease(leaseKey, input.signal, async (sharedSignal) => {
const startedAtMs = monotonicNowMs()
try {
const stdout = await input.runDiffNumstat(
buildGitBranchLineTotalDiffArgs(input.mergeBase),
sharedSignal
)
return parseNumstat(stdout)
} catch (error) {
// Why: an aborted pass must reject so a cancelled scan is never treated
// as completed. Everything else — a bad merge base, a timeout, a
// detached worktree — yields null so the field is omitted, not zeroed.
if (sharedSignal.aborted) {
throw error
}
return null
} finally {
// `finally`, not the success path: a timeout is the costliest outcome.
if (!sharedSignal.aborted) {
const settledAtMs = monotonicNowMs()
recordRangedNumstatDuration(leaseKey, settledAtMs - startedAtMs, settledAtMs)
}
}
}),
// Untracked files are invisible to a ranged diff but already render as
// CHANGES rows, so they are added on top. Stat-keyed caching inside makes
// this near-free when attachLineStats just read the same paths.
collectUntrackedAdditions(input.worktreePath, input.untrackedPaths, input.signal)
])
if (tracked === null) {
return undefined
}
return sumGitBranchLineTotal({ mergeBase: input.mergeBase, tracked, untracked })
}
@@ -0,0 +1,236 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
applyCachedGitStatusLineStats,
beginGitStatusLineStatsCacheWrite,
clearGitStatusLineStatsCache,
readCachedGitBranchLineTotal,
reuseOrRecomputeGitStatusLineStats,
storeGitStatusLineStats
} from './git-status-line-stats-cache'
import type { GitBranchLineTotal } from './git-status-types'
const CACHE_KEY = 'native\0/repo'
const MERGE_BASE = 'a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4'
const OTHER_MERGE_BASE = '0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c'
const TOTAL: GitBranchLineTotal = { added: 12, removed: 3, mergeBase: MERGE_BASE }
function entries(added?: number): { path: string; status: string; area: string; added?: number }[] {
return [{ path: 'src/a.ts', status: 'modified', area: 'unstaged', ...(added ? { added } : {}) }]
}
function seedSnapshot(branchLineTotal?: GitBranchLineTotal): void {
storeGitStatusLineStats({
cacheKey: CACHE_KEY,
head: 'head-1',
entries: entries(3),
...(branchLineTotal ? { branchLineTotal } : {})
})
}
describe('branch line total inside the status line-stats cache', () => {
beforeEach(() => {
clearGitStatusLineStatsCache()
})
it('costs nothing when the caller did not ask for a total', async () => {
const recompute = vi.fn(async () => true)
const result = await reuseOrRecomputeGitStatusLineStats({
cacheKey: CACHE_KEY,
head: 'head-1',
entries: entries(),
writeToken: beginGitStatusLineStatsCacheWrite(CACHE_KEY),
reuse: false,
isAborted: () => false,
recompute
})
expect(result).toEqual({})
expect(recompute).toHaveBeenCalledTimes(1)
})
it('reuses the cached total on a line-stats reuse hit without re-running the diff', async () => {
seedSnapshot(TOTAL)
const compute = vi.fn(async () => TOTAL)
const recompute = vi.fn(async () => true)
const result = await reuseOrRecomputeGitStatusLineStats({
cacheKey: CACHE_KEY,
head: 'head-1',
entries: entries(),
writeToken: beginGitStatusLineStatsCacheWrite(CACHE_KEY),
reuse: true,
isAborted: () => false,
recompute,
branchLineTotal: { mergeBase: MERGE_BASE, compute }
})
expect(result).toEqual({ branchLineTotal: TOTAL })
expect(compute).not.toHaveBeenCalled()
expect(recompute).not.toHaveBeenCalled()
})
it('recomputes and backfills when the snapshot has no total for this fork point', async () => {
seedSnapshot({ added: 99, removed: 99, mergeBase: OTHER_MERGE_BASE })
const compute = vi.fn(async () => TOTAL)
const first = await reuseOrRecomputeGitStatusLineStats({
cacheKey: CACHE_KEY,
head: 'head-1',
entries: entries(),
writeToken: beginGitStatusLineStatsCacheWrite(CACHE_KEY),
reuse: true,
isAborted: () => false,
recompute: async () => true,
branchLineTotal: { mergeBase: MERGE_BASE, compute }
})
const second = await reuseOrRecomputeGitStatusLineStats({
cacheKey: CACHE_KEY,
head: 'head-1',
entries: entries(),
writeToken: beginGitStatusLineStatsCacheWrite(CACHE_KEY),
reuse: true,
isAborted: () => false,
recompute: async () => true,
branchLineTotal: { mergeBase: MERGE_BASE, compute }
})
expect(first).toEqual({ branchLineTotal: TOTAL })
expect(second).toEqual({ branchLineTotal: TOTAL })
expect(compute).toHaveBeenCalledTimes(1)
expect(readCachedGitBranchLineTotal({ cacheKey: CACHE_KEY, mergeBase: MERGE_BASE })).toEqual(
TOTAL
)
})
it('never serves a cached total that was measured against another fork point', () => {
seedSnapshot(TOTAL)
expect(
readCachedGitBranchLineTotal({ cacheKey: CACHE_KEY, mergeBase: OTHER_MERGE_BASE })
).toBeUndefined()
})
it('starts the ranged diff before waiting on the per-area numstat', async () => {
const order: string[] = []
let releaseRecompute = (): void => {}
const recomputeGate = new Promise<void>((resolve) => {
releaseRecompute = resolve
})
const pending = reuseOrRecomputeGitStatusLineStats({
cacheKey: CACHE_KEY,
head: 'head-1',
entries: entries(),
writeToken: beginGitStatusLineStatsCacheWrite(CACHE_KEY),
reuse: false,
isAborted: () => false,
recompute: async () => {
order.push('recompute')
await recomputeGate
return true
},
branchLineTotal: {
mergeBase: MERGE_BASE,
compute: async () => {
order.push('compute')
return TOTAL
}
}
})
releaseRecompute()
expect(await pending).toEqual({ branchLineTotal: TOTAL })
expect(order).toEqual(['compute', 'recompute'])
})
it('keeps the exact total when the per-area numstat pass failed', async () => {
const result = await reuseOrRecomputeGitStatusLineStats({
cacheKey: CACHE_KEY,
head: 'head-1',
entries: entries(),
writeToken: beginGitStatusLineStatsCacheWrite(CACHE_KEY),
reuse: false,
isAborted: () => false,
recompute: async () => false,
branchLineTotal: { mergeBase: MERGE_BASE, compute: async () => TOTAL }
})
expect(result).toEqual({ branchLineTotal: TOTAL })
// The incomplete pass stays uncacheable, so nothing was pinned for reuse.
expect(
applyCachedGitStatusLineStats({ cacheKey: CACHE_KEY, head: 'head-1', entries: entries() })
).toBe(false)
})
it('omits the field entirely when the total could not be known exact', async () => {
const result = await reuseOrRecomputeGitStatusLineStats({
cacheKey: CACHE_KEY,
head: 'head-1',
entries: entries(4),
writeToken: beginGitStatusLineStatsCacheWrite(CACHE_KEY),
reuse: false,
isAborted: () => false,
recompute: async () => true,
branchLineTotal: { mergeBase: MERGE_BASE, compute: async () => undefined }
})
expect(result).toEqual({})
expect('branchLineTotal' in result).toBe(false)
expect(readCachedGitBranchLineTotal({ cacheKey: CACHE_KEY, mergeBase: MERGE_BASE })).toBe(
undefined
)
})
it('rejects instead of returning a partial total when the pass aborts mid-diff', async () => {
let aborted = false
await expect(
reuseOrRecomputeGitStatusLineStats({
cacheKey: CACHE_KEY,
head: 'head-1',
entries: entries(),
writeToken: beginGitStatusLineStatsCacheWrite(CACHE_KEY),
reuse: false,
isAborted: () => aborted,
recompute: async () => true,
branchLineTotal: {
mergeBase: MERGE_BASE,
compute: async () => {
aborted = true
const error = new Error('The operation was aborted.')
error.name = 'AbortError'
throw error
}
}
})
).rejects.toMatchObject({ name: 'AbortError' })
expect(readCachedGitBranchLineTotal({ cacheKey: CACHE_KEY, mergeBase: MERGE_BASE })).toBe(
undefined
)
})
it('rejects a reuse hit whose backfill compute is aborted', async () => {
seedSnapshot()
let aborted = false
await expect(
reuseOrRecomputeGitStatusLineStats({
cacheKey: CACHE_KEY,
head: 'head-1',
entries: entries(),
writeToken: beginGitStatusLineStatsCacheWrite(CACHE_KEY),
reuse: true,
isAborted: () => aborted,
recompute: async () => true,
branchLineTotal: {
mergeBase: MERGE_BASE,
compute: async () => {
aborted = true
return TOTAL
}
}
})
).rejects.toMatchObject({ name: 'AbortError' })
})
})
+158 -62
View File
@@ -1,3 +1,19 @@
import { settleGitBranchLineTotalWithinSoftDeadline } from './git-branch-line-total'
import {
beginGitStatusLineStatsCacheWrite,
bumpGitStatusLineStatsKeyGeneration,
isWriteTokenCurrent,
markGitStatusLineStatsStored,
resetGitStatusLineStatsWriteGenerations,
type GitStatusLineStatsWriteToken
} from './git-status-line-stats-write-token'
import type { GitBranchLineTotal } from './git-status-types'
export {
beginGitStatusLineStatsCacheWrite,
type GitStatusLineStatsWriteToken
} from './git-status-line-stats-write-token'
type GitStatusLineStatsEntry = {
path?: unknown
status?: unknown
@@ -19,13 +35,10 @@ type CachedLineStats = {
identity: string
storedAt: number
stats: { added?: number; removed?: number }[]
}
export type GitStatusLineStatsWriteToken = {
cacheKey: string
globalGeneration: number
keyGeneration: number
beginSeq: number
// Why: the branch total is derived from the same tree snapshot as the entry
// stats, so it must share their reuse lifecycle — a poll that reuses line
// stats must reuse the total rather than re-running the ranged diff.
branchLineTotal?: GitBranchLineTotal
}
// Why: the TTL is the sole staleness backstop when file contents change while
@@ -33,50 +46,11 @@ export type GitStatusLineStatsWriteToken = {
// reuse identity), so a missed watcher signal pins counts for at most this long.
export const GIT_STATUS_LINE_STATS_CACHE_MAX_AGE_MS = 2 * 60_000
const GIT_STATUS_LINE_STATS_CACHE_MAX_ENTRIES = 128
const GIT_STATUS_LINE_STATS_WRITE_KEYS_MAX_ENTRIES = 1024
const lineStatsByWorktree = new Map<string, CachedLineStats>()
// Why: mutation invalidation must retire scans that began before it. A scan
// captures these generations at begin; a mismatch at store/clear time means an
// invalidation happened mid-scan and the derived stats may be pre-mutation.
let globalInvalidationGeneration = 0
const keyInvalidationGenerationByWorktree = new Map<string, number>()
// Why: overlapping recomputes must resolve latest-begun-wins without letting a
// reuse-only read (which never stores) starve an older recompute's store.
const lastStoredBeginSeqByWorktree = new Map<string, number>()
let nextBeginSeq = 0
// Why: wall-clock steps (NTP, VM resume) must not extend or shrink the TTL.
const monotonicNowMs = (): number => performance.now()
function bumpBoundedKeyMap(map: Map<string, number>, cacheKey: string, value: number): void {
map.delete(cacheKey)
map.set(cacheKey, value)
while (map.size > GIT_STATUS_LINE_STATS_WRITE_KEYS_MAX_ENTRIES) {
const oldestKey = map.keys().next().value
if (oldestKey === undefined) {
return
}
map.delete(oldestKey)
}
}
export function beginGitStatusLineStatsCacheWrite(cacheKey: string): GitStatusLineStatsWriteToken {
return {
cacheKey,
globalGeneration: globalInvalidationGeneration,
keyGeneration: keyInvalidationGenerationByWorktree.get(cacheKey) ?? 0,
beginSeq: ++nextBeginSeq
}
}
function isWriteTokenCurrent(token: GitStatusLineStatsWriteToken): boolean {
return (
token.globalGeneration === globalInvalidationGeneration &&
token.keyGeneration === (keyInvalidationGenerationByWorktree.get(token.cacheKey) ?? 0) &&
token.beginSeq >= (lastStoredBeginSeqByWorktree.get(token.cacheKey) ?? 0)
)
}
function createInputIdentity(head: string | undefined, entries: GitStatusLineStatsEntry[]): string {
return JSON.stringify([
head ?? null,
@@ -143,27 +117,72 @@ export function applyCachedGitStatusLineStats(input: {
return true
}
/**
* Only valid immediately after `applyCachedGitStatusLineStats` returned true —
* that call is what proves the snapshot is fresh and matches this scan's
* entries. The merge base must match too, or the total describes a fork point
* this scan is no longer comparing against.
*/
export function readCachedGitBranchLineTotal(input: {
cacheKey: string
mergeBase: string
}): GitBranchLineTotal | undefined {
const total = lineStatsByWorktree.get(input.cacheKey)?.branchLineTotal
return total?.mergeBase === input.mergeBase ? total : undefined
}
/**
* Backfills a total onto a snapshot that was reused for its entry stats. Purely
* additive, so unlike a full store it must not retire older in-flight scans.
*/
export function updateCachedGitBranchLineTotal(input: {
cacheKey: string
head?: string
entries: GitStatusLineStatsEntry[]
branchLineTotal: GitBranchLineTotal
writeToken: GitStatusLineStatsWriteToken
}): void {
if (!isWriteTokenCurrent(input.writeToken)) {
return
}
const cached = lineStatsByWorktree.get(input.cacheKey)
if (!cached || cached.identity !== createInputIdentity(input.head, input.entries)) {
return
}
cached.branchLineTotal = input.branchLineTotal
}
export function storeGitStatusLineStats(input: {
cacheKey: string
head?: string
entries: GitStatusLineStatsEntry[]
now?: number
writeToken?: GitStatusLineStatsWriteToken
branchLineTotal?: GitBranchLineTotal
}): void {
const writeToken = input.writeToken ?? beginGitStatusLineStatsCacheWrite(input.cacheKey)
if (!isWriteTokenCurrent(writeToken)) {
return
}
bumpBoundedKeyMap(lastStoredBeginSeqByWorktree, input.cacheKey, writeToken.beginSeq)
markGitStatusLineStatsStored(input.cacheKey, writeToken.beginSeq)
const now = input.now ?? monotonicNowMs()
const identity = createInputIdentity(input.head, input.entries)
// Why: a total that missed its soft deadline lands here later; an unchanged
// snapshot must carry it forward or the next recompute would drop it and the
// chip could never appear on a repo where the diff is always slow.
const previous = lineStatsByWorktree.get(input.cacheKey)
const branchLineTotal =
input.branchLineTotal ??
(previous?.identity === identity ? previous.branchLineTotal : undefined)
lineStatsByWorktree.delete(input.cacheKey)
lineStatsByWorktree.set(input.cacheKey, {
identity: createInputIdentity(input.head, input.entries),
identity,
storedAt: now,
stats: input.entries.map((entry) => ({
...(entry.added === undefined ? {} : { added: entry.added }),
...(entry.removed === undefined ? {} : { removed: entry.removed })
}))
})),
...(branchLineTotal === undefined ? {} : { branchLineTotal })
})
trimLineStatsCache(now)
}
@@ -189,7 +208,12 @@ export async function reuseOrRecomputeGitStatusLineStats(input: {
reuse: boolean
isAborted: () => boolean
recompute: () => Promise<boolean>
}): Promise<void> {
/** Omitted when the caller did not ask for a branch total, which costs nothing. */
branchLineTotal?: {
mergeBase: string
compute: () => Promise<GitBranchLineTotal | undefined>
}
}): Promise<{ branchLineTotal?: GitBranchLineTotal }> {
if (input.isAborted()) {
// Why: reject rather than resolve — a cancelled scan must not look like a
// completed status result (including a cache-hit reuse path).
@@ -206,9 +230,26 @@ export async function reuseOrRecomputeGitStatusLineStats(input: {
if (input.isAborted()) {
throw createGitStatusLineStatsAbortError()
}
return
return reuseCachedBranchLineTotal(input)
}
// Why: started before the await below so both diffs run concurrently, and
// pre-caught so an aborted total can never surface as an unhandled rejection
// when recompute rejects first.
const totalPromise = input.branchLineTotal?.compute().catch(() => undefined)
const complete = await input.recompute()
const branchLineTotal = totalPromise
? await settleGitBranchLineTotalWithinSoftDeadline({
total: totalPromise,
onLateArrival: (late) =>
updateCachedGitBranchLineTotal({
cacheKey: input.cacheKey,
head: input.head,
entries: input.entries,
branchLineTotal: late,
writeToken: input.writeToken
})
})
: undefined
if (input.isAborted()) {
// Why: an aborted pass never reached storeGitStatusLineStats, so there is
// nothing partial to undo; clearing here would instead evict a concurrent
@@ -217,21 +258,80 @@ export async function reuseOrRecomputeGitStatusLineStats(input: {
throw createGitStatusLineStatsAbortError()
}
if (!complete) {
return
// Why: the total comes from its own ranged diff, so a failed per-area
// numstat leaves it exact even though the entry stats are uncacheable.
return branchLineTotal === undefined ? {} : { branchLineTotal }
}
storeGitStatusLineStats({
cacheKey: input.cacheKey,
head: input.head,
entries: input.entries,
writeToken: input.writeToken
writeToken: input.writeToken,
...(branchLineTotal === undefined ? {} : { branchLineTotal })
})
if (!input.branchLineTotal) {
return {}
}
// Why: read back rather than return the local — the store carries forward a
// total that arrived late on an unchanged snapshot, which is the only way the
// chip ever appears where the diff always outruns the soft deadline.
const published = readCachedGitBranchLineTotal({
cacheKey: input.cacheKey,
mergeBase: input.branchLineTotal.mergeBase
})
return published === undefined ? {} : { branchLineTotal: published }
}
async function reuseCachedBranchLineTotal(input: {
cacheKey: string
head?: string
entries: GitStatusLineStatsEntry[]
writeToken: GitStatusLineStatsWriteToken
isAborted: () => boolean
branchLineTotal?: {
mergeBase: string
compute: () => Promise<GitBranchLineTotal | undefined>
}
}): Promise<{ branchLineTotal?: GitBranchLineTotal }> {
if (!input.branchLineTotal) {
return {}
}
const cached = readCachedGitBranchLineTotal({
cacheKey: input.cacheKey,
mergeBase: input.branchLineTotal.mergeBase
})
if (cached) {
return { branchLineTotal: cached }
}
// The snapshot predates this feature or was computed against another fork
// point; compute once and backfill so the next reuse hit is free. A reuse pass
// exists to be cheap, so it waits no longer than any other for the diff.
const backfill = (late: GitBranchLineTotal): void => {
updateCachedGitBranchLineTotal({
cacheKey: input.cacheKey,
head: input.head,
entries: input.entries,
branchLineTotal: late,
writeToken: input.writeToken
})
}
const branchLineTotal = await settleGitBranchLineTotalWithinSoftDeadline({
total: input.branchLineTotal.compute().catch(() => undefined),
onLateArrival: backfill
})
if (input.isAborted()) {
throw createGitStatusLineStatsAbortError()
}
if (branchLineTotal === undefined) {
return {}
}
backfill(branchLineTotal)
return { branchLineTotal }
}
export function clearGitStatusLineStatsCache(): void {
globalInvalidationGeneration += 1
lineStatsByWorktree.clear()
keyInvalidationGenerationByWorktree.clear()
lastStoredBeginSeqByWorktree.clear()
resetGitStatusLineStatsWriteGenerations()
}
export function clearGitStatusLineStatsCacheKey(
@@ -242,15 +342,11 @@ export function clearGitStatusLineStatsCacheKey(
return
}
if (writeToken === undefined) {
bumpBoundedKeyMap(
keyInvalidationGenerationByWorktree,
cacheKey,
(keyInvalidationGenerationByWorktree.get(cacheKey) ?? 0) + 1
)
bumpGitStatusLineStatsKeyGeneration(cacheKey)
} else {
// Why: a token-scoped purge must retire scans that began before it, so an
// older in-flight scan can't store pre-purge counts and repopulate this key.
bumpBoundedKeyMap(lastStoredBeginSeqByWorktree, cacheKey, writeToken.beginSeq)
markGitStatusLineStatsStored(cacheKey, writeToken.beginSeq)
}
lineStatsByWorktree.delete(cacheKey)
}
@@ -0,0 +1,69 @@
/**
* Generation bookkeeping that decides whether a git-status line-stats scan may
* still write. Split from the cache itself so the snapshot store stays readable.
*/
export type GitStatusLineStatsWriteToken = {
cacheKey: string
globalGeneration: number
keyGeneration: number
beginSeq: number
}
const GIT_STATUS_LINE_STATS_WRITE_KEYS_MAX_ENTRIES = 1024
// Why: mutation invalidation must retire scans that began before it. A scan
// captures these generations at begin; a mismatch at store/clear time means an
// invalidation happened mid-scan and the derived stats may be pre-mutation.
let globalInvalidationGeneration = 0
const keyInvalidationGenerationByWorktree = new Map<string, number>()
// Why: overlapping recomputes must resolve latest-begun-wins without letting a
// reuse-only read (which never stores) starve an older recompute's store.
const lastStoredBeginSeqByWorktree = new Map<string, number>()
let nextBeginSeq = 0
function bumpBoundedKeyMap(map: Map<string, number>, cacheKey: string, value: number): void {
map.delete(cacheKey)
map.set(cacheKey, value)
while (map.size > GIT_STATUS_LINE_STATS_WRITE_KEYS_MAX_ENTRIES) {
const oldestKey = map.keys().next().value
if (oldestKey === undefined) {
return
}
map.delete(oldestKey)
}
}
export function beginGitStatusLineStatsCacheWrite(cacheKey: string): GitStatusLineStatsWriteToken {
return {
cacheKey,
globalGeneration: globalInvalidationGeneration,
keyGeneration: keyInvalidationGenerationByWorktree.get(cacheKey) ?? 0,
beginSeq: ++nextBeginSeq
}
}
export function isWriteTokenCurrent(token: GitStatusLineStatsWriteToken): boolean {
return (
token.globalGeneration === globalInvalidationGeneration &&
token.keyGeneration === (keyInvalidationGenerationByWorktree.get(token.cacheKey) ?? 0) &&
token.beginSeq >= (lastStoredBeginSeqByWorktree.get(token.cacheKey) ?? 0)
)
}
export function markGitStatusLineStatsStored(cacheKey: string, beginSeq: number): void {
bumpBoundedKeyMap(lastStoredBeginSeqByWorktree, cacheKey, beginSeq)
}
export function bumpGitStatusLineStatsKeyGeneration(cacheKey: string): void {
bumpBoundedKeyMap(
keyInvalidationGenerationByWorktree,
cacheKey,
(keyInvalidationGenerationByWorktree.get(cacheKey) ?? 0) + 1
)
}
export function resetGitStatusLineStatsWriteGenerations(): void {
globalInvalidationGeneration += 1
keyInvalidationGenerationByWorktree.clear()
lastStoredBeginSeqByWorktree.clear()
}
+101
View File
@@ -0,0 +1,101 @@
type StatusReadEntry<T> = {
controller: AbortController
promise: Promise<T>
liveLeases: number
settled: boolean
}
function getAbortReason(signal: AbortSignal): unknown {
try {
signal.throwIfAborted()
} catch (error) {
return error
}
return new DOMException('This operation was aborted', 'AbortError')
}
export class GitStatusReadLeaseOwner<T> {
private readonly entries = new Map<string, StatusReadEntry<T>>()
lease(
key: string,
signal: AbortSignal | undefined,
load: (sharedSignal: AbortSignal) => Promise<T>
): Promise<T> {
if (signal?.aborted) {
return Promise.reject(getAbortReason(signal))
}
let entry = this.entries.get(key)
if (!entry) {
const controller = new AbortController()
const promise = load(controller.signal)
const createdEntry = { controller, promise, liveLeases: 0, settled: false }
entry = createdEntry
this.entries.set(key, createdEntry)
void promise.then(
() => this.settle(key, createdEntry),
() => this.settle(key, createdEntry)
)
}
entry.liveLeases += 1
return this.createLease(key, entry, signal)
}
invalidate(): void {
this.entries.clear()
}
private createLease(
key: string,
entry: StatusReadEntry<T>,
signal: AbortSignal | undefined
): Promise<T> {
return new Promise<T>((resolve, reject) => {
let active = true
const release = (abortReason?: unknown): boolean => {
if (!active) {
return false
}
active = false
signal?.removeEventListener('abort', onAbort)
entry.liveLeases -= 1
if (abortReason !== undefined && entry.liveLeases === 0 && !entry.settled) {
if (this.entries.get(key) === entry) {
this.entries.delete(key)
}
entry.controller.abort(abortReason)
}
return true
}
const onAbort = (): void => {
const reason = getAbortReason(signal!)
if (release(reason)) {
reject(reason)
}
}
signal?.addEventListener('abort', onAbort, { once: true })
void entry.promise.then(
(value) => {
if (release()) {
resolve(value)
}
},
(error: unknown) => {
if (release()) {
reject(error)
}
}
)
})
}
private settle(key: string, entry: StatusReadEntry<T>): void {
entry.settled = true
if (this.entries.get(key) === entry) {
this.entries.delete(key)
}
}
}
+12
View File
@@ -52,6 +52,15 @@ export type GitUncommittedEntry = {
export type GitStatusEntry = GitUncommittedEntry
// `mergeBase(base, HEAD) → working tree`, deduplicated, so committing doesn't move it.
// Matches the per-file rows rather than git: binary and >2MB untracked count zero.
// `mergeBase` is echoed so a renderer can drop a moved fork point.
export type GitBranchLineTotal = {
added: number
removed: number
mergeBase: string
}
export type GitStatusResult = {
entries: GitStatusEntry[]
conflictOperation: GitConflictOperation
@@ -69,6 +78,9 @@ export type GitStatusResult = {
// "too many changes" state.
didHitLimit?: boolean
statusLength?: number
// Only computed when the request carried a merge-base OID (the renderer's
// visibility gate), and omitted — never zeroed — whenever it cannot be trusted.
branchLineTotal?: GitBranchLineTotal
}
// Why: when hasUpstream is false, ahead/behind are placeholder zeros, not a