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:
1 parent
43742be658
commit
3e5576ffbb
12 files changed
+1005
-43
No files matched your search
+134
-18
@@ -17,8 +17,11 @@
|
||||
* newest event that has one wins; when there is no evidence the session cwd is
|
||||
* kept (lifted to the repository top level for subdirectory sessions).
|
||||
*
|
||||
* Resolutions are cached process-wide, so the client's periodic re-ask is
|
||||
* cheap after the first scan.
|
||||
* Resolutions are cached process-wide ({@link ACTIVE_ROOT_TTL_MS}), concurrent
|
||||
* callers share one in-flight resolution AND one in-flight base probe, and
|
||||
* every cache is bounded — so the client's periodic re-ask, the debounced
|
||||
* fs-watch frames and the twelve route handlers that funnel through
|
||||
* `cwdOf()` are answered without a process spawn after the first scan.
|
||||
*/
|
||||
import { stat } from 'node:fs/promises'
|
||||
import { dirname, isAbsolute, join, sep } from 'node:path'
|
||||
@@ -27,12 +30,27 @@ import { requireAbsolute } from './fs-tree.ts'
|
||||
import { runGit } from './git.ts'
|
||||
import { readPersistedSessionOf } from './session-store.ts'
|
||||
|
||||
/** How long one computed root is reused before the event log is scanned again. */
|
||||
const ACTIVE_ROOT_TTL_MS = 3_000
|
||||
/**
|
||||
* How long one computed root is reused before the event log is scanned again.
|
||||
*
|
||||
* 15 s, deliberately longer than the client's per-tab 5 s poll: at 3 s every
|
||||
* poll was a cache miss (one `git rev-parse --show-toplevel` spawn plus up to
|
||||
* 4 000 events of backlog scanning per ask, measured 9.6–44.7 ms), which is
|
||||
* the opposite of what this cache is for. The semantic cost of the longer TTL
|
||||
* is that a session which MOVES into a linked worktree is followed within at
|
||||
* most 15 s of the move (was 3 s) — every event-driven re-ask (fs-watch
|
||||
* frames, route calls, editor opens) is served from the cache in the meantime
|
||||
* and no refresh path is turned off.
|
||||
*/
|
||||
const ACTIVE_ROOT_TTL_MS = 15_000
|
||||
/** Only the newest slice of the event log is considered. */
|
||||
const ACTIVE_ROOT_MAX_EVENTS = 4_000
|
||||
/** Upper bound on git probes per scan (cache misses are what cost). */
|
||||
const ACTIVE_ROOT_MAX_PROBES = 24
|
||||
/** Bounds of the three process-wide caches below (LRU, oldest evicted first). */
|
||||
const PATH_TOP_CACHE_MAX = 512
|
||||
const LINKED_WORKTREE_CACHE_MAX = 512
|
||||
const ACTIVE_ROOT_CACHE_MAX = 256
|
||||
/** Explicit override, mainly for tests and manual pinning. */
|
||||
const ACTIVE_ROOT_OVERRIDE_ENV = 'DSH_SIDEBAR_WORKTREE_ROOT'
|
||||
/** Keys whose string values describe where a tool actually ran. */
|
||||
@@ -47,11 +65,47 @@ const ACTIVE_ROOT_PATH_PATTERN = /[A-Za-z]:(?:\\|\/)[^\\/\s"'\x60,;|)<>*?]+(?:[\
|
||||
* (measured ~7 ms), and the repeated asks every debounced watch frame, every
|
||||
* route call, the client's 5 s poll are exactly what the TTL exists to keep
|
||||
* free.
|
||||
*
|
||||
* All three maps are BOUNDED: a long-lived host (and a `keepMounted` right
|
||||
* sidebar that keeps asking about every session it has ever shown) would
|
||||
* otherwise grow them forever. `pathTopCache` caches negative answers too
|
||||
* (`undefined` = "no git top level here"), which is what keeps a non-repo
|
||||
* session cheap; those entries are evictable like any other.
|
||||
*/
|
||||
const activeWorktreeRootCache = new Map<string, { root: string; base: string; expires: number }>()
|
||||
const pathTopCache = new Map<string, string | undefined>()
|
||||
const linkedWorktreeCache = new Map<string, boolean>()
|
||||
|
||||
/**
|
||||
* In-flight de-duplication, mirroring `git.ts`'s `repoRootsInFlight`.
|
||||
*
|
||||
* `activeRootInFlight` collapses a burst of asks for the SAME (session, base)
|
||||
* into one resolution (one base spawn, one event scan); `topLevelInFlight`
|
||||
* collapses the base probe across DIFFERENT sessions that share a base (N tabs
|
||||
* of one workspace would otherwise spawn N `git rev-parse` processes at once).
|
||||
* Both delete their entry on the resolved AND the rejected path, so a failure
|
||||
* never poisons the map.
|
||||
*/
|
||||
const activeRootInFlight = new Map<string, Promise<string>>()
|
||||
const topLevelInFlight = new Map<string, Promise<string | undefined>>()
|
||||
|
||||
/**
|
||||
* Insert or refresh one cache entry, evicting the least recently used entry
|
||||
* once the cache holds more than `max`. Map iteration order is insertion
|
||||
* order, so deleting before setting moves the key to the young end — which is
|
||||
* what makes a HIT refresh recency (this is the repo's bounded-cache style
|
||||
* from `fs-tree.ts`'s `directoryCache`, with the recency touch added).
|
||||
*/
|
||||
function cachePut<K, V>(map: Map<K, V>, key: K, value: V, max: number): void {
|
||||
map.delete(key)
|
||||
map.set(key, value)
|
||||
while (map.size > max) {
|
||||
const oldest = map.keys().next().value
|
||||
if (oldest === undefined) break
|
||||
map.delete(oldest)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalized IDENTITY of a path (case- and separator-insensitive), for
|
||||
* comparisons and cache keys only: it lowercases, so it must never be handed
|
||||
@@ -82,6 +136,29 @@ async function gitTopLevelOf(cwd: string): Promise<string | undefined> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link gitTopLevelOf} with in-flight sharing per path identity: concurrent
|
||||
* asks for one directory (a route burst, or several sessions rooted in the
|
||||
* same repository) spawn ONE git process between them.
|
||||
*/
|
||||
function topLevelOf(cwd: string): Promise<string | undefined> {
|
||||
const key = pathKeyOf(cwd)
|
||||
const pending = topLevelInFlight.get(key)
|
||||
if (pending !== undefined) return pending
|
||||
const promise = gitTopLevelOf(cwd).then(
|
||||
(top) => {
|
||||
topLevelInFlight.delete(key)
|
||||
return top
|
||||
},
|
||||
(error: unknown) => {
|
||||
topLevelInFlight.delete(key)
|
||||
throw error
|
||||
},
|
||||
)
|
||||
topLevelInFlight.set(key, promise)
|
||||
return promise
|
||||
}
|
||||
|
||||
/** Collapse duplicated separators without destroying a UNC prefix. */
|
||||
function normalizeActivePath(value: string): string {
|
||||
const trimmed = value.replace(/[\\/]+$/, '')
|
||||
@@ -149,11 +226,18 @@ function collectActivePaths(value: unknown, map: Map<string, ActivePathEntry>, s
|
||||
/** git top level for one path (its directory when the path names a file). */
|
||||
async function topOfActivePath(value: string): Promise<string | undefined> {
|
||||
const key = pathKeyOf(value)
|
||||
if (pathTopCache.has(key)) return pathTopCache.get(key)
|
||||
let top = await gitTopLevelOf(value)
|
||||
if (top === undefined) top = await gitTopLevelOf(dirname(value))
|
||||
if (pathTopCache.has(key)) {
|
||||
const cached = pathTopCache.get(key)
|
||||
// A cached `undefined` ("not in a repository") is the answer that keeps a
|
||||
// non-repo session cheap, so it is re-inserted like any other hit — which
|
||||
// also refreshes its recency in the bounded LRU.
|
||||
cachePut(pathTopCache, key, cached, PATH_TOP_CACHE_MAX)
|
||||
return cached
|
||||
}
|
||||
let top = await topLevelOf(value)
|
||||
if (top === undefined) top = await topLevelOf(dirname(value))
|
||||
const result = top === undefined ? undefined : requireAbsolute(top)
|
||||
pathTopCache.set(key, result)
|
||||
cachePut(pathTopCache, key, result, PATH_TOP_CACHE_MAX)
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -165,7 +249,10 @@ async function topOfActivePath(value: string): Promise<string | undefined> {
|
||||
async function isLinkedWorktree(top: string): Promise<boolean> {
|
||||
const key = pathKeyOf(top)
|
||||
const cached = linkedWorktreeCache.get(key)
|
||||
if (cached !== undefined) return cached
|
||||
if (cached !== undefined) {
|
||||
cachePut(linkedWorktreeCache, key, cached, LINKED_WORKTREE_CACHE_MAX)
|
||||
return cached
|
||||
}
|
||||
let linked = false
|
||||
try {
|
||||
const out = (await runGit(top, ['rev-parse', '--absolute-git-dir', '--git-common-dir'])).trim().split(/\r?\n/)
|
||||
@@ -178,7 +265,10 @@ async function isLinkedWorktree(top: string): Promise<boolean> {
|
||||
} catch {
|
||||
linked = false
|
||||
}
|
||||
linkedWorktreeCache.set(key, linked)
|
||||
// `false` is a real answer ("the main checkout", "a submodule", "not a
|
||||
// repo") and is cached: the negative is what keeps a subdirectory session
|
||||
// from re-probing the same top level on every scan.
|
||||
cachePut(linkedWorktreeCache, key, linked, LINKED_WORKTREE_CACHE_MAX)
|
||||
return linked
|
||||
}
|
||||
|
||||
@@ -237,6 +327,11 @@ async function sessionEventsOf(ctx: Context, sessionId: string): Promise<readonl
|
||||
|
||||
/**
|
||||
* The directory the sidebar should treat as the session's root.
|
||||
*
|
||||
* The cache is consulted BEFORE the probe, and concurrent asks for the same
|
||||
* (session, base) share ONE in-flight resolution: twelve route handlers funnel
|
||||
* through `cwdOf()`, so a burst of parallel `/sidebar/*` calls used to spawn a
|
||||
* `git rev-parse` process per call.
|
||||
* @param ctx - host plugin context.
|
||||
* @param sessionId - session whose tool calls are inspected.
|
||||
* @param base - the authoritative session cwd (already resolved by the caller).
|
||||
@@ -246,23 +341,44 @@ export async function activeWorktreeRootOf(ctx: Context, sessionId: string, base
|
||||
if (base === '') return base
|
||||
const override = (process.env[ACTIVE_ROOT_OVERRIDE_ENV] ?? '').trim()
|
||||
if (override !== '' && isAbsolute(override)) return requireAbsolute(override)
|
||||
// The cache is consulted BEFORE the probe: doing it afterwards still pays the
|
||||
// spawn on every ask, which is the whole cost the TTL is there to avoid. The
|
||||
// comparison is on the raw base, so a session whose caller switched base (the
|
||||
// `/sidebar/*` routes pass the client's own) never reuses the other one's root.
|
||||
// The comparison is on the raw base, so a session whose caller switched base
|
||||
// (the `/sidebar/*` routes pass the client's own) never reuses the other
|
||||
// one's root.
|
||||
const cached = activeWorktreeRootCache.get(sessionId)
|
||||
if (cached !== undefined && cached.expires > Date.now() && cached.base === base) return cached.root
|
||||
const top = await gitTopLevelOf(base)
|
||||
if (cached !== undefined && cached.expires > Date.now() && cached.base === base) {
|
||||
cachePut(activeWorktreeRootCache, sessionId, cached, ACTIVE_ROOT_CACHE_MAX)
|
||||
return cached.root
|
||||
}
|
||||
const flightKey = `${sessionId}\0${base}`
|
||||
const pending = activeRootInFlight.get(flightKey)
|
||||
if (pending !== undefined) return pending
|
||||
const promise = resolveActiveWorktreeRoot(ctx, sessionId, base).then(
|
||||
(root) => {
|
||||
activeRootInFlight.delete(flightKey)
|
||||
return root
|
||||
},
|
||||
(error: unknown) => {
|
||||
activeRootInFlight.delete(flightKey)
|
||||
throw error
|
||||
},
|
||||
)
|
||||
activeRootInFlight.set(flightKey, promise)
|
||||
return promise
|
||||
}
|
||||
|
||||
/** One uncached resolution (see {@link activeWorktreeRootOf}). */
|
||||
async function resolveActiveWorktreeRoot(ctx: Context, sessionId: string, base: string): Promise<string> {
|
||||
const top = await topLevelOf(base)
|
||||
if (top === undefined) {
|
||||
// "Not inside a repository" is an answer too (the base itself), and caching
|
||||
// it is what keeps a non-repo session from re-probing on every ask.
|
||||
activeWorktreeRootCache.set(sessionId, { root: base, base, expires: Date.now() + ACTIVE_ROOT_TTL_MS })
|
||||
cachePut(activeWorktreeRootCache, sessionId, { root: base, base, expires: Date.now() + ACTIVE_ROOT_TTL_MS }, ACTIVE_ROOT_CACHE_MAX)
|
||||
return base
|
||||
}
|
||||
const canonicalTop = requireAbsolute(top)
|
||||
const effectiveBase = pathUnderOf(base, canonicalTop) ? base : canonicalTop
|
||||
const active = await activeRootFromEvents(await sessionEventsOf(ctx, sessionId), effectiveBase)
|
||||
const root = active ?? effectiveBase
|
||||
activeWorktreeRootCache.set(sessionId, { root, base, expires: Date.now() + ACTIVE_ROOT_TTL_MS })
|
||||
cachePut(activeWorktreeRootCache, sessionId, { root, base, expires: Date.now() + ACTIVE_ROOT_TTL_MS }, ACTIVE_ROOT_CACHE_MAX)
|
||||
return root
|
||||
}
|
||||
@@ -49,6 +49,15 @@ export interface AgentOpenRequest {
|
||||
/** One subscribed sidebar view's sender. */
|
||||
type Sender = (request: AgentOpenRequest) => void
|
||||
|
||||
/**
|
||||
* Cap on one session's queue of un-delivered opens. A session whose sidebar is
|
||||
* never shown (a long unattended run that keeps opening files) would otherwise
|
||||
* grow this array for the lifetime of the host process; past the cap the OLDEST
|
||||
* queued opens are dropped, so the newest intent survives and the order of what
|
||||
* remains is still FIFO.
|
||||
*/
|
||||
const AGENT_OPEN_QUEUE_MAX = 64
|
||||
|
||||
/**
|
||||
* Per-session queue of open requests plus the connected sidebar views.
|
||||
*
|
||||
@@ -70,6 +79,8 @@ export class AgentOpenRegistry {
|
||||
const request: AgentOpenRequest = { id: randomUUID(), sessionId, kind, target, title }
|
||||
const list = this.pending.get(sessionId) ?? []
|
||||
list.push(request)
|
||||
// Bounded per-session queue: drop the OLDEST queued opens past the cap.
|
||||
if (list.length > AGENT_OPEN_QUEUE_MAX) list.splice(0, list.length - AGENT_OPEN_QUEUE_MAX)
|
||||
this.pending.set(sessionId, list)
|
||||
const views = this.subscribers.get(sessionId)
|
||||
if (views !== undefined && views.size > 0) {
|
||||
|
||||
+23
-3
@@ -204,8 +204,10 @@ async function readDirectory(path: string, maxEntries: number, exclude?: Exclude
|
||||
await probeSymlinkTargets(rows, gate)
|
||||
// Mark singleton-directory rows AFTER the symlink probe (it finalizes
|
||||
// isDir/broken), so the client can fold compact chains without an extra
|
||||
// round trip per collapsed level.
|
||||
await probeCompactRows(rows, exclude, gate)
|
||||
// round trip per collapsed level. A TRUNCATED level is skipped entirely: the
|
||||
// rows on screen are a slice of a level too wide to be worth folding, and
|
||||
// the fold mark would be decided by the cap rather than by the directory.
|
||||
if (!truncated) await probeCompactRows(rows, exclude, gate)
|
||||
rows.sort(compareEntries)
|
||||
return { path, entries: rows, truncated }
|
||||
}
|
||||
@@ -312,6 +314,17 @@ async function probeSymlinkTargets(rows: SidebarFsEntry[], gate?: ProbeGate, con
|
||||
/** How many compact probes run in flight during one level listing. */
|
||||
const COMPACT_PROBE_CONCURRENCY = 32
|
||||
|
||||
/**
|
||||
* How many children of ONE level are probed for the singleton fold mark.
|
||||
*
|
||||
* Folding is decorative — it decides whether a row renders as `a/b/c` instead
|
||||
* of three rows — so a wide level must not pay one `opendir` per directory row:
|
||||
* a cold listing of a 100-directory level issued 100 syscalls to decorate rows
|
||||
* the user may never look at. Past this many ELIGIBLE directory rows the
|
||||
* remaining rows are simply left unmarked (an un-folded listing), in row order.
|
||||
*/
|
||||
const COMPACT_PROBE_MAX = 32
|
||||
|
||||
/**
|
||||
* Mark each directory row whose contents are EXACTLY one non-symlink child
|
||||
* (`compact`), so the explorer can fold singleton chains into one breadcrumb
|
||||
@@ -319,13 +332,20 @@ const COMPACT_PROBE_CONCURRENCY = 32
|
||||
* preloads marked levels to stabilize the fold label before expansion.
|
||||
* Bounded concurrency like the symlink probe: each probe is one opendir + up
|
||||
* to two dirent reads, so a directory-heavy level stays responsive. A shared
|
||||
* {@link ProbeGate} also keeps a whole batch's levels within one probe budget.
|
||||
* {@link ProbeGate} also keeps a whole batch's levels within one probe budget,
|
||||
* and at most {@link COMPACT_PROBE_MAX} rows of one level are probed at all.
|
||||
* Probe failures (unreadable child level) leave the row unmarked — it simply
|
||||
* does not fold.
|
||||
*/
|
||||
async function probeCompactRows(rows: SidebarFsEntry[], exclude?: ExcludeMatcher, gate?: ProbeGate, concurrency = COMPACT_PROBE_CONCURRENCY): Promise<void> {
|
||||
let probed = 0
|
||||
await forEachRow(rows, concurrency, async (row) => {
|
||||
if (!row.isDir || row.broken) return
|
||||
// The cap counts PROBES, not rows visited: rows the visitor skips (files,
|
||||
// broken links) cost nothing, and the increment happens before the await
|
||||
// so concurrent workers cannot overshoot it.
|
||||
if (probed >= COMPACT_PROBE_MAX) return
|
||||
probed += 1
|
||||
if (await runProbe(gate, () => hasSingletonChild(row.path, exclude))) row.compact = true
|
||||
})
|
||||
}
|
||||
|
||||
+163
-9
@@ -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))
|
||||
|
||||
+18
-4
@@ -688,7 +688,12 @@ function buildApi(
|
||||
// The client's explorerExclude pref rides the request (compiled here so
|
||||
// the listing and the singleton fold probe share one matcher).
|
||||
const exclude = compileExcludePatterns(record.exclude, cwd)
|
||||
return listDirectory(target, resolved.listLimit, exclude)
|
||||
// One request-wide probe gate, exactly like the batch route below: a
|
||||
// single-level listing bounds its own probe pools anyway (the shared
|
||||
// budget equals them on purpose — see PROBE_BUDGET), but building one
|
||||
// here keeps the two listing routes the same shape, so neither can ever
|
||||
// fan out per row without a budget.
|
||||
return listDirectory(target, resolved.listLimit, exclude, createProbeGate())
|
||||
},
|
||||
// Batch listing: one request for every level the tree has expanded, so a
|
||||
// mount/refresh costs one round trip instead of N. Each path rides the
|
||||
@@ -1796,9 +1801,18 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
|
||||
ctx.effect(() => () => {
|
||||
openToolsDisposers?.()
|
||||
agentOpenRegistry.dispose()
|
||||
agentOpenWss.close()
|
||||
fsWatchWss.close()
|
||||
sidechatWss.close()
|
||||
// `WebSocketServer.close()` on a `noServer` server only stops accepting
|
||||
// upgrades: with ws@8 an already-upgraded socket is NOT terminated (the
|
||||
// server just waits for it), so the accepted sockets must be closed
|
||||
// explicitly or every fs-watch `fs.watch` handle and the agent-opens
|
||||
// subscriber set survives the plugin unmount until the browser disconnects.
|
||||
// The sockets' own `close` handlers stay the ones releasing those
|
||||
// resources (they are idempotent, and a socket already closing ignores a
|
||||
// second close).
|
||||
for (const wss of [agentOpenWss, fsWatchWss, sidechatWss]) {
|
||||
for (const client of wss.clients) client.close()
|
||||
wss.close()
|
||||
}
|
||||
}, 'dsh-better-sidebar: teardown')
|
||||
}
|
||||
|
||||
|
||||
+89
-2
@@ -267,6 +267,94 @@ function liveThreadAgent(ctx: Context, childId: string): Agent | undefined {
|
||||
return agents?.get(childId)
|
||||
}
|
||||
|
||||
/**
|
||||
* The host's lightweight stored-session observation (`sessionPersistence.stat`),
|
||||
* read structurally: the plugin's own mirror of the service only models the
|
||||
* handle API, and a host without `stat` must degrade to an uncached read rather
|
||||
* than fail.
|
||||
*/
|
||||
interface SidebarStoredSessionStat {
|
||||
/** Opaque change token; the JSONL backend composes it from the file's
|
||||
* dev/ino/size/mtimeNs/ctimeNs, i.e. it changes iff the artifact does. */
|
||||
readonly revision?: unknown
|
||||
/** Physical artifact size in bytes, when the backend can provide it. */
|
||||
readonly sizeBytes?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Cold-thread log memo: how many THREADS keep their decoded log. The
|
||||
* transcript polls `sidechat.events` per open thread (15 s fallback, plus one
|
||||
* pull per push frame), so a handful of threads is the whole working set.
|
||||
*/
|
||||
const COLD_LOG_MEMO_MAX = 16
|
||||
const coldLogMemo = new Map<string, readonly SidechatLogEvent[]>()
|
||||
|
||||
/**
|
||||
* Read one COLD thread's persisted log, memoized by the stored artifact's
|
||||
* IDENTITY: `childId` plus the host's change token (dev/ino/size/mtimeNs/
|
||||
* ctimeNs) and the physical size.
|
||||
*
|
||||
* Why: a cold thread is re-read on every poll, and each read opens the handle,
|
||||
* decodes the ENTIRE persisted log and scans it back to `session/end-seed` —
|
||||
* O(thread history) per tick for an answer that only changes when the artifact
|
||||
* does. With the memo a repeat poll costs one `stat`.
|
||||
*
|
||||
* Only the RESULT is memoized, never the handle:
|
||||
* {@link readPersistedSession} still opens and closes it (its `finally`), so a
|
||||
* concurrent writer is unaffected. A host without `stat`, or a session whose
|
||||
* stat is unreadable, reads uncached — the read itself then reports the real
|
||||
* error (404 for a gone thread) exactly as before.
|
||||
*/
|
||||
async function readColdThreadLog(
|
||||
persistence: SidebarSessionPersistenceService,
|
||||
childId: string,
|
||||
): Promise<readonly SidechatLogEvent[]> {
|
||||
const identity = await storedIdentityOf(persistence, childId)
|
||||
if (identity === undefined) {
|
||||
return (await readPersistedSession(persistence, childId)).events as unknown as readonly SidechatLogEvent[]
|
||||
}
|
||||
const key = `${childId}\0${identity}`
|
||||
const hit = coldLogMemo.get(key)
|
||||
if (hit !== undefined) {
|
||||
// Refresh recency (the memo is a bounded LRU).
|
||||
coldLogMemo.delete(key)
|
||||
coldLogMemo.set(key, hit)
|
||||
return hit
|
||||
}
|
||||
const events = (await readPersistedSession(persistence, childId)).events as unknown as readonly SidechatLogEvent[]
|
||||
// One thread owns at most one entry: a changed artifact replaces the old
|
||||
// version instead of pinning a second copy of a potentially huge log.
|
||||
const prefix = `${childId}\0`
|
||||
for (const existing of coldLogMemo.keys()) {
|
||||
if (existing.startsWith(prefix)) coldLogMemo.delete(existing)
|
||||
}
|
||||
coldLogMemo.set(key, events)
|
||||
while (coldLogMemo.size > COLD_LOG_MEMO_MAX) {
|
||||
const oldest = coldLogMemo.keys().next().value
|
||||
if (oldest === undefined) break
|
||||
coldLogMemo.delete(oldest)
|
||||
}
|
||||
return events
|
||||
}
|
||||
|
||||
/** The stored artifact's change identity, or undefined when unavailable. */
|
||||
async function storedIdentityOf(
|
||||
persistence: SidebarSessionPersistenceService,
|
||||
childId: string,
|
||||
): Promise<string | undefined> {
|
||||
const stat = (persistence as { stat?: (id: string) => Promise<SidebarStoredSessionStat | undefined> }).stat
|
||||
if (typeof stat !== 'function') return undefined
|
||||
try {
|
||||
const snapshot = await stat.call(persistence, childId)
|
||||
if (snapshot === undefined) return undefined
|
||||
return `${String(snapshot.revision ?? '')}\0${String(snapshot.sizeBytes ?? '')}`
|
||||
} catch {
|
||||
// Unreadable stat (an unknown session, a permission race): fall back to
|
||||
// the plain read, which reports the failure in the route's own shape.
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The thread's event log (seed + its own events, already expanded): the live
|
||||
* agent's in-memory log while the thread is attached — the freshest read,
|
||||
@@ -289,8 +377,7 @@ async function threadLogEvents(ctx: Context, childId: string): Promise<readonly
|
||||
throw new SidebarError('sidechat-error', 'the session persistence service is unavailable', 503)
|
||||
}
|
||||
try {
|
||||
const inspected = await readPersistedSession(persistence, childId)
|
||||
return inspected.events as unknown as readonly SidechatLogEvent[]
|
||||
return await readColdThreadLog(persistence, childId)
|
||||
} catch (error: unknown) {
|
||||
throw new SidebarError(
|
||||
'not-found',
|
||||
|
||||
Reference in new issue
Block a user