perf(host): cwd 解析加在飞去重与 TTL 对齐、numstat 加 pathspec 与输出上限

src/active-worktree.ts 是 v0.25 新文件,却插进了 12 条 /sidebar/* 路由共用的
cwdOf():实测每次缓存未命中 9.6–44.7ms、1–4 次真实 git spawn,而 TTL 3s 与客户端
新的 5s 每-tab 轮询错配——每次轮询必然未命中。

- active-worktree:(session, base) 整链与 base 探针都加在飞去重(并发 8 次只 spawn
  一次);ACTIVE_ROOT_TTL_MS 3s→15s(跟随 worktree 的延迟代价写进注释);三个模块级
  缓存加 LRU 上界 512/512/256,负结果仍缓存但可淘汰。
- git.ts:两条 --numstat 加 pathspec(非 ?? 路径 + R/C 的 origin,必须
  --literal-pathspecs;未跟踪路径不参与 ⇒ 未忽略的大目录从两条全仓库 diff 变成零条;
  路径超 8KB 回退整仓库 diff)、runGit 加 8MiB 输出上限、状态行上限改在产出侧生效。
- fs-tree:折叠探测每层封顶 32 且截断层不探测(折叠是纯装饰)。
- index.ts:单层 fs.tree 补 ProbeGate;teardown 主动关闭三个 noServer WSS 的已接受
  连接(ws@8 的 close() 不终止在连 socket,句柄会活到浏览器断开)。
- sidechat-routes:冷线程日志按 (childId, revision, size) memo(16 线程,句柄照旧
  open/close,只有结果被缓存)。
- agent-opens:每会话队列封顶 64,最旧的丢弃,FIFO 与 drainAll 语义不变。

测试:扩展 active-worktree / git-worktree / fs-tree-probe-gate / sidechat-routes /
smoke / agent-opens;14 项「临时回退→变红→还原」突变全部被捕获。
This commit is contained in:
Menghuan1918 committed 2026-10-15 23:05:32 +08:00
1 parent 43742be658
commit 3e5576ffbb
12 files changed
+1005 -43

No files matched your search

+163 -9
View File
@@ -243,14 +243,49 @@ export function parseLogLines(output: string): GitLogEntry[] {
return rows
}
/**
* Hard ceiling on one git command's stdout. A runaway command — a whole-repo
* `diff` with no pathspec (the shape a repository with an unignored nested
* `node_modules` produced: 59 631 entries / 9.24 MB), a `show` of a generated
* file — must not be accumulated into an unbounded JS string. Exceeding it
* kills the child and rejects with the ordinary {@link GitCommandError} shape;
* callers that treat a git failure as "no answer" (the numstat sides, blame)
* keep their existing fallback.
*/
const GIT_OUTPUT_MAX_BYTES = 8 * 1024 * 1024
/** Per-command knobs of {@link runGit}. */
export interface RunGitOptions {
/** Stdout ceiling in bytes; exceeding it kills the child and rejects. */
maxBytes?: number
/**
* Number of NUL-framed fields after which the child is killed and the output
* produced SO FAR resolves — the caller's row cap made real during
* production instead of after parsing. One field is one row, but a
* rename/copy record costs TWO (its new name and its origin), so a caller
* that must never cut a row off early passes twice its row cap; a torn tail
* is fine, {@link parsePorcelainZ} already tolerates one.
*/
maxNulFields?: number
}
/** Count the NUL bytes of one stdout chunk (the `-z` field separator). */
function countNulFields(chunk: Buffer): number {
let count = 0
for (let at = chunk.indexOf(0); at !== -1; at = chunk.indexOf(0, at + 1)) count += 1
return count
}
/** Run one git command; resolves with stdout, rejects with GitCommandError. */
export function runGit(cwd: string, args: string[], timeoutMs = 30_000): Promise<string> {
export function runGit(cwd: string, args: string[], timeoutMs = 30_000, options: RunGitOptions = {}): Promise<string> {
// `core.quotePath=false`: emit paths verbatim instead of C-quoting them
// (git's default turns a CJK/space path into an octal-escaped, quoted
// string, and every diff surface renders that string as the file name).
// The `-z`-framed porcelain callers are unaffected: git never quotes
// NUL-framed output.
const full = ['-C', cwd, '--no-pager', '-c', 'color.ui=false', '-c', 'core.quotePath=false', ...args]
const maxBytes = options.maxBytes ?? GIT_OUTPUT_MAX_BYTES
const maxNulFields = options.maxNulFields
return new Promise<string>((resolvePromise, reject) => {
const child = spawn('git', full, {
stdio: ['ignore', 'pipe', 'pipe'],
@@ -258,12 +293,37 @@ export function runGit(cwd: string, args: string[], timeoutMs = 30_000): Promise
env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' },
})
let stdout = ''
let outBytes = 0
let outFields = 0
let stderr = ''
// Set when the caller's row cap stopped production: the partial answer is
// then the answer, and the killed child's non-zero exit must not be
// reported as a git failure of its own.
let fieldCapped = false
const timer = setTimeout(() => {
child.kill('SIGKILL')
reject(new GitCommandError(`git ${args[0] ?? ''} timed out after ${timeoutMs}ms`, 'git-error', args.join(' ')))
}, timeoutMs)
child.stdout.on('data', (chunk: Buffer) => { stdout += chunk.toString('utf8') })
child.stdout.on('data', (chunk: Buffer) => {
stdout += chunk.toString('utf8')
outBytes += chunk.length
if (outBytes > maxBytes) {
child.kill('SIGKILL')
reject(new GitCommandError(
`git ${args[0] ?? ''} output exceeded ${maxBytes} bytes`,
'git-error',
args.join(' '),
))
return
}
if (maxNulFields !== undefined) {
outFields += countNulFields(chunk)
if (outFields >= maxNulFields) {
fieldCapped = true
child.kill('SIGKILL')
}
}
})
child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') })
child.on('error', (error) => {
clearTimeout(timer)
@@ -271,7 +331,7 @@ export function runGit(cwd: string, args: string[], timeoutMs = 30_000): Promise
})
child.on('close', (code) => {
clearTimeout(timer)
if (code === 0) {
if (fieldCapped || code === 0) {
resolvePromise(stdout)
} else {
reject(new GitCommandError(stderr.trim() || `git exited with ${String(code)}`, 'git-error', args.join(' ')))
@@ -487,6 +547,16 @@ export async function currentBranch(cwd: string): Promise<string> {
* freeze the browser main thread on JSON parse or list render (#369). */
const GIT_STATUS_LIMIT = 2_000
/**
* NUL-field budget of the status read (the row cap enforced while git is
* producing, not after parsing a megabyte of untracked paths). Porcelain
* frames one field per row and TWO per rename/copy record, so the budget is
* twice the row cap: at least `GIT_STATUS_LIMIT + 1` ROWS always fit, which is
* what keeps the truncation flag honest for a rename-heavy tree, while a
* 59k-entry untracked walk is still stopped after ~200 KB instead of 9 MB.
*/
const GIT_STATUS_MAX_FIELDS = (GIT_STATUS_LIMIT + 1) * 2
/**
* Fold one path's counts from both numstat sides into a running map. A file
* changed in the index AND in the worktree is measured on each side against
@@ -511,6 +581,59 @@ function addLineCounts(into: Map<string, GitLineCounts>, from: Map<string, GitLi
}
}
/** Byte budget one numstat pathspec may carry (well under every platform's
* command-line cap, so a repository with thousands of tracked modifications
* falls back to the whole-repo diff instead of failing to spawn). */
const NUMSTAT_PATHSPEC_MAX_BYTES = 8_000
/**
* The paths the two `--numstat` diffs of {@link status} actually have to look
* at, read from the SAME porcelain output:
*
* - every reported path EXCEPT untracked ones (`??`): a file absent from the
* index exists on neither diff side, so git can never print a numstat row
* for it — and in the pathological case (an unignored nested
* `node_modules`) those are 59k of the 59k paths, i.e. all of the argv;
* - the ORIGIN path of every rename/copy record (the next NUL field): a
* pathspec that keeps only the new name hides the pair from git's rename
* detection, and the counts silently degrade from `0 0` to a full-file add.
*
* `[]` means "no tracked change at all": both diffs are guaranteed empty and
* the caller skips the two processes entirely. `undefined` means the set is
* too large to spell out on a command line (Windows caps one at ~32k chars) —
* the caller falls back to the unpathspec'd whole-repo diff, which is the old
* behaviour, not a wrong answer.
*/
function numstatPathsof(porcelainZ: string): string[] | undefined {
const fields = porcelainZ.split('\0')
const paths: string[] = []
let bytes = 0
const add = (path: string): boolean => {
if (path === '') return true
bytes += Buffer.byteLength(path) + 1
if (bytes > NUMSTAT_PATHSPEC_MAX_BYTES) return false
paths.push(path)
return true
}
let index = 0
while (index < fields.length) {
const field = fields[index]!
index += 1
if (field === '') continue
const xy = field.slice(0, 2)
// A torn tail (the row cap kills the child mid-record) has no path.
const path = field.slice(3)
if (path === '' || xy === '??') continue
if (!add(path)) return undefined
if (xy[0] === 'R' || xy[0] === 'C') {
const origin = fields[index]
index += 1
if (origin !== undefined && !add(origin)) return undefined
}
}
return paths
}
/**
* Working-tree status (untracked included). `--untracked-files=all` lists
* the contents of new directories as individual entries, while preserving
@@ -521,18 +644,49 @@ function addLineCounts(into: Map<string, GitLineCounts>, from: Map<string, GitLi
* per file, and callers keep their existing refresh cadence. A numstat failure
* costs only the counts (the rows fall back to their count-less rendering) —
* the status answer itself must never fail because of it.
*
* The porcelain read now comes FIRST, because its paths become the pathspec of
* both numstat diffs: the counts only ever ride rows the status read itself
* reports, and limiting the diffs to those paths is what keeps an unignored
* nested `node_modules` (59 631 entries / 9.24 MB of numstat) out of the two
* whole-repo walks. `--literal-pathspecs` is required: porcelain paths are
* literal file names, and without it a name like `:colon.txt` is parsed as
* pathspec magic and silently loses its counts.
*/
export async function status(cwd: string, selected?: string): Promise<GitStatusResult> {
const repositories = await repoRoots(cwd)
if (repositories.length === 0) return { isRepo: false, entries: [], repositories: [] }
const root = await repoRoot(cwd, selected)
const [branch, raw, unstagedNumstat, stagedNumstat] = await Promise.all([
currentBranch(root).catch(() => 'HEAD'),
runGit(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all']),
runGit(root, ['diff', '--numstat', '-z']).catch(() => ''),
runGit(root, ['diff', '--cached', '--numstat', '-z']).catch(() => ''),
])
const branchPromise = currentBranch(root).catch(() => 'HEAD')
const raw = await runGit(
root,
['status', '--porcelain=v1', '-z', '--untracked-files=all'],
undefined,
// The row cap is enforced while git is still producing, not after parsing
// a megabyte of untracked paths: see {@link GIT_STATUS_MAX_FIELDS}.
{ maxNulFields: GIT_STATUS_MAX_FIELDS },
)
const parsed = parsePorcelainZ(raw)
const pathspec = numstatPathsof(raw)
let unstagedNumstat = ''
let stagedNumstat = ''
// `undefined` = too many paths to spell out on one command line (fall back
// to the whole-repo diff); `[]` = no tracked change at all, so both diffs are
// known empty and neither process is spawned.
if (pathspec === undefined || pathspec.length > 0) {
// `--literal-pathspecs` must precede the subcommand (`git <flag> diff …`).
// Porcelain paths are literal file names, and without it a name like
// `:colon.txt` is parsed as pathspec magic and silently loses its counts.
const literal = pathspec === undefined ? [] : ['--literal-pathspecs']
const paths = pathspec === undefined ? [] : ['--', ...pathspec]
const [unstaged, staged] = await Promise.all([
runGit(root, [...literal, 'diff', '--numstat', '-z', ...paths]).catch(() => ''),
runGit(root, [...literal, 'diff', '--cached', '--numstat', '-z', ...paths]).catch(() => ''),
])
unstagedNumstat = unstaged
stagedNumstat = staged
}
const branch = await branchPromise
const lineCounts = new Map<string, GitLineCounts>()
addLineCounts(lineCounts, parseNumstat(stagedNumstat))
addLineCounts(lineCounts, parseNumstat(unstagedNumstat))