Files
knowledge-governance/web/src/VersionHistory.tsx
姚章浩 e34306b2db
build / build (push) Failing after 18s
fix(ui): 已释放窗口不再渲染 held 文案,版本页不再把 500 说成未接线
发布管理:maintenanceSummary 只看 job.state === 'failed' 就给 held 处置文案;
窗口已 released 的旧作业(libsync-internal-1793399248431728863)因此自相矛盾。
改为仅 held 时给 recoveryError,已释放时给 releasedFailure(如实记录失败,不提供强制成功)。

版本记录:LoadVersionHistorySyncState 把可空的 finished_at 扫进 time.Time;
部署重启触发的同步在"进行中"时该列为 NULL,扫描失败使整页 500
(nginx access log:GET /api/v1/version-history?limit=30 → 500,74 字节错误体)。
改为指针接值再判空。前端同时区分"未配置/加载失败"并显示服务端 code。

RED/GREEN:新增 Go 集成用例(NULL finished_at)、两条前端用例;
make verify 16/16 通过(local 档案)。
2026-11-01 19:34:31 +08:00

440 lines
16 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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、已交付开发快照及当前运行 SHA 的提交,按提交时间倒序。
// 只读:不提供打 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 && Number.isFinite(new Date(value).getTime())
? new Date(value).toLocaleString('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
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 | undefined
canSync: boolean
onRefresh: () => void
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 ?? []
const expandedSHA =
props.expanded === undefined
? (items.find(
(item) =>
page?.current_running.state === 'matched' && item.commit_sha === page.current_running.matched_commit_sha
)?.commit_sha ??
items[0]?.commit_sha ??
null)
: props.expanded
return (
<section className="version-history" aria-label="版本记录">
<header className="version-history-header">
<div>
<h2>版本记录</h2>
<p>查看当前构建,以及每次更新带来的变化。</p>
</div>
<div className="version-history-actions">
<button type="button" onClick={props.onRefresh} disabled={props.loading}>
刷新
</button>
{props.canSync ? (
<button
type="button"
onClick={props.onSync}
disabled={
props.loading ||
!page?.sync.available ||
page.sync.status === 'running' ||
page.sync.status === 'pending'
}
>
{page?.sync.status === 'running' || page?.sync.status === 'pending' ? '同步进行中…' : '同步记录'}
</button>
) : null}
</div>
</header>
<section className="version-history-current-card" aria-label="当前版本">
<h3>当前版本</h3>
<dl className="version-history-build-grid">
<div>
<dt>运行版本</dt>
<dd className="version-history-running-version">
{page
? page.current_running.state === 'unknown'
? '未知'
: page.current_running.display_version
: build?.identity_available
? build.display_version
: '未知'}
</dd>
</div>
<div>
<dt>构建类型</dt>
<dd>
{build?.build_kind === 'development' ? '开发构建' : build?.build_kind === 'release' ? '正式构建' : '未知'}
</dd>
</div>
<div>
<dt>提交</dt>
<dd className="version-history-sha">
{(page ? page.current_running.commit_sha : build?.identity_available ? build.commit_sha : '') || '—'}
</dd>
</div>
<div>
<dt>构建时间(北京时间)</dt>
<dd>
{build && (!page || build.commit_sha === page.current_running.commit_sha) ? stamp(build.built_at) : '—'}
</dd>
</div>
</dl>
<p className="version-history-running-state">
{page
? runningText(page.current_running)
: props.error
? '当前运行标记不可用:版本记录加载失败(原因见下方),不是"未配置"'
: '正在读取当前运行版本…'}
</p>
</section>
<section className="version-history-records" aria-label="版本变更列表">
<div className="version-history-records-heading">
<h3>每一版改了什么</h3>
<p>记录来自仓库,只读展示,不执行发布或部署。</p>
</div>
<p className="version-history-sync-line">
{page ? syncText(page.sync) : props.error ? '同步状态不可用:请求失败' : '正在读取同步状态…'}
{page?.sync.status === 'running' || page?.sync.status === 'pending' ? (
<span className="version-history-badge pending">同步中</span>
) : null}
{page?.sync.status === 'failed' ? <span className="version-history-badge warn">同步失败</span> : null}
</p>
{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">
{props.error
? '列表加载失败:这不是"未接线",请按上方错误码排查后重试'
: 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={expandedSHA === item.commit_sha}
onExpand={() => props.onExpand(expandedSHA === 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>
</section>
)
}
function ChangeNotes({ text }: { text: string }) {
const categories: Record<string, { label: string; tone: string }> = {
Added: { label: '新增', tone: 'added' },
Changed: { label: '调整', tone: 'changed' },
Fixed: { label: '修复', tone: 'fixed' },
Security: { label: '安全', tone: 'security' },
}
let category = { label: '说明', tone: 'note' }
return (
<div className="version-history-notes">
{text.split(/\r?\n/).map((line, index) => {
const trimmed = line.trim()
if (!trimmed) return null
const heading = /^#{1,6}\s+(.+)$/.exec(trimmed)
if (heading) {
if (categories[heading[1]]) {
category = categories[heading[1]]
return null
}
return <h4 key={index}>{heading[1]}</h4>
}
const content = trimmed.replace(/^[-*]\s+/, '')
return (
<p className="version-history-change-row" key={index}>
<span className={'version-history-change-tag ' + category.tone}>{category.label}</span>
<span>
{content
.split(/(\*\*[^*]+\*\*|`[^`]+`)/g)
.map((part, i) =>
part.startsWith('**') && part.endsWith('**') ? (
<strong key={i}>{part.slice(2, -2)}</strong>
) : part.startsWith('`') && part.endsWith('`') ? (
<code key={i}>{part.slice(1, -1)}</code>
) : (
part
)
)}
</span>
</p>
)
})}
</div>
)
}
function TimelineEntry({
item,
currentMatchedSHA,
expanded,
onExpand,
}: {
item: VersionHistoryItem
currentMatchedSHA: string
expanded: boolean
onExpand: () => void
}) {
const heading = item.version_label || `历史提交 · ${item.short_sha}`
const note = item.version_state === 'verified' ? item.release_notes : ''
const isCurrent = Boolean(item.commit_sha && item.commit_sha === currentMatchedSHA)
const detailID = 'version-detail-' + item.commit_sha
return (
<li
className={`version-history-entry ${item.record_kind}${isCurrent ? ' is-current' : ''}`}
data-version-commit={item.commit_sha}
>
<button
type="button"
className="version-history-entry-head"
onClick={onExpand}
aria-expanded={expanded}
aria-controls={detailID}
>
<strong className={`version-history-version ${item.record_kind}`}>{heading}</strong>
<span className={`version-history-badge ${item.record_kind}`}>{kindLabel[item.record_kind] ?? '历史提交'}</span>
{isCurrent ? <span className="version-history-badge current">当前运行</span> : null}
<span className="version-history-sha" title={item.commit_sha}>
{item.short_sha}
</span>
<time dateTime={item.committed_at}>{stamp(item.committed_at)}</time>
<span className="version-history-subject">{item.subject.replace(/^[a-z]+(?:\([^)]+\))?!?:\s*/, '')}</span>
<span className="version-history-toggle">{expanded ? '收起详情' : '展开详情'}</span>
</button>
{!item.version_label && item.record_kind === 'historical' ? (
<p className="version-history-reason">版本号未能核验:{reasonLabel(item.version_reason)}</p>
) : null}
{expanded ? (
<div className="version-history-detail" id={detailID}>
{note ? (
<ChangeNotes text={note} />
) : (
<p className="version-history-no-notes">此提交未附单独的变更说明,可查看下方原始提交。</p>
)}
<details className="version-history-technical">
<summary>原始记录与提交信息</summary>
<dl>
<div>
<dt>提交</dt>
<dd className="version-history-sha">{item.commit_sha}</dd>
</div>
<div>
<dt>作者</dt>
<dd>{item.author_display || '—'}</dd>
</div>
<div>
<dt>提交标题</dt>
<dd>{item.subject}</dd>
</div>
</dl>
{note ? <pre>{note}</pre> : null}
{item.body ? <pre>{item.body}</pre> : null}
<div className="version-history-links">
{item.commit_url ? (
<a href={item.commit_url} target="_blank" rel="noreferrer noopener">
查看提交
</a>
) : null}
{item.release_tags
.filter((tag) => tag.url)
.map((tag) => (
<a key={tag.name} href={tag.url} target="_blank" rel="noreferrer noopener">
查看 tag {tag.name}
</a>
))}
</div>
</details>
</div>
) : null}
</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 | undefined>(undefined)
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,
onRefresh: () => void load(filter, false),
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} />
}