fix: 分支过多时继续显示提交历史

This commit is contained in:
kelvinwww committed 2026-10-20 21:21:27 +08:00
1 parent 83faf70940
commit b9e07526c3
8 files changed
+143 -11

No files matched your search

+1
View File
@@ -4,6 +4,7 @@
### v0.28.0
- **[#1013] 超过 1000 个分支/远程跟踪引用时仍可访问提交历史**:界面显示明确标注的提交列表,保留提交选择与详情。列表读取本地分支、远程分支和当前 HEAD;分页通过 Git 引用、HEAD 与 shallow 边界的状态指纹校验,状态变化时要求刷新。引用输出上限为 8 MiB,引用数量上限为 100,000,shallow 元数据上限为 1 MiB。
- **正式版支持线前移到 DSH 0.2.1-rc.1+**:13 条 DSH peer 下限统一为 `^0.2.1-rc.1`,开发依赖、CI 与安装脚本使用精确 RC 基线。不新增运行时兼容层、不改功能实现。
- **沿用已发布 alpha 的功能**:上游 alpha.5 → rc.1 完整源码树差异共 355 项,全部为 `package.json`,源码零变化;本次仅同步版本、依赖声明与文档。伴随依赖调整为 Cordis peer `^4.0.5` / dev `4.0.5`、group `1.0.5`、schemastery `~3.18.5`,include 保持 `1.0.10`。
- **发布渠道切换至 npm `latest`**:插件 v0.28.0 即将接管 `latest`,现有 workflow 按正式版本号自动选择该标签,无需修改。**宿主 npm `latest` 此时仍是 0.2.0-rc.2,不能安装本版**;该宿主必须固定插件 **v0.26.1**。DSH 0.2.1-alpha.5 用户固定 **v0.28.0-alpha.0**;0.2.0-rc.1、0.1.7 及更早支持线保持原指引。用户已明确接受两个包的 `latest` 不对齐风险。
+3
View File
@@ -535,6 +535,9 @@ export const api = {
/** 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),
/** 图形界面超过分支上限时读取经状态指纹校验的分页历史。 */
gitHistory: (scope: SessionScope, options: { count?: number; cursor?: string } = {}, worktree?: string, signal?: AbortSignal) =>
call<{ isRepo: boolean; root?: string; entries: GitGraphResult['entries']; hasMore: boolean; nextCursor?: string; snapshot: string }>('git.history', 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, {
+28 -9
View File
@@ -120,6 +120,7 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP
const [branch, setBranch] = useState('')
const [page, setPage] = useState<GraphPage | null>(null)
const [branches, setBranches] = useState<GraphPage['branches']>([])
const [linearFallback, setLinearFallback] = useState(false)
const selectionRef = useRef(selectedRef)
selectionRef.current = selectedRef
const clearPreviewRef = useRef(onClearPreview)
@@ -162,11 +163,27 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP
setError(null)
setStale(false)
try {
const result = await api.gitGraph(scope, {
branch: branch || undefined, count: 50,
cursor: append ? previous?.nextCursor : undefined,
}, worktree, controller.signal)
let result: GraphPage
let fallback = linearFallback
if (append && linearFallback) {
const history = await api.gitHistory(scope, { count: 50, cursor: previous?.nextCursor }, worktree, controller.signal)
result = { ...history, branches: [] }
} else {
try {
result = await api.gitGraph(scope, {
branch: branch || undefined, count: 50,
cursor: append ? previous?.nextCursor : undefined,
}, worktree, controller.signal)
fallback = false
} catch (reason) {
if (append || !(reason instanceof SidebarApiError) || reason.code !== 'graph-limit') throw reason
const history = await api.gitHistory(scope, { count: 50 }, worktree, controller.signal)
result = { ...history, branches: [] }
fallback = true
}
}
if (controller.signal.aborted || gen !== generation.current) return
if (!append) setLinearFallback(fallback)
const next = append && previous ? {
...result,
entries: [...previous.entries, ...result.entries.filter(entry => !previous.entries.some(old => old.hashFull === entry.hashFull))],
@@ -199,6 +216,7 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP
setPage(null)
setBranch('')
setBranches([])
setLinearFallback(false)
}, [scope.sessionId, scope.cwd, scope.repoRoot, worktree])
useEffect(() => {
if (visible) void request(false)
@@ -264,12 +282,13 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP
return <section className={css.root} aria-label={t('gitGraph')} data-git-graph>
<div className={css.toolbar}>
<select className={css.select} aria-label={t('graphBranchFilter')}
{linearFallback && <div role="status">{t('graphLinearFallback')}</div>}
{!linearFallback && <select className={css.select} aria-label={t('graphBranchFilter')}
value={branch} onChange={event => { chooseBranch(event.target.value) }}>
<option value="">{t('graphAllBranches')}</option>
{branches.map(item => <option key={item.ref} value={item.ref}>{item.name}</option>)}
{branch && !branches.some(item => item.ref === branch) && <option value={branch}>{branch}</option>}
</select>
</select>}
</div>
<div className={css.scroll} aria-busy={loading} ref={scrollRef}>
{error !== null && <div className={css.notice} role="alert">
@@ -291,11 +310,11 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP
onMouseLeave={cancelHover}
onClick={() => { cancelHover(); select(entry) }}
onContextMenu={onContextMenu === undefined ? undefined : (event) => { onContextMenu(event, entry) }}>
<svg width={width} height={ROW_HEIGHT} viewBox={`0 0 ${width} ${ROW_HEIGHT}`} preserveAspectRatio="none" className={css.graph} aria-hidden="true">
{!linearFallback && <svg width={width} height={ROW_HEIGHT} viewBox={`0 0 ${width} ${ROW_HEIGHT}`} preserveAspectRatio="none" className={css.graph} aria-hidden="true">
{row.segments.map((edge, i) => <path key={i} data-color={colorSlot(edge.colorIndex)}
d={edgePath(edge, laneX, ROW_HEIGHT)} />)}
<circle cx={laneX(row.lane)} cy={ROW_HEIGHT / 2} r={3} data-color={slot} />
</svg>
</svg>}
{entry.refs.length > 0 && <span className={css.refs}>
{refPills(entry.refs, remotes).map(pill => <RefPill key={pill.name} pill={pill} slot={slot} />)}
</span>}
@@ -320,4 +339,4 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP
</div>}
</AnchoredPopover>
</section>
}
}
+1
View File
@@ -247,6 +247,7 @@ export const ja: Record<string, string> = {
graphBranchFilter: 'ブランチの絞り込み',
graphEmpty: 'コミットはありません',
graphLoadError: 'コミット履歴を読み込めませんでした',
graphLinearFallback: 'ブランチが多すぎるため、ブランチ構造を示さない履歴リストを表示しています',
graphStale: '履歴が変更されました。更新してください。',
graphDetails: 'コミットの詳細',
graphParents: '親コミット',
+2
View File
@@ -258,6 +258,7 @@ export const zh = {
graphBranchFilter: '分支筛选',
graphEmpty: '暂无提交',
graphLoadError: '加载提交历史失败',
graphLinearFallback: '分支过多,当前显示线性历史列表(不表示分支拓扑)',
graphStale: '提交历史已变化,请刷新',
graphDetails: '提交详情',
graphParents: '父提交',
@@ -891,6 +892,7 @@ export const en: Record<keyof typeof zh, string> = {
graphBranchFilter: 'Branch filter',
graphEmpty: 'No commits',
graphLoadError: 'Failed to load commit history',
graphLinearFallback: 'Too many branches; showing a linear history list (not branch topology)',
graphStale: 'History has changed. Refresh to continue.',
graphDetails: 'Commit details',
graphParents: 'Parents',
+58
View File
@@ -1,4 +1,6 @@
import { execFile } from 'node:child_process'
import { readFile } from 'node:fs/promises'
import { resolve } from 'node:path'
import { createHash } from 'node:crypto'
import { GitCommandError, repoRoot } from './git.ts'
@@ -26,6 +28,8 @@ export interface GitGraphResult {
const MAX_OUTPUT = 8 * 1024 * 1024
const MAX_OFFSET = 10_000
const MAX_HISTORY_REFS = 100_000
const MAX_SHALLOW_BYTES = 1024 * 1024
const OID = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/
const fail = (message: string, code = 'bad-request'): never => {
throw new GitCommandError(message, code, 'graph')
@@ -81,6 +85,60 @@ async function snapshotOf(root: string, branch: string | undefined) {
return { branches, fingerprint, tips, decorations, selected }
}
/** 计算线性历史的状态指纹,限制引用输出与浅克隆边界文件的大小。 */
async function historySnapshot(root: string): Promise<string> {
const refs = await readGit(root, ['for-each-ref', '--sort=refname', '--format=%(refname)%00%(objectname)'])
const lines = refs.trimEnd().split('\n').filter(Boolean)
if (lines.length > MAX_HISTORY_REFS) fail('Too many references to safely snapshot history (limit 100000)', 'graph-limit')
const head = (await readGit(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], true)).trim()
const shallowPath = (await readGit(root, ['rev-parse', '--git-path', 'shallow'])).trim()
let shallow: string | null = null
try {
const bytes = await readFile(resolve(root, shallowPath))
if (bytes.byteLength > MAX_SHALLOW_BYTES) fail('Shallow boundary metadata exceeds 1 MiB', 'graph-limit')
shallow = bytes.toString('base64')
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
return createHash('sha256').update(JSON.stringify({ root, refs: lines, head, shallow })).digest('hex')
}
export interface GitHistoryOptions { cursor?: string; count?: number }
export interface GitHistoryResult { isRepo: boolean; root?: string; entries: GitGraphEntry[]; hasMore: boolean; nextCursor?: string; snapshot: string }
/** 图形界面超过分支上限时读取提交列表,并校验引用、HEAD 和浅克隆边界。 */
export async function gitHistory(cwd: string, options: GitHistoryOptions = {}, selectedRepo?: string): Promise<GitHistoryResult> {
const count = options.count ?? 50
if (!Number.isSafeInteger(count) || count < 1) fail('Invalid history count')
const limit = Math.min(count, 200)
let cursor: { fingerprint: string; offset: number } | undefined
if (options.cursor !== undefined) {
if (typeof options.cursor !== 'string' || options.cursor.length > 512) fail('Invalid history cursor')
try {
const parsed = JSON.parse(Buffer.from(options.cursor, '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 history cursor')
cursor = parsed
} catch { fail('Invalid history cursor') }
}
const root = selectedRepo !== undefined ? await repoRoot(cwd, selectedRepo) : (await readGit(cwd, ['rev-parse', '--show-toplevel'])).trim()
const before = await historySnapshot(root)
if (cursor && cursor.fingerprint !== before) fail('History changed; refresh', 'graph-stale')
const offset = cursor?.offset ?? 0
const output = await readGit(root, ['log', '--branches', '--remotes', 'HEAD', '--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', '--'])
const fields = output.split('\0')
const entries: GitGraphEntry[] = []
for (let i = 0; i + 5 < fields.length; i += 6) {
const hashFull = fields[i]!.trim(), parents = fields[i + 1]!.split(' ').filter(Boolean)
if (!OID.test(hashFull) || parents.some(parent => !OID.test(parent))) fail('Invalid Git history 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: [] })
}
if (await historySnapshot(root) !== before) fail('History changed; refresh', 'graph-stale')
const hasMore = entries.length > limit
if (hasMore && offset + limit > MAX_OFFSET) fail('History limit reached (10000)', 'graph-limit')
return { isRepo: true, root, entries: entries.slice(0, limit), hasMore, snapshot: before,
...(hasMore ? { nextCursor: Buffer.from(JSON.stringify({ version: 1, fingerprint: before, offset: offset + limit })).toString('base64url') } : {}) }
}
/** 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> {
+11 -1
View File
@@ -39,7 +39,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 { gitGraph, gitHistory, type GitGraphOptions, type GitHistoryOptions } 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'
@@ -908,6 +908,16 @@ function buildApi(
throw error
}
},
'git.history': async (payload) => {
const { cwd } = await gitCwdOf(payload)
try { return await gitHistory(cwd, payload as GitHistoryOptions, selectedRepoOf(payload)) }
catch (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 }
+39 -1
View File
@@ -3,7 +3,7 @@ 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'
import { gitGraph, gitHistory } from '../src/git-graph.ts'
const dirs: string[] = []
// macOS tmpdir() keeps the /var symlink while git reports the resolved
@@ -84,6 +84,44 @@ describe('read-only Git graph', () => {
const graph = await gitGraph(dir)
expect(graph.entries[0]?.hashFull).toBe(detached)
expect(graph.entries.some(e => e.hashFull === stash)).toBe(false)
expect((await gitHistory(dir)).entries.some(e => e.hashFull === stash)).toBe(false)
})
it('uses bounded graph inventory but offers snapshot-validated history across all refs', async () => {
const dir = repo()
const base = commit(dir, 'base')
commit(dir, 'head')
const first = await gitHistory(dir, { count: 1 })
expect(first.entries[0]?.subject).toBe('head')
const second = await gitHistory(dir, { count: 1, cursor: first.nextCursor })
expect(second.entries[0]?.hashFull).toBe(base)
expect(second.snapshot).toBe(first.snapshot)
git(dir, 'tag', 'history-tag', base)
await expect(gitHistory(dir, { count: 1, cursor: first.nextCursor })).rejects.toMatchObject({ code: 'graph-stale' })
const generatedRefs = Array.from({ length: 999 }, (_, i) => `create refs/heads/generated-${String(i).padStart(4, '0')} ${base}`).join('\n') + '\n'
execFileSync('git', ['-C', dir, 'update-ref', '--stdin'], { input: generatedRefs, env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1' } })
expect((await gitGraph(dir, { count: 1 })).branches).toHaveLength(1000)
git(dir, 'update-ref', 'refs/heads/generated-0999', base)
await expect(gitGraph(dir)).rejects.toMatchObject({ code: 'graph-limit' })
expect((await gitHistory(dir, { count: 1 })).entries[0]?.subject).toBe('head')
})
it('detects detached HEAD movement and shallow-boundary changes between history pages', async () => {
const dir = repo()
const firstCommit = commit(dir, 'first')
const second = commit(dir, 'second')
git(dir, 'checkout', '--detach', second)
const firstPage = await gitHistory(dir, { count: 1 })
const detachedOnly = commit(dir, 'detached-only')
expect((await gitHistory(dir, { count: 1 })).entries[0]?.hashFull).toBe(detachedOnly)
await expect(gitHistory(dir, { count: 1, cursor: firstPage.nextCursor })).rejects.toMatchObject({ code: 'graph-stale' })
const shallow = join(dir, '.git', 'shallow')
writeFileSync(shallow, `${second}\n`)
const shallowPage = await gitHistory(dir, { count: 1 })
writeFileSync(shallow, `${second}\n${firstCommit}\n`)
await expect(gitHistory(dir, { count: 1, cursor: shallowPage.nextCursor })).rejects.toMatchObject({ code: 'graph-stale' })
})
it('rejects stale pages when refs move or the filter changes', async () => {