feat(version-history): 「版本记录」页 —— 追踪远端 main 全部提交(只读 + 管理员手动同步)
build / build (push) Successful in 57s

按已确认的契约实现(口径见 docs/VERSION_HISTORY.md):

- **版本号口径(只给有证据的)**:注释 tag + tag 指向该提交 + 该提交内 CHANGELOG 顶部三者一致 ⇒ 正式版本;
  tag 之后的提交按 `<主>.<次>.<自该 tag 的提交数>` 显示开发号(与 scripts/version.py **同规则**);
  证据不足 ⇒ 「历史提交 · 短SHA」+ 原因码,**不补造版本号**。完整 SHA 是唯一身份、版本号不是唯一键
  (tag 之后两条并行分支各自的第 1 个提交都算 0.1.1 ⇒ 两条都保留,用短 SHA 区分)。
- **迁移 000046**:version_history_commits(提交记录,主键 repo_key+commit_sha)+ version_history_sync_runs
  (同步状态)。快照 = 一次同步:抓完并与 X-Total-Count 对账通过才切换;失败不切换快照、不清空历史、
  last_success_at 不动(页面显示"上次同步失败(原因)· 仍展示上次成功数据");「同步成功」≠「历史完整」。
- **只读客户端(匿名,不使用任何凭据)**:白名单 origin + 固定仓库、拒绝任意 URL 与跨主机重定向、
  响应上限 5MB / 超时 15s、仅 5xx/429 退避重试(最多 3 次);逐页抓到短页为止;每次全量扫 tag
  ⇒ 旧提交后补的 tag 会更新既有记录(不新增第二行)。
- **接口**(三个都登记进 api/openapi.yaml):GET /api/v1/build-info(viewer)、
  GET /api/v1/version-history(viewer;游标绑定快照,过期返回 409 cursor_expired;不返回伪造 total)、
  POST /api/v1/version-history/sync(admin;并发同步复用同一作业,靠 IdempotencyKey)。
- **「当前运行」只认精确匹配**:产物注入的完整 SHA 命中某条记录才标该条;开发构建显式标注"开发构建";
  没有可用标识 ⇒ "当前运行版本未知";**不拿最新 main / 最新 tag 顶替**,CI 成功不等于已部署。
- **前端**:一级菜单第 5 项(版本记录)+ 时间线页面(全部/正式/开发/历史四段筛选、正文展开、
  加载更多、760px 单列无横向溢出、提交正文与变更记录按纯文本渲染);无打 tag / 发布 / 部署入口。

新增配置(留空即未接线,页面降级):VERSION_HISTORY_GITEA_BASE_URL / _REPO / _ALLOWED_ORIGINS /
_HTTP_TIMEOUT / _MAX_PAGES。

验证:`make verify` 15/15 success(tests-go 578 通过 / 0 失败;tests-web 209 通过 / 0 失败);
新增 Go 用例 30(版本口径与图遍历 12、客户端守卫 6、同步编排 5、接口 7);前端新增 18(组件 10 + 客户端 8);
真实仓库匿名快照拉取(`VERSION_HISTORY_LIVE_BASE_URL=… go test -run TestLiveSyncAgainstRealRepository`):
抓到 113 条与 X-Total-Count 一致、v0.1.0 是注释 tag 且目标与 `git rev-parse v0.1.0^{commit}` 一致、
开发号逐个等于 `git rev-list --count v0.1.0..<sha>`(正式 1 / 开发 22 / 历史 90)。
This commit is contained in:
姚章浩
2026-10-13 19:40:19 +08:00
parent ad9c5d20d4
commit 0974d8dfa2
35 changed files with 6413 additions and 659 deletions
+2057 -632
View File
File diff suppressed because it is too large Load Diff
+209
View File
@@ -0,0 +1,209 @@
// @ts-expect-error The test runner provides Node; the browser bundle intentionally omits @types/node.
import { readFileSync } from 'node:fs'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { VersionHistoryView } from './VersionHistory'
import type { VersionHistoryItem, VersionHistoryPage } from './versionHistory'
const releaseItem: VersionHistoryItem = {
commit_sha: '6de5d5236380ad619fe35e4bd20f49b2d967903e',
short_sha: '6de5d5236380',
parents: ['97f4b296613e23889997dd14004cd23f6c3a2c3f'],
committed_at: '2026-10-13T16:45:56+08:00',
author_display: '姚章浩',
subject: 'feat(version): 开发号随提交自动递增 + 首个正式版本 0.1.0',
body: '正文第一行\n正文第二行',
record_kind: 'release',
version_label: '0.1.0',
version_state: 'verified',
release_tags: [{ name: 'v0.1.0', url: 'https://gitea.example/Weknora/knowledge-governance/src/tag/v0.1.0' }],
release_notes: '### Added\n\n- 首个正式版本',
commit_url: 'https://gitea.example/Weknora/knowledge-governance/commit/6de5d5236380ad619fe35e4bd20f49b2d967903e',
version_reason: 'annotated_tag_and_changelog_top_match',
is_current_running: true,
}
const developmentItem: VersionHistoryItem = {
...releaseItem,
commit_sha: '950c1b429bc814d9fa7c2c1449f999a05537af21',
short_sha: '950c1b429bc8',
subject: 'feat(release): 抬档门禁',
body: '',
record_kind: 'development',
version_label: '0.1.1',
version_state: 'verified',
release_tags: [],
release_notes: '',
is_current_running: false,
}
const historicalItem: VersionHistoryItem = {
...releaseItem,
commit_sha: 'e1c5f68c0d8a4f2b9c3d5e7a1b2c3d4e5f607182',
short_sha: 'e1c5f68c0d8a',
subject: 'chore(deploy): 部署与备份脚本',
body: '',
record_kind: 'historical',
version_label: '',
version_state: 'unknown',
release_tags: [],
release_notes: '',
version_reason: 'no_baseline',
is_current_running: false,
commit_url: 'https://gitea.example/Weknora/knowledge-governance/commit/e1c5f68c0d8a4f2b9c3d5e7a1b2c3d4e5f607182',
}
const page: VersionHistoryPage = {
items: [releaseItem, developmentItem, historicalItem],
next_cursor: 'cursor-2',
has_more: true,
sync: {
available: true,
status: 'completed',
complete: true,
last_success_at: '2026-10-13T20:00:00+08:00',
fetched_count: 111,
expected_count: 111,
error_code: '',
source_head_sha: 'ad9c5d20d467…',
active_snapshot_id: 12,
repo: 'Weknora/knowledge-governance',
},
current_running: {
state: 'matched',
commit_sha: '6de5d5236380ad619fe35e4bd20f49b2d967903e',
display_version: '0.1.0',
matched_commit_sha: '6de5d5236380ad619fe35e4bd20f49b2d967903e',
},
}
const render = (over: Partial<Parameters<typeof VersionHistoryView>[0]> = {}) =>
renderToStaticMarkup(
<VersionHistoryView
page={page}
build={null}
filter="all"
loading={false}
loadingMore={false}
error={null}
notice={null}
expanded={null}
canSync={false}
onFilter={vi.fn()}
onLoadMore={vi.fn()}
onSync={vi.fn()}
onExpand={vi.fn()}
{...over}
/>
)
describe('VersionHistoryView', () => {
it('lists commits newest-first with kind badges, short sha, times and links', () => {
const html = render()
expect(html).toContain('版本记录')
expect(html).toContain('正式版本')
expect(html).toContain('开发版本')
expect(html).toContain('历史提交')
expect(html).toContain('0.1.0')
expect(html).toContain('0.1.1')
expect(html).toContain('950c1b429bc8')
expect(html).toContain('查看提交')
expect(html).toContain('查看 tag v0.1.0')
expect(html.indexOf('0.1.0')).toBeLessThan(html.indexOf('0.1.1'))
})
it('marks only the exact-match commit as current running', () => {
const html = render()
const flags = html.match(/当前运行/g) ?? []
// 顶部一句「当前运行:…」+ 恰好一个条目徽标
expect(flags.length).toBe(2)
expect(html).toContain('已匹配到下面的提交')
})
it('never labels a commit when the running identity is unknown', () => {
const html = render({
page: {
...page,
current_running: { state: 'unknown', commit_sha: '', display_version: 'dev', matched_commit_sha: '' },
},
})
expect(html).toContain('当前运行版本未知')
expect(html).not.toContain('当前运行</span>')
expect(html).not.toContain('已匹配到下面的提交')
})
it('does not invent a version number for unverified history commits', () => {
const html = render()
const start = html.indexOf('历史提交 · e1c5f68c0d8a')
expect(start).toBeGreaterThan(-1)
expect(html).toContain('版本号未能核验:找不到可核验的发布基线')
expect(html).not.toMatch(/历史提交 · e1c5f68c0d8a[\s\S]{0,200}?\d+\.\d+\.\d+[\s\S]{0,40}?版本号未能核验/)
})
it('keeps two commits that resolve to the same number as separate entries', () => {
const sameNumber: VersionHistoryItem = {
...developmentItem,
commit_sha: 'c'.repeat(40),
short_sha: 'cccccccccccc',
subject: '另一条同号提交',
}
const html = render({ page: { ...page, items: [developmentItem, sameNumber] } })
expect(html).toContain('950c1b429bc8')
expect(html).toContain('cccccccccccc')
expect((html.match(/0\.1\.1/g) ?? []).length).toBe(2)
})
it('shows an honest empty state and never offers tag/publish/deploy actions', () => {
const html = render({ page: { ...page, items: [], has_more: false } })
expect(html).toContain('暂无记录')
expect(html).not.toContain('打 tag')
expect(html).not.toContain('发布</button>')
expect(html).not.toContain('部署</button>')
// 非管理员看不到同步入口
expect(html).not.toContain('同步记录</button>')
})
it('exposes the admin sync entry only for admins and reflects sync failures', () => {
const html = render({ canSync: true })
expect(html).toContain('同步记录')
const failed = render({
canSync: true,
page: {
...page,
sync: { ...page.sync, status: 'failed', complete: false, error_code: 'gitea_unreachable' },
},
})
expect(failed).toContain('上次同步失败(gitea_unreachable)')
expect(failed).toContain('仍展示上次成功的数据')
expect(failed).toContain('同步失败')
})
it('degrades to "not wired" instead of failing when the source is unconfigured', () => {
const html = render({
page: { ...page, items: [], sync: { ...page.sync, available: false, status: '' } },
})
expect(html).toContain('未接线')
expect(html).not.toContain('同步记录</button>')
})
it('keeps mobile single-column rules so nothing overflows horizontally', () => {
const css = readFileSync(new URL('./versionHistory.css', import.meta.url), 'utf8')
expect(css).toMatch(/@media \(max-width: 760px\)[\s\S]*?\.version-history[\s\S]*?overflow-wrap:\s*anywhere/)
expect(css).toMatch(
/@media \(max-width: 760px\)[\s\S]*?\.version-history-entry-head\s*\{\s*flex-direction:\s*column/
)
})
it('renders commit bodies as text, never as markup', () => {
const html = render({
expanded: developmentItem.commit_sha,
page: {
...page,
items: [{ ...developmentItem, body: '<img src=x onerror=alert(1)>', release_notes: '<script>x</script>' }],
},
})
expect(html).not.toContain('<img src=x')
expect(html).not.toContain('<script>x</script>')
expect(html).toContain('&lt;img src=x')
})
})
+285
View File
@@ -0,0 +1,285 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
fetchVersionHistory,
fetchBuildInfo,
reasonLabel,
syncVersionHistory,
type BuildInfo,
type VersionHistoryItem,
type VersionHistoryPage,
} from './versionHistory'
import { useOptionalAuth } from './auth'
import './versionHistory.css'
// 「版本记录」页:追踪**所有已进入远端 main 的提交**,按提交时间倒序。
// 只读:不提供打 tag / 发布 / 部署按钮;版本号只按证据展示,证据不足就说"历史提交"。
const FILTERS: ReadonlyArray<{ id: string; label: string }> = [
{ id: 'all', label: '全部' },
{ id: 'release', label: '正式' },
{ id: 'development', label: '开发' },
{ id: 'historical', label: '历史' },
]
const stamp = (value: string) => (value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '—')
const kindLabel: Record<string, string> = { release: '正式版本', development: '开发版本', historical: '历史提交' }
const runningText = (running: VersionHistoryPage['current_running']) => {
if (running.state === 'matched')
return `当前运行:${running.display_version}(${running.commit_sha.slice(0, 12)},已匹配到下面的提交)`
if (running.state === 'development') {
return `当前运行:开发构建 ${running.display_version}(${running.commit_sha.slice(0, 12)})—— 这份产物不在已同步的提交里`
}
return '当前运行版本未知(产物没有注入可核验的提交标识)'
}
const syncText = (sync: VersionHistoryPage['sync']) => {
if (!sync.available) return '未接线:还没有配置只读的仓库来源'
if (!sync.status) return '尚未同步过'
if (sync.status === 'running' || sync.status === 'pending') return `同步中(${sync.status})`
if (sync.status === 'failed') {
return `上次同步失败(${sync.error_code || '未知原因'})· 仍展示上次成功的数据(${stamp(sync.last_success_at)})`
}
if (!sync.complete) {
return `上次同步:部分历史(${sync.fetched_count}/${sync.expected_count ?? '?'})· ${stamp(sync.last_success_at)}`
}
return `最后同步:${stamp(sync.last_success_at)}(${sync.fetched_count} 条提交)`
}
interface ViewProps {
page: VersionHistoryPage | null
build: BuildInfo | null
filter: string
loading: boolean
loadingMore: boolean
error: string | null
notice: string | null
expanded: string | null
canSync: boolean
onFilter: (id: string) => void
onLoadMore: () => void
onSync: () => void
onExpand: (sha: string | null) => void
}
export function VersionHistoryView(props: ViewProps) {
const { page, build } = props
const items = page?.items ?? []
return (
<section className="version-history" aria-label="版本记录">
<header className="version-history-header">
<div>
<h2>版本记录</h2>
<p>
{page
? runningText(page.current_running)
: build
? `当前运行:${build.identity_available ? build.display_version : '未知'}`
: '当前运行版本未知'}
</p>
<p className="version-history-sync-line">
{page ? syncText(page.sync) : '正在读取同步状态…'}
{page?.sync.status === 'running' || page?.sync.status === 'pending' ? (
<span className="version-history-badge pending">同步中</span>
) : null}
{page && page.sync.status === 'failed' ? (
<span className="version-history-badge warn">同步失败</span>
) : null}
</p>
</div>
{props.canSync ? (
<button type="button" onClick={props.onSync} disabled={props.loading || !page?.sync.available}>
{page?.sync.status === 'running' || page?.sync.status === 'pending' ? '同步进行中…' : '同步记录'}
</button>
) : null}
</header>
{props.error ? (
<div className="error-banner" role="alert">
{props.error}
</div>
) : null}
{props.notice ? <div className="version-history-notice">{props.notice}</div> : null}
<nav className="version-history-filters" aria-label="按记录类型筛选">
{FILTERS.map((entry) => (
<button
type="button"
key={entry.id}
className={props.filter === entry.id ? 'active' : ''}
aria-pressed={props.filter === entry.id}
onClick={() => props.onFilter(entry.id)}
>
{entry.label}
</button>
))}
</nav>
{items.length === 0 && !props.loading ? (
<div className="empty-state">
{page?.sync.available
? '暂无记录(先同步一次,或该筛选下没有条目)'
: '版本记录未接线:等待配置只读的仓库来源'}
</div>
) : null}
<ol className="version-history-timeline">
{items.map((item) => (
<TimelineEntry
key={item.commit_sha}
item={item}
// 「当前运行」以页面级判定为准(同一份事实),条目标志只做兜底
currentMatchedSHA={page?.current_running.state === 'matched' ? page.current_running.matched_commit_sha : ''}
expanded={props.expanded === item.commit_sha}
onExpand={() => props.onExpand(props.expanded === item.commit_sha ? null : item.commit_sha)}
/>
))}
</ol>
{props.loading ? <div className="empty-state">正在读取版本记录…</div> : null}
{page?.has_more ? (
<button type="button" className="version-history-more" onClick={props.onLoadMore} disabled={props.loadingMore}>
{props.loadingMore ? '正在加载…' : '加载更多'}
</button>
) : null}
</section>
)
}
function TimelineEntry({
item,
currentMatchedSHA,
expanded,
onExpand,
}: {
item: VersionHistoryItem
currentMatchedSHA: string
expanded: boolean
onExpand: () => void
}) {
const isRelease = item.record_kind === 'release' && item.version_state === 'verified'
const heading = isRelease ? item.version_label : item.version_label || `历史提交 · ${item.short_sha}`
const note = isRelease ? item.release_notes : ''
const hasDetail = Boolean(item.body) || Boolean(note)
return (
<li className={`version-history-entry ${item.record_kind}`}>
<div className="version-history-entry-head">
<strong>{heading}</strong>
<span>{stamp(item.committed_at)}</span>
</div>
<div className="version-history-entry-meta">
<span className={`version-history-badge ${item.record_kind}`}>{kindLabel[item.record_kind] ?? '历史提交'}</span>
<span className="version-history-sha">{item.short_sha}</span>
{item.commit_sha && item.commit_sha === currentMatchedSHA ? (
<span className="version-history-badge current">当前运行</span>
) : null}
<span className="version-history-author">{item.author_display}</span>
</div>
<p className="version-history-subject">{item.subject}</p>
{!item.version_label && item.record_kind === 'historical' ? (
<p className="version-history-reason">版本号未能核验:{reasonLabel(item.version_reason)}</p>
) : null}
{hasDetail ? (
<>
<button type="button" className="version-history-toggle" onClick={onExpand} aria-expanded={expanded}>
{expanded ? '收起详情' : '展开详情'}
</button>
{expanded ? (
<div className="version-history-detail">
{item.record_kind === 'release' && note ? <pre>{note}</pre> : null}
{item.body ? <pre>{item.body}</pre> : null}
</div>
) : null}
</>
) : null}
<div className="version-history-links">
{item.commit_url ? (
<a href={item.commit_url} target="_blank" rel="noreferrer noopener">
查看提交
</a>
) : null}
{item.release_tags.map((tag) => (
<a key={tag.name} href={tag.url} target="_blank" rel="noreferrer noopener">
查看 tag {tag.name}
</a>
))}
</div>
</li>
)
}
export function VersionHistory() {
const auth = useOptionalAuth()
const [page, setPage] = useState<VersionHistoryPage | null>(null)
const [build, setBuild] = useState<BuildInfo | null>(null)
const [filter, setFilter] = useState('all')
const [loading, setLoading] = useState(true)
const [loadingMore, setLoadingMore] = useState(false)
const [error, setError] = useState<string | null>(null)
const [notice, setNotice] = useState<string | null>(null)
const [expanded, setExpanded] = useState<string | null>(null)
const cursor = useRef('')
const load = useCallback(async (kind: string, append: boolean) => {
append ? setLoadingMore(true) : setLoading(true)
try {
const next = await fetchVersionHistory({ kind, cursor: append ? cursor.current : '' })
cursor.current = next.next_cursor
setPage((current) => (append && current ? { ...next, items: [...current.items, ...next.items] } : next))
setError(null)
} catch (cause) {
setError(cause instanceof Error ? cause.message : '加载版本记录失败')
} finally {
append ? setLoadingMore(false) : setLoading(false)
}
}, [])
useEffect(() => {
void load(filter, false)
}, [filter, load])
useEffect(() => {
let cancelled = false
void fetchBuildInfo()
.then((value) => {
if (!cancelled) setBuild(value)
})
.catch(() => undefined)
return () => {
cancelled = true
}
}, [])
// 只有管理员能看到同步入口;其他人只能看(服务端也会再判一次角色)
const canSync = auth?.identity?.role === 'admin'
const onSync = useCallback(async () => {
setNotice(null)
try {
const accepted = await syncVersionHistory()
setNotice(accepted.reused ? '已有同步任务在跑,本次复用它。' : '已提交同步任务,稍后刷新即可看到新记录。')
await load(filter, false)
} catch (cause) {
setError(cause instanceof Error ? cause.message : '触发同步失败')
}
}, [filter, load])
const viewProps = useMemo<ViewProps>(
() => ({
page,
build,
filter,
loading,
loadingMore,
error,
notice,
expanded,
canSync,
onFilter: setFilter,
onLoadMore: () => void load(filter, true),
onSync: () => void onSync(),
onExpand: setExpanded,
}),
[page, build, filter, loading, loadingMore, error, notice, expanded, canSync, load, onSync]
)
return <VersionHistoryView {...viewProps} />
}
+171
View File
@@ -0,0 +1,171 @@
/* 「版本记录」页:只读时间线。窄屏(≤760px,与工作台既有断点一致)单列、无横向溢出。 */
.version-history {
display: flex;
flex-direction: column;
gap: 12px;
min-width: 0;
}
.version-history-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
.version-history-header h2 {
margin: 0 0 4px;
font-size: 18px;
}
.version-history-header p {
margin: 0;
color: var(--muted, #666);
font-size: 13px;
}
.version-history-sync-line {
display: flex;
align-items: center;
gap: 8px;
margin-top: 4px !important;
}
.version-history-notice {
padding: 8px 10px;
border-radius: 6px;
background: rgba(64, 158, 255, 0.12);
font-size: 13px;
}
.version-history-filters {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.version-history-filters button.active {
font-weight: 600;
border-color: currentColor;
}
.version-history-timeline {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 10px;
min-width: 0;
}
.version-history-entry {
border-left: 3px solid rgba(127, 127, 127, 0.35);
padding: 10px 12px;
background: rgba(127, 127, 127, 0.06);
border-radius: 6px;
min-width: 0;
}
.version-history-entry.release {
border-left-color: #2f9e44;
}
.version-history-entry.development {
border-left-color: #1c7ed6;
}
.version-history-entry-head {
display: flex;
justify-content: space-between;
gap: 8px;
flex-wrap: wrap;
}
.version-history-entry-head strong {
font-size: 15px;
}
.version-history-entry-meta {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
margin-top: 4px;
font-size: 12px;
color: var(--muted, #666);
}
.version-history-badge {
padding: 1px 6px;
border-radius: 999px;
border: 1px solid currentColor;
font-size: 12px;
}
.version-history-badge.release {
color: #2f9e44;
}
.version-history-badge.development {
color: #1c7ed6;
}
.version-history-badge.historical {
color: #868e96;
}
.version-history-badge.current {
color: #e8590c;
}
.version-history-badge.pending {
color: #1c7ed6;
}
.version-history-badge.warn {
color: #c92a2a;
}
.version-history-sha {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
overflow-wrap: anywhere;
}
.version-history-subject {
margin: 6px 0 0;
overflow-wrap: anywhere;
}
.version-history-reason {
margin: 4px 0 0;
font-size: 12px;
color: #c92a2a;
overflow-wrap: anywhere;
}
.version-history-toggle {
margin-top: 6px;
}
.version-history-detail pre {
margin: 6px 0 0;
padding: 8px;
max-height: 320px;
overflow: auto;
background: rgba(127, 127, 127, 0.1);
border-radius: 6px;
white-space: pre-wrap;
overflow-wrap: anywhere;
font-size: 12px;
}
.version-history-links {
display: flex;
gap: 10px;
flex-wrap: wrap;
margin-top: 6px;
font-size: 13px;
}
@media (max-width: 760px) {
.version-history-header {
flex-direction: column;
align-items: stretch;
}
.version-history-entry {
padding: 8px 10px;
}
.version-history-entry-head {
flex-direction: column;
gap: 2px;
}
/* 窄屏单列:正文/标题/hash 一律换行,不出现横向滚动 */
.version-history,
.version-history-timeline,
.version-history-entry,
.version-history-subject,
.version-history-sha,
.version-history-reason {
max-width: 100%;
overflow-wrap: anywhere;
word-break: break-word;
}
.version-history-detail pre {
max-height: none;
}
}
+140
View File
@@ -0,0 +1,140 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { fetchBuildInfo, fetchVersionHistory, reasonLabel, syncVersionHistory } from './versionHistory'
const jsonResponse = (body: unknown, status = 200) =>
Promise.resolve({ ok: status >= 200 && status < 300, status, json: () => Promise.resolve(body) } as Response)
afterEach(() => vi.unstubAllGlobals())
const pageBody = {
items: [
{
commit_sha: 'a'.repeat(40),
short_sha: 'aaaaaaaaaaaa',
parents: [],
committed_at: '2026-10-13T10:00:00Z',
author_display: '姚章浩',
subject: 'feat: 甲',
body: '正文',
record_kind: 'development',
version_label: '0.1.2',
version_state: 'verified',
release_tags: [],
release_notes: '',
commit_url: 'https://gitea.example/commit/aaa',
version_reason: 'counted_commits_since_base_tag',
is_current_running: false,
},
],
next_cursor: 'next-cursor',
has_more: true,
sync: {
available: true,
status: 'completed',
complete: true,
last_success_at: '2026-10-13T12:00:00Z',
fetched_count: 111,
expected_count: 111,
error_code: '',
source_head_sha: 'a'.repeat(40),
active_snapshot_id: 3,
repo: 'Weknora/knowledge-governance',
},
current_running: {
state: 'development',
commit_sha: 'b'.repeat(40),
display_version: '0.1.2',
matched_commit_sha: '',
},
}
describe('versionHistory client', () => {
it('loads a page, keeps the cursor and reads sync/current-running facts', async () => {
const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) => jsonResponse(pageBody))
vi.stubGlobal('fetch', fetchMock)
const page = await fetchVersionHistory({ kind: 'all', cursor: '' })
expect(fetchMock).toHaveBeenCalledOnce()
const url = String(fetchMock.mock.calls[0][0])
expect(url).toContain('/api/v1/version-history?')
expect(url).not.toContain('kind=all')
expect(url).toContain('limit=30')
expect(page.items[0].version_label).toBe('0.1.2')
expect(page.next_cursor).toBe('next-cursor')
expect(page.has_more).toBe(true)
expect(page.sync.expected_count).toBe(111)
expect(page.current_running.state).toBe('development')
})
it('passes the kind filter and cursor through', async () => {
const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) =>
jsonResponse({ ...pageBody, items: [], has_more: false })
)
vi.stubGlobal('fetch', fetchMock)
await fetchVersionHistory({ kind: 'historical', cursor: 'c-1', limit: 50 })
const url = String(fetchMock.mock.calls[0][0])
expect(url).toContain('kind=historical')
expect(url).toContain('cursor=c-1')
expect(url).toContain('limit=50')
})
it('explains an expired cursor instead of showing a raw error', async () => {
vi.stubGlobal(
'fetch',
vi.fn(() => jsonResponse({ code: 'cursor_expired' }, 409))
)
await expect(fetchVersionHistory({ kind: 'all', cursor: 'stale' })).rejects.toThrow('已被清理')
})
it('rejects malformed payloads instead of rendering half-truths', async () => {
vi.stubGlobal(
'fetch',
vi.fn(() => jsonResponse({ items: 'nope' }))
)
await expect(fetchVersionHistory({ kind: 'all', cursor: '' })).rejects.toThrow('响应无效')
})
it('posts the sync request and reports reuse', async () => {
const fetchMock = vi.fn((_input: RequestInfo | URL, _init?: RequestInit) =>
jsonResponse({ job_id: 'job-1', status: 'running', reused: true })
)
vi.stubGlobal('fetch', fetchMock)
const accepted = await syncVersionHistory()
expect(String(fetchMock.mock.calls[0][0])).toBe('/api/v1/version-history/sync')
expect(fetchMock.mock.calls[0][1]).toMatchObject({ method: 'POST' })
expect(accepted.reused).toBe(true)
})
it('says admin-only when the sync is refused', async () => {
vi.stubGlobal(
'fetch',
vi.fn(() => jsonResponse({ code: 'forbidden_role' }, 403))
)
await expect(syncVersionHistory()).rejects.toThrow('只有管理员')
})
it('never fabricates a build identity when injection is missing', async () => {
vi.stubGlobal(
'fetch',
vi.fn(() =>
jsonResponse({
release_version: '',
build_kind: 'development',
commit_sha: null,
display_version: 'dev',
built_at: '',
identity_available: false,
})
)
)
const info = await fetchBuildInfo()
expect(info.commit_sha).toBeNull()
expect(info.identity_available).toBe(false)
})
it('maps every evidence reason to a human explanation', () => {
expect(reasonLabel('lightweight_tag')).toContain('轻量 tag')
expect(reasonLabel('no_baseline')).toContain('发布基线')
expect(reasonLabel('shallow_or_incomplete_graph')).toContain('提交图不完整')
expect(reasonLabel('something_new')).toBe('版本号未能核验')
})
})
+194
View File
@@ -0,0 +1,194 @@
// 「版本记录」页的客户端:只读查询 + 管理员手动同步。
// 页面读的是本库缓存(Gitea 不可达也能看),同步动作只允许管理员触发。
export type VersionRecordKind = 'release' | 'development' | 'historical'
export type VersionState = 'verified' | 'unknown'
export type CurrentRunningState = 'matched' | 'development' | 'unknown'
export interface VersionHistoryTag {
name: string
url: string
}
export interface VersionHistoryItem {
commit_sha: string
short_sha: string
parents: string[]
committed_at: string
author_display: string
subject: string
body: string
record_kind: VersionRecordKind
version_label: string
version_state: VersionState
release_tags: VersionHistoryTag[]
release_notes: string
commit_url: string
version_reason: string
is_current_running: boolean
}
export interface VersionHistorySyncState {
available: boolean
status: string
complete: boolean
last_success_at: string
fetched_count: number
expected_count: number | null
error_code: string
source_head_sha: string
active_snapshot_id: number
repo: string
}
export interface VersionHistoryCurrentRunning {
state: CurrentRunningState
commit_sha: string
display_version: string
matched_commit_sha: string
}
export interface VersionHistoryPage {
items: VersionHistoryItem[]
next_cursor: string
has_more: boolean
sync: VersionHistorySyncState
current_running: VersionHistoryCurrentRunning
}
export interface BuildInfo {
release_version: string
build_kind: string
commit_sha: string | null
display_version: string
built_at: string
identity_available: boolean
}
export interface SyncAccepted {
job_id: string
status: string
reused: boolean
}
const record = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null
const text = (value: unknown): string => (typeof value === 'string' ? value : '')
const bool = (value: unknown): boolean => value === true
const count = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)
// 「版本号未能核验」的原因码 → 页面文案(不补造版本号,只解释为什么没有号)。
export const reasonLabels: Record<string, string> = {
annotated_tag_and_changelog_top_match: '注释 tag 与提交内版本记录一致',
counted_commits_since_base_tag: '按发布基线数出来的开发号',
lightweight_tag: '该提交上的 tag 是轻量 tag,不作为正式版本证据',
no_changelog_top: '该提交内没有已发布版本的变更记录',
changelog_top_mismatch: 'tag 版本与该提交内的变更记录不一致',
no_release_tag_for_commit: '没有指向该提交的正式 tag',
no_baseline: '找不到可核验的发布基线(该版本没有对应的 tag)',
shallow_or_incomplete_graph: '提交图不完整(检出被截断),提交数算不准',
}
export const reasonLabel = (reason: string): string => reasonLabels[reason] ?? '版本号未能核验'
const parseItem = (value: unknown): VersionHistoryItem => {
if (!record(value)) throw new Error('版本记录条目无效')
return {
commit_sha: text(value.commit_sha),
short_sha: text(value.short_sha),
parents: Array.isArray(value.parents)
? value.parents.filter((item): item is string => typeof item === 'string')
: [],
committed_at: text(value.committed_at),
author_display: text(value.author_display),
subject: text(value.subject),
body: text(value.body),
record_kind: (text(value.record_kind) || 'historical') as VersionRecordKind,
version_label: text(value.version_label),
version_state: (text(value.version_state) || 'unknown') as VersionState,
release_tags: Array.isArray(value.release_tags)
? value.release_tags.filter(record).map((tag) => ({ name: text(tag.name), url: text(tag.url) }))
: [],
release_notes: text(value.release_notes),
commit_url: text(value.commit_url),
version_reason: text(value.version_reason),
is_current_running: bool(value.is_current_running),
}
}
export async function fetchVersionHistory(
params: { kind: string; cursor: string; limit?: number },
signal?: AbortSignal
): Promise<VersionHistoryPage> {
const query = new URLSearchParams()
if (params.kind && params.kind !== 'all') query.set('kind', params.kind)
if (params.cursor) query.set('cursor', params.cursor)
query.set('limit', String(params.limit ?? 30))
const response = await fetch(`/api/v1/version-history?${query.toString()}`, {
headers: { Accept: 'application/json' },
signal,
})
const value = (await response.json().catch(() => null)) as unknown
if (!response.ok) {
const code = record(value) ? text(value.code) : ''
if (response.status === 409 || code === 'cursor_expired') {
throw new Error('这次翻页依据的记录快照已被清理,请刷新页面重新加载。')
}
throw new Error(`加载版本记录失败(HTTP ${response.status})`)
}
if (!record(value) || !Array.isArray(value.items) || !record(value.sync) || !record(value.current_running)) {
throw new Error('版本记录响应无效')
}
const sync = value.sync
const running = value.current_running
const expected = typeof sync.expected_count === 'number' ? sync.expected_count : null
return {
items: value.items.map(parseItem),
next_cursor: text(value.next_cursor),
has_more: bool(value.has_more),
sync: {
available: bool(sync.available),
status: text(sync.status),
complete: bool(sync.complete),
last_success_at: text(sync.last_success_at),
fetched_count: count(sync.fetched_count),
expected_count: expected,
error_code: text(sync.error_code),
source_head_sha: text(sync.source_head_sha),
active_snapshot_id: count(sync.active_snapshot_id),
repo: text(sync.repo),
},
current_running: {
state: (text(running.state) || 'unknown') as CurrentRunningState,
commit_sha: text(running.commit_sha),
display_version: text(running.display_version),
matched_commit_sha: text(running.matched_commit_sha),
},
}
}
export async function syncVersionHistory(): Promise<SyncAccepted> {
const response = await fetch('/api/v1/version-history/sync', {
method: 'POST',
headers: { Accept: 'application/json' },
})
const value = (await response.json().catch(() => null)) as unknown
if (!response.ok) {
throw new Error(response.status === 403 ? '只有管理员能触发同步。' : `触发同步失败(HTTP ${response.status})`)
}
if (!record(value)) throw new Error('同步响应无效')
return { job_id: text(value.job_id), status: text(value.status), reused: bool(value.reused) }
}
export async function fetchBuildInfo(signal?: AbortSignal): Promise<BuildInfo> {
const response = await fetch('/api/v1/build-info', { headers: { Accept: 'application/json' }, signal })
if (!response.ok) throw new Error(`读取当前运行版本失败(HTTP ${response.status})`)
const value = (await response.json()) as unknown
if (!record(value)) throw new Error('构建身份响应无效')
return {
release_version: text(value.release_version),
build_kind: text(value.build_kind),
commit_sha: typeof value.commit_sha === 'string' ? value.commit_sha : null,
display_version: text(value.display_version),
built_at: text(value.built_at),
identity_available: bool(value.identity_available),
}
}
+4 -9
View File
@@ -1,16 +1,11 @@
export type ModuleId = 'dashboard' | 'sources' | 'knowledge' | 'tasks' | 'releases' | 'settings'
export type ModuleId = 'dashboard' | 'sources' | 'knowledge' | 'tasks' | 'releases' | 'settings' | 'versions'
export interface WorkspaceState {
openTabs: ModuleId[]
activeTab: ModuleId
}
const moduleIds = new Set<ModuleId>([
'dashboard',
'tasks',
'releases',
'settings',
])
const moduleIds = new Set<ModuleId>(['dashboard', 'tasks', 'releases', 'settings'])
export const initialWorkspace: WorkspaceState = {
openTabs: ['dashboard'],
@@ -45,10 +40,10 @@ export function restoreWorkspace(raw: string | null): WorkspaceState {
const saved = JSON.parse(raw) as { openTabs?: unknown; activeTab?: unknown }
if (!Array.isArray(saved.openTabs)) return initialWorkspace
const restoredTabs = saved.openTabs.filter(
(value): value is ModuleId => typeof value === 'string' && moduleIds.has(value as ModuleId),
(value): value is ModuleId => typeof value === 'string' && moduleIds.has(value as ModuleId)
)
const openTabs = ['dashboard', ...restoredTabs.filter((tab) => tab !== 'dashboard')].filter(
(tab, index, tabs) => tabs.indexOf(tab) === index,
(tab, index, tabs) => tabs.indexOf(tab) === index
) as ModuleId[]
const activeTab =
typeof saved.activeTab === 'string' &&