feat(git-graph): 只读提交图的读取器与路由

新增一条 `git.graph` 路由:本地分支、远程跟踪分支与 HEAD 的提交图,纯读取
(不 checkout、不 fetch、不改任何 ref),沿用 Git 视角当前选择的仓库 / 工作树。

读取是有界的,任何一项超限都明确报错而不是悄悄截断或拖垮宿主:

- 每页最多 200 条(默认 50),游标偏移最多 10,000,分支最多 1,000;
- 每个 git 进程 10 s 超时、输出 8 MiB 上限;
- 历史按「钉住的 tip OID 集合」做 `--topo-order` 走查,分页游标是不透明字符串;
- 响应带快照指纹:分页期间 refs 变了就返回 `graph-stale`,客户端重取第一页,
  绝不把两份历史拼在一起。

错误码单独建了两条(`graph-stale` / `graph-limit`)并映射到 409 / 400:共用的
Git 错误映射会把它们压成通用的 `git-error`,客户端就失去了「游标过期、请刷新」
这个唯一可区分的信号。

测试:`tests/git-graph.spec.ts` 用真实仓库覆盖合并父提交、分支装饰、完整
message 与稳定分页,refs 移动 / 换筛选条件导致的过期,以及选中容器仓库与
linked worktree 的 HEAD;`tests/smoke.spec.ts` 新增一条路由级用例,钉住
「按选中的仓库与工作树路由、陈旧游标映射成 409」。
This commit is contained in:
vlln committed 2026-10-15 20:44:33 -07:00
1 parent c765c3eb49
commit 1508487442
6 files changed
+343

No files matched your search

+5
View File
@@ -26,6 +26,8 @@ import type {
SidebarUpdateTeamTaskRequest,
} from '../context-types.ts'
import type { WorkflowRunView } from '../workflow-runs.ts'
import type { GitGraphOptions, GitGraphResult } from '../git-graph.ts'
export type { GitGraphOptions, GitGraphResult, GitGraphEntry, GitGraphBranch } from '../git-graph.ts'
/** One wire failure. */
export class SidebarApiError extends Error {
@@ -517,6 +519,9 @@ export const api = {
call<{ current: string; names: string[] }>('git.branch', gitPayload(scope, worktree, {}), signal),
gitCheckout: (scope: SessionScope, branch: string, worktree?: string) =>
call<{ ok: true }>('git.checkout', gitPayload(scope, worktree, { branch })),
/** Read-only topological history; stale cursors require a fresh first page. */
gitGraph: (scope: SessionScope, options: GitGraphOptions = {}, worktree?: string, signal?: AbortSignal) =>
call<GitGraphResult>('git.graph', gitPayload(scope, worktree, { ...options }), signal),
/** Recent commit history, lazily pageable (skip/count; defaults 0/30). */
gitLog: (scope: SessionScope, count?: number, skip?: number, worktree?: string, signal?: AbortSignal) =>
call<GitLogEntry[]>('git.log', gitPayload(scope, worktree, {
+133
View File
@@ -0,0 +1,133 @@
import { execFile } from 'node:child_process'
import { createHash } from 'node:crypto'
import { GitCommandError, repoRoot } from './git.ts'
export interface GitGraphEntry {
hash: string
hashFull: string
parents: string[]
subject: string
author: string
date: string
refs: string[]
message: string
}
export interface GitGraphBranch { ref: string; name: string; hashFull: string }
export interface GitGraphOptions { branch?: string; count?: number; cursor?: string }
export interface GitGraphResult {
isRepo: boolean
root?: string
entries: GitGraphEntry[]
branches: GitGraphBranch[]
hasMore: boolean
nextCursor?: string
snapshot: string
}
const MAX_OUTPUT = 8 * 1024 * 1024
const MAX_OFFSET = 10_000
const OID = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/
const fail = (message: string, code = 'bad-request'): never => {
throw new GitCommandError(message, code, 'graph')
}
/** Separate read-only runner: bounded buffers, no prompts/lazy network fetches,
* replacement objects or optional index writes. Never pass client revisions. */
function readGit(cwd: string, args: string[], allowMissing = false): Promise<string> {
return new Promise((resolve, reject) => {
execFile('git', ['-C', cwd, '--no-pager', '--no-replace-objects', '-c', 'color.ui=false', ...args], {
encoding: 'utf8', timeout: 10_000, maxBuffer: MAX_OUTPUT, windowsHide: true,
env: { ...process.env, LC_ALL: 'C', GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0', GIT_NO_LAZY_FETCH: '1' },
}, (error, stdout, stderr) => {
if (!error) return resolve(stdout)
if (allowMissing && error.code === 1 && !stderr.trim()) return resolve('')
reject(new GitCommandError(stderr.trim() || error.message, 'git-error', args[0] ?? 'graph'))
})
})
}
function cursorOf(value: unknown): { fingerprint: string; offset: number } | undefined {
if (value === undefined) return undefined
if (typeof value !== 'string' || value.length > 512 || !/^[A-Za-z0-9_-]+$/.test(value)) fail('Invalid graph cursor')
try {
const parsed = JSON.parse(Buffer.from(value as string, 'base64url').toString('utf8'))
if (parsed?.version !== 1 || !/^[a-f0-9]{64}$/.test(parsed.fingerprint)
|| !Number.isSafeInteger(parsed.offset) || parsed.offset < 1 || parsed.offset > MAX_OFFSET) fail('Invalid graph cursor')
return parsed
} catch { return fail('Invalid graph cursor') }
}
async function snapshotOf(root: string, branch: string | undefined) {
const raw = await readGit(root, ['for-each-ref', '--sort=refname', '--format=%(refname)%00%(objectname)', 'refs/heads/', 'refs/remotes/'])
const branches: GitGraphBranch[] = raw.trimEnd().split('\n').filter(Boolean).map(line => {
const [ref, hashFull] = line.split('\0')
if (!ref || !hashFull || !OID.test(hashFull)) return fail('Invalid Git reference output', 'git-error')
return { ref, name: ref.replace(/^refs\/(heads|remotes)\//, ''), hashFull }
})
// Bound argv as well as output on repositories with enormous ref inventories.
if (branches.length > 1000) fail('Too many branches for graph (limit 1000)', 'graph-limit')
const head = (await readGit(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], true)).trim()
const symbolicHead = (await readGit(root, ['symbolic-ref', '--quiet', 'HEAD'], true)).trim()
if (head && !OID.test(head)) fail('Invalid HEAD', 'git-error')
if (!head && (!symbolicHead || branches.some(item => item.ref === symbolicHead))) fail('Cannot resolve HEAD', 'git-error')
const fingerprint = createHash('sha256').update(JSON.stringify({ root, branch, branches, head, symbolicHead })).digest('hex')
const selected = branch === undefined ? undefined : branches.find(item => item.ref === branch)
const tips = branch === undefined
? [...new Set([...branches.map(item => item.hashFull), ...(head ? [head] : [])])].sort()
: selected ? [selected.hashFull] : []
const decorations = new Map<string, string[]>()
for (const item of branches) decorations.set(item.hashFull, [...(decorations.get(item.hashFull) ?? []), item.name])
if (head) decorations.set(head, ['HEAD', ...(decorations.get(head) ?? [])])
return { branches, fingerprint, tips, decorations, selected }
}
/** Immutable OID traversal + before/after ref fingerprints prevents concatenating
* pages from different histories. No server cache or repository mutation. */
export async function gitGraph(cwd: string, options: GitGraphOptions = {}, selectedRepo?: string): Promise<GitGraphResult> {
const { branch, count = 50 } = options
if (branch !== undefined && (typeof branch !== 'string' || branch.length > 1024 || !/^refs\/(heads|remotes)\/.+/.test(branch))) fail('Expected a full local or remote branch ref')
if (typeof count !== 'number' || !Number.isSafeInteger(count) || count < 1) fail('Invalid graph count')
const limit = Math.min(count, 200)
const cursor = cursorOf(options.cursor)
let root: string
try {
// Probe strictly first: existing discovery deliberately swallows errors;
// graph must not turn permissions, broken Git or timeout into an empty UI.
root = (await readGit(cwd, ['rev-parse', '--show-toplevel'])).trim()
if (selectedRepo !== undefined) root = await repoRoot(cwd, selectedRepo)
} catch (error) {
if (!(error instanceof GitCommandError) || !/^fatal: not a git repository(?: \(|:)/.test(error.message)) throw error
try { root = await repoRoot(cwd, selectedRepo) } catch (discoveryError) {
if (!(discoveryError instanceof GitCommandError) || discoveryError.code !== 'not-repo') throw discoveryError
if (cursor) fail('Graph repository changed; refresh', 'graph-stale')
return { isRepo: false, entries: [], branches: [], hasMore: false, snapshot: '' }
}
root = (await readGit(root, ['rev-parse', '--show-toplevel'])).trim()
}
const before = await snapshotOf(root, branch)
if (cursor && cursor.fingerprint !== before.fingerprint) fail('Graph changed; refresh', 'graph-stale')
if (branch !== undefined && !before.selected) fail('Unknown graph branch')
const offset = cursor?.offset ?? 0
const entries: GitGraphEntry[] = []
if (before.tips.length) {
const output = await readGit(root, ['log', '--topo-order', '--no-decorate', '--no-show-signature', '--encoding=UTF-8',
`--max-count=${limit + 1}`, `--skip=${offset}`, '--format=%H%x00%P%x00%an%x00%ai%x00%s%x00%B%x00', ...before.tips, '--'])
// Git separates records with LF; only strip it from the next OID, never
// from message fields. NUL framing preserves multiline/control text.
const fields = output.split('\0')
for (let i = 0; i + 5 < fields.length; i += 6) {
const hashFull = fields[i]!.trim()
const parents = fields[i + 1]!.split(' ').filter(Boolean)
if (!OID.test(hashFull) || parents.some(parent => !OID.test(parent))) fail('Invalid Git graph output', 'git-error')
entries.push({ hash: hashFull.slice(0, 7), hashFull, parents,
author: fields[i + 2]!, date: fields[i + 3]!, subject: fields[i + 4]!, message: fields[i + 5]!, refs: before.decorations.get(hashFull) ?? [] })
}
}
const after = await snapshotOf(root, branch)
if (after.fingerprint !== before.fingerprint) fail('Graph changed; refresh', 'graph-stale')
const hasMore = entries.length > limit
if (hasMore && offset + limit > MAX_OFFSET) fail('Graph history limit reached (10000)', 'graph-limit')
return { isRepo: true, root, entries: entries.slice(0, limit), branches: before.branches, hasMore,
...(hasMore ? { nextCursor: Buffer.from(JSON.stringify({ version: 1, fingerprint: before.fingerprint, offset: offset + limit })).toString('base64url') } : {}),
snapshot: before.fingerprint }
}
+14
View File
@@ -43,6 +43,7 @@ import { createSidechatPushHub } from './sidechat-push.ts'
import { launchExternal } from './open-external.ts'
import { createArchiveTasks, respondArchiveDownload, type ArchiveTasks } from './archive-route.ts'
import * as git from './git.ts'
import { gitGraph, type GitGraphOptions } from './git-graph.ts'
import { SettingsConflictError } from '@deepseek-ai/dsh-settings'
import { AgentOpenRegistry, registerOpenTool, type AgentOpenRequest } from './agent-opens.ts'
import { buildSubagentLiveApi, type SidebarSubagentLiveRoutes } from './subagent-live-route.ts'
@@ -889,6 +890,19 @@ function buildApi(
await git.checkout(cwd, requireString(payload, 'branch'), selectedRepoOf(payload))
return { ok: true }
},
'git.graph': async (payload) => {
const { cwd } = await gitCwdOf(payload)
try {
return await gitGraph(cwd, payload as GitGraphOptions, selectedRepoOf(payload))
} catch (error) {
// The shared Git mapper collapses legacy command codes. Preserve the
// graph cursor's refresh signal rather than reporting a generic error.
if (error instanceof git.GitCommandError && (error.code === 'graph-stale' || error.code === 'graph-limit' || error.code === 'bad-request')) {
throw new SidebarError(error.code, error.message, error.code === 'graph-stale' ? 409 : 400)
}
throw error
}
},
'git.log': async (payload) => {
const { cwd } = await gitCwdOf(payload)
const record = payload as { count?: unknown; skip?: unknown }
+2
View File
@@ -21,6 +21,8 @@ export type SidebarErrorCode =
| 'fs-error'
| 'fs-conflict'
| 'git-error'
| 'graph-stale'
| 'graph-limit'
| 'git-suggest-empty'
| 'git-suggest-error'
| 'job-error'
+135
View File
@@ -0,0 +1,135 @@
import { afterEach, describe, expect, it } from 'vitest'
import { execFileSync } from 'node:child_process'
import { mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { gitGraph } from '../src/git-graph.ts'
const dirs: string[] = []
// macOS tmpdir() keeps the /var symlink while git reports the resolved
// /private/var prefix, and on Windows TEMP is often the 8.3 short form
// (C:\Users\RUNNER~1\...) while git reports the long path. The NATIVE realpath
// resolves both aliasings (libuv's GetFinalPathNameByHandle expands 8.3 names),
// so every fixture path this suite hands to git is spelled the way git answers
// back — the reader selects a checkout root by platform path identity.
function temp() { const dir = realpathSync.native(mkdtempSync(join(tmpdir(), 'sidebar-graph-'))); dirs.push(dir); return dir }
function git(dir: string, ...args: string[]) {
return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' } }).trim()
}
function repo() {
const dir = temp()
git(dir, 'init', '-b', 'main')
git(dir, 'config', 'user.name', 'Graph Tester')
git(dir, 'config', 'user.email', 'graph@example.test')
git(dir, 'config', 'commit.gpgsign', 'false')
return dir
}
function commit(dir: string, message: string) { git(dir, 'commit', '--allow-empty', '-m', message); return git(dir, 'rev-parse', 'HEAD') }
afterEach(() => {
const root = realpathSync.native(tmpdir())
for (const dir of dirs.splice(0)) { if (resolve(dir).startsWith(root + '/') || resolve(dir).startsWith(root + '\\')) rmSync(dir, { recursive: true, force: true }) }
})
function files(dir: string): Record<string, string> {
const result: Record<string, string> = {}
function visit(path: string) { for (const name of readdirSync(path)) { const full = join(path, name); if (statSync(full).isDirectory()) visit(full); else result[full] = readFileSync(full).toString('base64') } }
visit(dir)
return result
}
describe('read-only Git graph', () => {
it('distinguishes non-repositories, unborn repositories and real failures', async () => {
expect(await gitGraph(temp())).toMatchObject({ isRepo: false, entries: [] })
expect(await gitGraph(repo())).toMatchObject({ isRepo: true, entries: [], hasMore: false })
await expect(gitGraph(join(temp(), 'missing'))).rejects.toMatchObject({ code: 'git-error' })
})
it('returns merge parents, branch decorations, full messages and stable pages without writes', async () => {
const dir = repo()
const base = commit(dir, 'base')
git(dir, 'checkout', '-b', 'topic')
const topic = commit(dir, 'topic\n\nBody with unicode 日本語 and separators \x1e\x1f')
git(dir, 'checkout', 'main')
commit(dir, 'main change')
git(dir, 'merge', '--no-ff', 'topic', '-m', 'merge')
git(dir, 'update-ref', 'refs/remotes/origin/topic', topic)
writeFileSync(join(dir, 'untracked'), 'leave alone')
const before = files(dir)
const all = await gitGraph(dir)
expect(all.entries[0]!.parents).toHaveLength(2)
expect(all.entries.find(e => e.hashFull === topic)?.message).toContain('Body with unicode 日本語 and separators \x1e\x1f')
expect(all.entries.find(e => e.hashFull === topic)?.refs).toContain('origin/topic')
expect(all.entries.at(-1)?.hashFull).toBe(base)
const page1 = await gitGraph(dir, { count: 2 })
const page2 = await gitGraph(dir, { count: 2, cursor: page1.nextCursor })
expect([...page1.entries, ...page2.entries]).toEqual(all.entries)
expect(page2.hasMore).toBe(false)
expect(page2.nextCursor).toBeUndefined()
expect(page2.snapshot).toBe(page1.snapshot)
expect(files(dir)).toEqual(before)
const filtered = await gitGraph(dir, { branch: 'refs/remotes/origin/topic' })
expect(filtered.entries.map(e => e.hashFull)).toEqual([topic, base])
})
it('includes detached HEAD but excludes stash-only history', async () => {
const dir = repo()
commit(dir, 'base')
writeFileSync(join(dir, 'tracked'), 'a')
git(dir, 'add', '.')
commit(dir, 'tracked')
writeFileSync(join(dir, 'tracked'), 'b')
git(dir, 'stash')
const stash = git(dir, 'rev-parse', 'refs/stash')
git(dir, 'checkout', '--detach')
const detached = commit(dir, 'detached')
const graph = await gitGraph(dir)
expect(graph.entries[0]?.hashFull).toBe(detached)
expect(graph.entries.some(e => e.hashFull === stash)).toBe(false)
})
it('rejects stale pages when refs move or the filter changes', async () => {
const dir = repo()
commit(dir, 'one'); commit(dir, 'two')
const first = await gitGraph(dir, { count: 1 })
await expect(gitGraph(dir, { cursor: first.nextCursor, branch: 'refs/heads/main' })).rejects.toMatchObject({ code: 'graph-stale' })
git(dir, 'branch', 'new-decoration')
await expect(gitGraph(dir, { cursor: first.nextCursor })).rejects.toMatchObject({ code: 'graph-stale' })
const second = await gitGraph(dir, { count: 1, branch: 'refs/heads/new-decoration' })
git(dir, 'branch', '-D', 'new-decoration')
await expect(gitGraph(dir, { cursor: second.nextCursor, branch: 'refs/heads/new-decoration' })).rejects.toMatchObject({ code: 'graph-stale' })
})
it('uses selected container repositories and linked worktree HEADs', async () => {
const container = temp()
for (const name of ['a', 'b']) {
git(container, 'init', '-b', 'main', name)
git(join(container, name), 'config', 'user.name', 'Graph Tester')
git(join(container, name), 'config', 'user.email', 'graph@example.test')
git(join(container, name), 'config', 'commit.gpgsign', 'false')
commit(join(container, name), name)
}
expect((await gitGraph(container, {}, join(container, 'b'))).entries[0]?.subject).toBe('b')
const linked = join(temp(), 'linked')
git(join(container, 'b'), 'worktree', 'add', '--detach', linked)
const head = commit(linked, 'linked only')
expect((await gitGraph(linked, {}, join(container, 'b'))).entries[0]?.hashFull).toBe(head)
})
it('fails visibly instead of truncating oversized full messages', async () => {
const dir = repo()
const message = join(dir, 'message')
writeFileSync(message, 'large message\n\n' + 'x'.repeat(9 * 1024 * 1024))
git(dir, 'commit', '--allow-empty', '-F', message)
await expect(gitGraph(dir)).rejects.toMatchObject({ code: 'git-error' })
})
it('rejects option injection, unknown refs and malformed or unbounded cursors', async () => {
const dir = repo(); commit(dir, 'one')
for (const branch of ['--all', 'HEAD', 'main', 'refs/heads/main --all', 'refs/heads/main~1', 'refs/tags/v1', 'refs/heads/main\0']) {
await expect(gitGraph(dir, { branch })).rejects.toMatchObject({ code: 'bad-request' })
}
for (const cursor of ['', '!', 'a'.repeat(513), Buffer.from(JSON.stringify({ version: 1, fingerprint: 'a'.repeat(64), offset: 10001 })).toString('base64url')]) {
await expect(gitGraph(dir, { cursor })).rejects.toMatchObject({ code: 'bad-request' })
}
for (const count of [0, -1, NaN, 1.5]) await expect(gitGraph(dir, { count })).rejects.toMatchObject({ code: 'bad-request' })
})
})
+54
View File
@@ -631,6 +631,60 @@ describe('session cwd resolution over the API route', () => {
}
})
it('git.graph routes selected repositories and worktrees and maps stale cursors', async () => {
const scratch = realpathSync.native(mkdtempSync(join(tmpdir(), 'sidebar-graph-route-')))
const cwd = join(scratch, 'workspace')
mkdirSync(cwd)
const run = (dir: string, args: string[]): void => {
const result = spawnSync('git', ['-C', dir, '-c', 'user.name=Test', '-c', 'user.email=test@dsh.invalid', '-c', 'commit.gpgsign=false', ...args], { encoding: 'utf8' })
if (result.status !== 0) throw new Error(result.stderr)
}
const a = join(cwd, 'a')
const b = join(cwd, 'b')
const linked = join(scratch, 'linked')
try {
for (const path of [a, b]) {
run(scratch, ['init', '-q', '-b', 'main', path])
run(path, ['commit', '-q', '--allow-empty', '-m', path === a ? 'a-root' : 'b-root'])
}
run(b, ['worktree', 'add', '-q', '--detach', linked])
run(linked, ['commit', '-q', '--allow-empty', '-m', 'detached-linked'])
const route = mount({ sessions: { get: () => ({ header: { cwd } }) } })
const base = { sessionId: 'graph-route', cwd }
// `git rev-parse --show-toplevel` answers in git's own spelling — the
// resolved path joined by '/' — while `join()` produced the host
// separator and (on Windows) Windows' case-insensitive drive/comparison
// rules apply. Compare path identity, then the rows that selection
// produced, so the assertion stays about WHICH checkout was selected.
const pathKey = (path: string): string => {
const slashed = path.replaceAll('\\', '/').replace(/\/+$/, '')
return process.platform === 'win32' ? slashed.toLowerCase() : slashed
}
const reportedRoot = (result: { value?: { cwd: string } }): string =>
pathKey((result.value as unknown as { root: string }).root)
const basePage = await invoke(route, 'git.graph', base)
expect(basePage).toMatchObject({ ok: true, value: { entries: [{ subject: 'a-root' }] } })
expect(reportedRoot(basePage)).toBe(pathKey(a))
const childPage = await invoke(route, 'git.graph', { ...base, repoRoot: b })
expect(childPage).toMatchObject({ ok: true, value: { entries: [{ subject: 'b-root' }] } })
expect(reportedRoot(childPage)).toBe(pathKey(b))
const payload = { ...base, repoRoot: b, worktree: linked, count: 1 }
const first = await invoke(route, 'git.graph', payload)
expect(first).toMatchObject({ ok: true, value: { entries: [{ subject: 'detached-linked' }], hasMore: true } })
expect(reportedRoot(first)).toBe(pathKey(linked))
const cursor = (first.value as unknown as { nextCursor: string }).nextCursor
expect(typeof cursor).toBe('string')
expect(await invoke(route, 'git.graph', { ...payload, cursor })).toMatchObject({ ok: true, value: { entries: [{ subject: 'b-root' }], hasMore: false } })
run(linked, ['commit', '-q', '--allow-empty', '-m', 'HEAD moved'])
expect(await invoke(route, 'git.graph', { ...payload, cursor })).toMatchObject({ ok: false, status: 409, error: { code: 'graph-stale' } })
expect(await invoke(route, 'git.graph', { ...payload, branch: '--all' })).toMatchObject({ ok: false, status: 400, error: { code: 'bad-request' } })
expect(await invoke(route, 'git.graph', { ...payload, worktree: a })).toMatchObject({ ok: false })
} finally {
// scratch is the canonical mkdtemp directory allocated by this test.
rmSync(scratch, { recursive: true, force: true })
}
})
it('uses the client summary cwd while the session is detached', async () => {
const route = mount()
const result = await invoke(route, 'session.cwd', { sessionId: 's-detached', cwd: '/tmp/summary-cwd' })