From 3e5576ffbb3d88b4ee3bf65d4c8ac7169998926e Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Thu, 15 Oct 2026 23:05:32 +0800 Subject: [PATCH] =?UTF-8?q?perf(host):=20cwd=20=E8=A7=A3=E6=9E=90=E5=8A=A0?= =?UTF-8?q?=E5=9C=A8=E9=A3=9E=E5=8E=BB=E9=87=8D=E4=B8=8E=20TTL=20=E5=AF=B9?= =?UTF-8?q?=E9=BD=90=E3=80=81numstat=20=E5=8A=A0=20pathspec=20=E4=B8=8E?= =?UTF-8?q?=E8=BE=93=E5=87=BA=E4=B8=8A=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 项「临时回退→变红→还原」突变全部被捕获。 --- src/active-worktree.ts | 152 ++++++++++++++++++++++---- src/agent-opens.ts | 11 ++ src/fs-tree.ts | 26 ++++- src/git.ts | 172 ++++++++++++++++++++++++++++-- src/index.ts | 22 +++- src/sidechat-routes.ts | 91 +++++++++++++++- tests/active-worktree.spec.ts | 176 ++++++++++++++++++++++++++++++- tests/agent-opens.spec.ts | 26 +++++ tests/fs-tree-probe-gate.spec.ts | 55 ++++++++++ tests/git-worktree.spec.ts | 146 ++++++++++++++++++++++++- tests/sidechat-routes.spec.ts | 90 ++++++++++++++++ tests/smoke.spec.ts | 81 +++++++++++++- 12 files changed, 1005 insertions(+), 43 deletions(-) diff --git a/src/active-worktree.ts b/src/active-worktree.ts index a3ecff12..b6f76bb2 100644 --- a/src/active-worktree.ts +++ b/src/active-worktree.ts @@ -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() const pathTopCache = new Map() const linkedWorktreeCache = new Map() +/** + * 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>() +const topLevelInFlight = new Map>() + +/** + * 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(map: Map, 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 { } } +/** + * {@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 { + 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, s /** git top level for one path (its directory when the path names a file). */ async function topOfActivePath(value: string): Promise { 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 { async function isLinkedWorktree(top: string): Promise { 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 { } 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 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 { + 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 } diff --git a/src/agent-opens.ts b/src/agent-opens.ts index d102920e..453b8aa7 100644 --- a/src/agent-opens.ts +++ b/src/agent-opens.ts @@ -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) { diff --git a/src/fs-tree.ts b/src/fs-tree.ts index 2c6d721d..7af15372 100644 --- a/src/fs-tree.ts +++ b/src/fs-tree.ts @@ -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 { + 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 }) } diff --git a/src/git.ts b/src/git.ts index 4a0b588c..ebcc3655 100644 --- a/src/git.ts +++ b/src/git.ts @@ -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 { +export function runGit(cwd: string, args: string[], timeoutMs = 30_000, options: RunGitOptions = {}): Promise { // `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((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 { * 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, from: Map { + 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, from: Map { 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 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() addLineCounts(lineCounts, parseNumstat(stagedNumstat)) addLineCounts(lineCounts, parseNumstat(unstagedNumstat)) diff --git a/src/index.ts b/src/index.ts index 86800831..0e53ea1a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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') } diff --git a/src/sidechat-routes.ts b/src/sidechat-routes.ts index be84947d..8ffc1d0e 100644 --- a/src/sidechat-routes.ts +++ b/src/sidechat-routes.ts @@ -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() + +/** + * 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 { + 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 { + const stat = (persistence as { stat?: (id: string) => Promise }).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 [] as string[]) +/** The plugin's git probe seam: call order plus an optional canned answer. */ +const seam = vi.hoisted(() => ({ + /** Every cwd handed to the plugin's own git probe, in call order. */ + probed: [] as string[], + /** + * Optional canned answer per probe. Set it to exercise the process-wide + * caches (which are keyed per session) without paying one REAL git spawn per + * key; `probed` still records every call the module made. + */ + responder: null as null | ((cwd: string, args: string[]) => string), +})) + +const probed = seam.probed // Records (and delegates to) the real spawn so the case-folding regression is // visible on case-insensitive hosts too. @@ -17,7 +28,8 @@ vi.mock('../src/git.ts', async (importOriginal) => { ...actual, runGit: (cwd: string, args: string[], timeoutMs?: number) => { probed.push(cwd) - return actual.runGit(cwd, args, timeoutMs) + const canned = seam.responder?.(cwd, args) + return canned === undefined ? actual.runGit(cwd, args, timeoutMs) : Promise.resolve(canned) }, } }) @@ -61,6 +73,29 @@ function sessionCtx(cwd: string, calls: Array>): Context } as never } +/** + * The same live-session face with the session LOOKUP counted. The root cache is + * consulted before the session is ever read, so `lookups()` is the observable + * difference between "answered from the TTL cache" and "scanned the event log + * again" — which is what makes the no-rescan assertion below discriminative. + */ +function countingSessionCtx(cwd: string, calls: Array>): { ctx: Context; lookups: () => number } { + let lookups = 0 + const ctx = { + sessions: { + get: () => { + lookups += 1 + return { + header: { cwd }, + snapshotEvents: () => calls.map((data, index) => ({ type: 'tool/call', seq: index, time: index, data })), + } + }, + }, + get: () => undefined, + } as never + return { ctx: ctx as Context, lookups: () => lookups } +} + describe('active worktree root', () => { it('follows a linked worktree of a DIFFERENT repository named by the tool calls', async () => { const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-')) @@ -117,4 +152,139 @@ describe('active worktree root', () => { rmSync(root, { recursive: true, force: true }) } }) + + /** + * Steady-state cost: twelve `/sidebar/*` route handlers funnel through + * `cwdOf()`, so a burst of parallel calls for one session used to spawn one + * `git rev-parse` per call. The in-flight maps collapse the whole + * (session, base) resolution into one. + */ + it('shares ONE base git spawn across a burst of concurrent asks', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-')) + const repo = join(root, 'repo') + try { + initRepo(repo, 'a.txt') + const { ctx, lookups } = countingSessionCtx(repo, []) + probed.length = 0 + const answers = await Promise.all( + Array.from({ length: 8 }, () => activeWorktreeRootOf(ctx, 's-burst', repo)), + ) + expect(probed).toEqual([repo]) + // The whole resolution is shared, not just the spawn: the event log is + // read (and scanned) once for the burst. + expect(lookups()).toBe(1) + // Every concurrent caller still gets the resolved answer. + expect(new Set(answers)).toEqual(new Set([realpathSync.native(repo)])) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + /** + * Different sessions rooted in the SAME repository share the base probe: + * without the per-path in-flight map, N tabs of one workspace spawn N + * `git rev-parse` processes at once. Each session still resolves on its own + * (its own event log decides its root). + */ + it('shares ONE base probe across different sessions of one repository', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-')) + const repo = join(root, 'repo') + try { + initRepo(repo, 'a.txt') + const { ctx, lookups } = countingSessionCtx(repo, []) + probed.length = 0 + await Promise.all( + Array.from({ length: 6 }, (_unused, index) => activeWorktreeRootOf(ctx, `s-shared-${index}`, repo)), + ) + expect(probed).toEqual([repo]) + expect(lookups()).toBe(6) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + /** The TTL is what makes the client's 5 s poll free; 3 s made every poll a miss. */ + it('answers a second ask inside the TTL without scanning or spawning', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-')) + const repo = join(root, 'repo') + try { + initRepo(repo, 'a.txt') + mkdirSync(join(repo, 'src')) + // A tool call INSIDE the repository: scanning it costs a probe, and the + // answer is the repository top level. + const { ctx, lookups } = countingSessionCtx(repo, [{ cwd: join(repo, 'src') }]) + const first = await activeWorktreeRootOf(ctx, 's-ttl', repo) + expect(first).toBe(realpathSync.native(repo)) + expect(lookups()).toBe(1) + expect(probed.length).toBeGreaterThan(0) + + probed.length = 0 + await expect(activeWorktreeRootOf(ctx, 's-ttl', repo)).resolves.toBe(first) + // No spawn AND no event-log scan (the cache is consulted before the + // session is read, so the scan never starts). + expect(probed).toEqual([]) + expect(lookups()).toBe(1) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + /** + * The client's per-tab poll is every 5 s, so a 3 s TTL made every poll a + * miss. The cached root must survive past the old window (10 s in, still a + * hit) — the clock is moved, not the test. + */ + it('serves the cached root 10 s later (longer than the old 3 s TTL)', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-')) + const repo = join(root, 'repo') + try { + initRepo(repo, 'a.txt') + const { ctx, lookups } = countingSessionCtx(repo, []) + const first = await activeWorktreeRootOf(ctx, 's-ttl-span', repo) + probed.length = 0 + const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 10_000) + try { + await expect(activeWorktreeRootOf(ctx, 's-ttl-span', repo)).resolves.toBe(first) + } finally { + clock.mockRestore() + } + expect(probed).toEqual([]) + expect(lookups()).toBe(1) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + /** + * The three process-wide maps are bounded LRUs. The module exposes no test + * seam, so the bound is observed the only way it is observable from outside: + * after `cap` distinct sessions, the OLDEST session's next ask is a miss + * again (it was evicted) while the youngest ones still hit. + */ + it('bounds the root cache: the oldest session is evicted past the cap', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-')) + try { + // The canned answer keeps the 257 probes from being 257 real processes; + // `probed` still counts every probe the module made. + seam.responder = (cwd) => `${cwd}\n` + const ctx = sessionCtx(root, []) + const cap = 256 + for (let index = 0; index <= cap; index += 1) { + await activeWorktreeRootOf(ctx, `lru-${index}`, root) + } + expect(probed).toHaveLength(cap + 1) + + probed.length = 0 + // The oldest SURVIVOR and the newest key are still cached: no probe. + await activeWorktreeRootOf(ctx, 'lru-1', root) + await activeWorktreeRootOf(ctx, `lru-${cap}`, root) + expect(probed).toEqual([]) + // Inserted first, so it is the one the cap evicted: re-asked, it probes. + await activeWorktreeRootOf(ctx, 'lru-0', root) + expect(probed).toEqual([root]) + } finally { + seam.responder = null + rmSync(root, { recursive: true, force: true }) + } + }) }) diff --git a/tests/agent-opens.spec.ts b/tests/agent-opens.spec.ts index 9663f7d1..02458f0a 100644 --- a/tests/agent-opens.spec.ts +++ b/tests/agent-opens.spec.ts @@ -107,6 +107,32 @@ describe('AgentOpenRegistry', () => { detach2() }) + /** + * The queue is bounded per session: a thread whose sidebar is never shown + * must not accumulate opens for the lifetime of the host process. + */ + it('caps the per-session queue, dropping the OLDEST queued opens', () => { + const registry = new AgentOpenRegistry() + const ids: string[] = [] + for (let index = 0; index < 70; index += 1) { + ids.push(registry.enqueue('s1', 'file', `/f${index}.txt`, `f${index}.txt`).id) + } + // Another session's queue is untouched by the cap. + registry.enqueue('s2', 'file', '/other.txt', 'other.txt') + + const received: Array<{ id: string }> = [] + const detach = registry.attach('s1', (request) => { received.push(request) }) + expect(received).toHaveLength(64) + // FIFO among the survivors, and the survivors are the NEWEST 64. + expect(received.map(request => request.id)).toEqual(ids.slice(6)) + detach() + + const other: unknown[] = [] + const detachOther = registry.attach('s2', (request) => { other.push(request) }) + expect(other).toHaveLength(1) + detachOther() + }) + it('drainAll drops the queue and dispose drops subscribers', () => { const registry = new AgentOpenRegistry() registry.enqueue('s1', 'file', '/a.txt', 'a.txt') diff --git a/tests/fs-tree-probe-gate.spec.ts b/tests/fs-tree-probe-gate.spec.ts index a83932f4..a0ef885e 100644 --- a/tests/fs-tree-probe-gate.spec.ts +++ b/tests/fs-tree-probe-gate.spec.ts @@ -135,4 +135,59 @@ describe('listDirectory probe budget', () => { rmSync(root, { recursive: true, force: true }) } }) + + /** + * The fold mark is decoration, so a wide level must not pay one `opendir` + * per directory row: past the per-level cap the remaining rows stay + * un-folded (and, crucially, un-probed). + */ + it('caps the compact probes of one wide level', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-probe-cap-')) + try { + const level = join(root, 'wide') + mkdirSync(level) + // 100 singleton chains: without the cap every one of them is probed. + for (let index = 0; index < 100; index += 1) { + mkdirSync(join(level, `only-${String(index).padStart(3, '0')}`)) + writeFileSync(join(level, `only-${String(index).padStart(3, '0')}`, 'child.txt'), 'x') + } + + const counted = countingGate() + const listing = await listDirectory(level, 1000, undefined, counted.gate) + expect(listing.entries).toHaveLength(100) + expect(counted.calls()).toBe(32) + // Probed in row order: the first 32 rows are folded, the rest are left + // alone rather than probed. + const folded = listing.entries.filter(entry => entry.compact === true) + expect(folded).toHaveLength(32) + expect(folded.map(entry => entry.name)).toEqual( + listing.entries.slice(0, 32).map(entry => entry.name), + ) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + it('skips the compact probe entirely on a truncated level', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-probe-truncated-')) + try { + const level = join(root, 'wide') + mkdirSync(level) + for (let index = 0; index < 6; index += 1) { + mkdirSync(join(level, `only-${index}`)) + writeFileSync(join(level, `only-${index}`, 'child.txt'), 'x') + } + + const counted = countingGate() + // A row cap below the level's width flags it truncated: the rows on + // screen are an arbitrary slice, so none of them is folded. + const listing = await listDirectory(level, 3, undefined, counted.gate) + expect(listing.truncated).toBe(true) + expect(listing.entries).toHaveLength(3) + expect(counted.calls()).toBe(0) + expect(listing.entries.every(entry => entry.compact === undefined)).toBe(true) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) }) diff --git a/tests/git-worktree.spec.ts b/tests/git-worktree.spec.ts index d51e3505..8664d7bc 100644 --- a/tests/git-worktree.spec.ts +++ b/tests/git-worktree.spec.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from 'vitest' import { spawnSync } from 'node:child_process' -import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' -import { parseWorktreeList, resolveWorktree, status, worktrees } from '../src/git.ts' +import { parseWorktreeList, resolveWorktree, runGit, status, worktrees } from '../src/git.ts' const IDENTITY = { GIT_AUTHOR_NAME: 'dsh-better-sidebar-test', @@ -132,4 +132,146 @@ describe('linked Git worktrees', () => { rmSync(root, { recursive: true, force: true }) } }) + + /** + * The status read feeds the two `--numstat` diffs a pathspec built from its + * OWN porcelain output (the untracked walk that produced 9.24 MB of numstat + * in a repository with an unignored nested `node_modules` must not reach the + * diff walks at all). This pins the part that is easy to get wrong: every + * path a row can carry counts for has to stay in that pathspec — including + * the ORIGIN name of a rename, without which git cannot pair the two sides + * and `0 0` silently becomes a full-file add. + */ + it('keeps every per-file count and the group total under the numstat pathspec', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-numstat-pathspec-')) + const main = join(root, 'main') + try { + git(root, ['init', '-q', main]) + git(main, ['checkout', '-q', '-b', 'main']) + // Rename detection is a user config; pin it so this fixture means the + // same thing on every machine (same convention as tests/git.spec.ts). + git(main, ['config', 'diff.renames', 'true']) + git(main, ['config', 'status.renames', 'true']) + writeFileSync(join(main, 'both-sides.txt'), 'one\ntwo\n') + writeFileSync(join(main, 'worktree-only.txt'), 'alpha\n') + writeFileSync(join(main, 'moved.txt'), 'same\n') + git(main, ['add', '-A']) + git(main, ['commit', '-q', '-m', 'base']) + + // One file changed on BOTH sides (their counts add up), one changed in + // the worktree only, a staged rename, and an untracked file. + writeFileSync(join(main, 'both-sides.txt'), 'one\ntwo\nthree\n') + git(main, ['add', 'both-sides.txt']) + writeFileSync(join(main, 'both-sides.txt'), 'one\ntwo\nthree\nfour\n') + writeFileSync(join(main, 'worktree-only.txt'), 'alpha\nbeta\n') + git(main, ['mv', 'moved.txt', 'renamed.txt']) + writeFileSync(join(main, 'untracked.txt'), 'brand new\n') + + const result = await status(main) + const byPath = new Map(result.entries.map(entry => [entry.path, entry])) + expect(byPath.get('both-sides.txt')).toMatchObject({ xy: 'MM', counts: { additions: 2, deletions: 0 } }) + expect(byPath.get('worktree-only.txt')).toMatchObject({ xy: ' M', counts: { additions: 1, deletions: 0 } }) + // A rename that loses its origin from the pathspec reports `1 0` here. + expect(byPath.get('renamed.txt')).toMatchObject({ xy: 'R ', counts: { additions: 0, deletions: 0 } }) + // No numstat row exists for an untracked file, pathspec or not. + expect(byPath.get('untracked.txt')).toEqual({ path: 'untracked.txt', xy: '??' }) + + // The group total the changes tree sums: dropping ANY of the paths above + // (or the rename origin) changes this number. + const totals = result.entries.reduce((sum, entry) => { + const counts = entry.counts + return counts !== undefined && 'additions' in counts + ? { additions: sum.additions + counts.additions, deletions: sum.deletions + counts.deletions } + : sum + }, { additions: 0, deletions: 0 }) + expect(totals).toEqual({ additions: 3, deletions: 0 }) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + /** + * The row cap's field budget is twice `GIT_STATUS_LIMIT` because porcelain + * frames TWO fields per rename record: a rename-heavy tree inside the row cap + * must not be cut short (and mislabelled `truncated`) by a budget that only + * counts ROWS. + * + * The fixture is sized so the budget is observable: the names are long and + * the count high enough that the status answer arrives in several 64 KiB + * reads, which is where a `limit + 1` budget — 2 001 fields for 1 800 rename + * records, i.e. before the answer ends — cuts the list off mid-stream. + */ + it('does not cut a rename-heavy tree inside the row cap short', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-rename-budget-')) + const main = join(root, 'main') + try { + git(root, ['init', '-q', main]) + git(main, ['checkout', '-q', '-b', 'main']) + git(main, ['config', 'status.renames', 'true']) + const renames = 1_800 + const pad = 'x'.repeat(140) + for (let index = 0; index < renames; index += 1) { + writeFileSync(join(main, `a${index}-${pad}.txt`), 'x\n') + } + git(main, ['add', '-A']) + git(main, ['commit', '-q', '-m', 'base']) + for (let index = 0; index < renames; index += 1) { + renameSync(join(main, `a${index}-${pad}.txt`), join(main, `b${index}-${pad}.txt`)) + } + git(main, ['add', '-A']) + + const result = await status(main) + // 1 800 rename records = 3 600 porcelain fields: under the row cap, and + // under the (2x) field budget, so nothing is dropped or flagged. + expect(result.entries).toHaveLength(renames) + expect(result.truncated).toBe(false) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + it('kills a command whose stdout passes the byte cap, and keeps the default ceiling generous', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-git-cap-')) + try { + git(root, ['init', '-q']) + git(root, ['checkout', '-q', '-b', 'main']) + writeFileSync(join(root, 'big.txt'), 'x'.repeat(256 * 1024)) + git(root, ['add', '-A']) + git(root, ['commit', '-q', '-m', 'big']) + + await expect(runGit(root, ['show', 'HEAD:big.txt'], 30_000, { maxBytes: 4_096 })) + .rejects.toThrow(/git show output exceeded 4096 bytes/) + // The default ceiling is far above any legitimate answer: the same read + // is unaffected without the option. + await expect(runGit(root, ['show', 'HEAD:big.txt'])).resolves.toHaveLength(256 * 1024) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + + it('stops producing once the NUL field cap is reached', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-field-cap-')) + try { + git(root, ['init', '-q']) + // Long names, so the status answer spans several 64 KiB pipe reads: the + // cap is checked per chunk, which is exactly how a runaway untracked + // walk is cut off mid-stream. + const files = 2_500 + for (let index = 0; index < files; index += 1) { + writeFileSync(join(root, `f${index}-${'x'.repeat(40)}.ts`), 'x') + } + const args = ['status', '--porcelain=v1', '-z', '--untracked-files=all'] + const all = await runGit(root, args) + expect(all.split('\0').filter(field => field !== '')).toHaveLength(files) + + const capped = await runGit(root, args, 30_000, { maxNulFields: 1_000 }) + const fields = capped.split('\0').filter(field => field !== '') + expect(fields.length).toBeGreaterThanOrEqual(1_000) + expect(fields.length).toBeLessThan(files) + // A complete prefix of the same answer, not a scrambled one. + expect(all.startsWith(fields.slice(0, 1_000).join('\0'))).toBe(true) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) }) diff --git a/tests/sidechat-routes.spec.ts b/tests/sidechat-routes.spec.ts index e31605b0..fad1103e 100644 --- a/tests/sidechat-routes.spec.ts +++ b/tests/sidechat-routes.spec.ts @@ -617,6 +617,96 @@ describe('sidechat.events', () => { expect(services.open).toHaveBeenCalledWith('child', 'read') }) + /** + * A cold thread is re-read on EVERY poll, and each read decodes the whole + * persisted log and scans it back to `session/end-seed`. The memo keys on the + * stored artifact's identity (the host's change token + physical size), so a + * repeat poll costs one `stat` while a changed artifact re-reads — and the + * handle is still opened and closed. + */ + it('reads a cold thread once per stored-artifact identity', async () => { + const child = agent('child') + const services = happyServices(undefined, child) + services.agents.get = vi.fn((_id: unknown) => undefined) + const read = vi.fn(async () => ({ events: threadLog() })) + const close = vi.fn(async () => {}) + services.open.mockImplementation(async () => ({ + header: { agentPreset: 'preset-a' }, + inheritedEventCount: 0, + read, + close, + })) + let revision = 'mtime-1:size-4096' + const stat = vi.fn(async () => ({ revision, sizeBytes: 4_096 })) + // `stat` is read structurally at runtime (the plugin's mirror of the host + // service models the handle API only), so the fake attaches it here. + const persistence = services.sessionPersistence as { stat?: unknown } + persistence.stat = stat + const api = buildSidechatApi(ctxWith(services)) + + const first = await api['sidechat.events']({ childId: 'cold-memo' }) + expect(first.events.map(event => event.seq)).toEqual([3, 4, 5, 6, 7]) + const second = await api['sidechat.events']({ childId: 'cold-memo' }) + expect(second.events.map(event => event.seq)).toEqual([3, 4, 5, 6, 7]) + // Same identity: ONE handle, ONE read, and the handle was closed. + expect(stat).toHaveBeenCalledTimes(2) + expect(services.open).toHaveBeenCalledTimes(1) + expect(read).toHaveBeenCalledTimes(1) + expect(close).toHaveBeenCalledTimes(1) + + // A new mtime is a new identity: the memo must not serve the stale log. + revision = 'mtime-2:size-8192' + await api['sidechat.events']({ childId: 'cold-memo' }) + expect(services.open).toHaveBeenCalledTimes(2) + expect(read).toHaveBeenCalledTimes(2) + expect(close).toHaveBeenCalledTimes(2) + }) + + /** The memo is bounded: a thread past the cap is re-read, not remembered. */ + it('bounds the cold-log memo', async () => { + const services = happyServices(undefined, agent('child')) + services.agents.get = vi.fn((_id: unknown) => undefined) + const read = vi.fn(async () => ({ events: threadLog() })) + services.open.mockImplementation(async () => ({ + header: { agentPreset: 'preset-a' }, + inheritedEventCount: 0, + read, + close: async () => {}, + })) + const persistence = services.sessionPersistence as { stat?: unknown } + persistence.stat = vi.fn(async (id: string) => ({ revision: `rev-${id}`, sizeBytes: 1 })) + const api = buildSidechatApi(ctxWith(services)) + + const cap = 16 + for (let index = 0; index <= cap; index += 1) { + await api['sidechat.events']({ childId: `cold-lru-${index}` }) + } + expect(services.open).toHaveBeenCalledTimes(cap + 1) + + // The newest thread still hits; the oldest was evicted and re-reads. + await api['sidechat.events']({ childId: `cold-lru-${cap}` }) + expect(services.open).toHaveBeenCalledTimes(cap + 1) + await api['sidechat.events']({ childId: 'cold-lru-0' }) + expect(services.open).toHaveBeenCalledTimes(cap + 2) + }) + + it('falls back to an uncached read when the host exposes no stat', async () => { + const child = agent('child') + const services = happyServices(undefined, child) + services.agents.get = vi.fn((_id: unknown) => undefined) + const read = vi.fn(async () => ({ events: threadLog() })) + services.open.mockImplementation(async () => ({ + header: { agentPreset: 'preset-a' }, + inheritedEventCount: 0, + read, + close: async () => {}, + })) + const api = buildSidechatApi(ctxWith(services)) + await api['sidechat.events']({ childId: 'cold-no-stat' }) + await api['sidechat.events']({ childId: 'cold-no-stat' }) + expect(services.open).toHaveBeenCalledTimes(2) + }) + it('returns a marker-less legacy log whole', async () => { const child = agent('child', { events: [ diff --git a/tests/smoke.spec.ts b/tests/smoke.spec.ts index 67139617..f5e9ebb7 100644 --- a/tests/smoke.spec.ts +++ b/tests/smoke.spec.ts @@ -9,6 +9,7 @@ import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync import { tmpdir, homedir } from 'node:os' import { dirname, join, resolve as resolvePath } from 'node:path' import { SettingsConflictError, type SettingsNamespace } from '@deepseek-ai/dsh-settings' +import { WebSocket } from 'ws' import { apply, FS_TREES_MAX_PATHS, mediaTypeForPath } from '../src/index.ts' import { SIDEBAR_PREFS_DEFAULTS } from '../src/prefs-shared.ts' import { encodeHtmlUrl } from '../src/html-route.ts' @@ -132,8 +133,63 @@ describe('host plugin smoke', () => { for (const cleanup of effects) cleanup() }) - it('serves HTML previews as UTF-8 without changing the file bytes', async () => { - const directory = mkdtempSync(join(tmpdir(), 'dsh-sidebar-html-utf8-')) + /** + * Teardown must release the ACCEPTED sockets, not merely stop accepting new + * ones: `WebSocketServer.close()` on a `noServer` server does not terminate + * an already-upgraded socket under ws@8 (it sets `_shouldEmitClose` and + * waits), so without the explicit `wss.clients` close every fs-watch + * `fs.watch` handle and the agent-opens subscriber set survives the plugin + * unmount until the browser disconnects. The client here is a REAL ws + * connection through the registered upgrade handler. + */ + it('closes the accepted push sockets on teardown', async () => { + const upgrades: SidebarWebUpgradeRoute[] = [] + const effects: Array<() => void | (() => void)> = [] + const ctx: FakeContext = { + webRuntime: { trustedHosts: [] }, + webServer: { + register: () => () => {}, + registerUpgrade: (route) => { upgrades.push(route); return () => {} }, + }, + sessions: { get: () => undefined }, + tools: { register: () => () => {} }, + effect: (fn) => { + const cleanup = fn() + if (typeof cleanup === 'function') effects.push(cleanup) + }, + inject: () => () => {}, + on: () => () => {}, + get: () => undefined, + } + apply(ctx as never) + const upgrade = upgrades.find(route => route.path === '/sidebar/ws/agent-opens')! + const { createServer } = await import('node:http') + const server = createServer() + server.on('upgrade', (req, socket, head) => { + upgrade.handler(req as never, socket as never, head as never) + }) + await new Promise((resolve) => { server.listen(0, '127.0.0.1', () => { resolve() }) }) + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('test setup: no server port') + const client = new WebSocket(`ws://127.0.0.1:${address.port}/sidebar/ws/agent-opens?sessionId=s-teardown`) + try { + await new Promise((resolve, reject) => { + client.once('open', () => { resolve() }) + client.once('error', reject) + }) + const closed = new Promise((resolve) => { + const timer = setTimeout(() => { resolve(false) }, 3_000) + client.once('close', () => { clearTimeout(timer); resolve(true) }) + }) + for (const cleanup of effects) cleanup() + expect(await closed).toBe(true) + } finally { + client.terminate() + await new Promise((resolve) => { server.close(() => { resolve() }) }) + } + }) + + it('serves HTML previews as UTF-8 without changing the file bytes', async () => { const directory = mkdtempSync(join(tmpdir(), 'dsh-sidebar-html-utf8-')) const path = join(directory, 'fragment.html') const source = Buffer.from('
排序算法可视化
', 'utf8') writeFileSync(path, source) @@ -1200,6 +1256,27 @@ describe('session cwd resolution over the API route', () => { } }) + it('fs.tree builds one probe gate for its single level', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-tree-gate-')) + const workspace = join(root, 'workspace') + mkdirSync(join(workspace, 'only'), { recursive: true }) + writeFileSync(join(workspace, 'only', 'child.txt'), 'x') + try { + const route = mount({ sessions: { get: () => ({ header: { cwd: workspace } }) } }) + const before = probeGateCalls.length + const answer = await invoke(route, 'fs.tree', { sessionId: 's-tree-single-gate', path: workspace }) + expect(answer.ok).toBe(true) + // The single-layer route is a probe-bounded request too: it lists ONE + // level, but that level runs the same per-row probes (`fs.trees` passes + // a gate for exactly this reason), so it must build one as well. + expect(probeGateCalls.length - before).toBe(1) + const entries = (answer.value as unknown as { entries: { compact?: boolean }[] }).entries + expect(entries.filter(entry => entry.compact === true)).toHaveLength(1) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + it.skipIf(!canCreateSymlink)('lists a workspace symlink that resolves outside the workspace', async () => { const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-symlink-security-')) const workspace = join(root, 'workspace')