Files
knowledge-governance/web/src/App.tsx
T
姚章浩 63f3b2c503 feat(governance): policy-driven ingestion from catalog annotations
Annotation in 来源与目录 is now the only import decision surface:
- migration 000033: catalog_import_intents (durable, rescan-proof per-file
  intent with locator snapshot + fetch lifecycle), source_items.policy_state,
  planned publication state, ui_setting_revisions.ingestion_concurrency
- marking fans a folder decision out to per-file intents, materializes
  versioned items, reuses already-verified local bytes (compare, don't pull),
  and plans one publication per routed KB; blocked retires planned rows
  while live publications stay untouched (需下架 shows in the KB diff)
- artifact.fetch worker lane (scripts/artifact_fetch.py): DingTalk export
  tree/live box API, AList /api/fs/get direct download with SSO-redirect
  fail-closed, PP ledger via locator hash; content-level dedupe on sha256
- 开始处理 promotes planned->pending inside the claim-time concurrency budget
  from system settings; claims enforce it in SQL
- monitor overview rebuilt as knowledge-base diff: planned/needs_removal per
  KB + fetch pipeline summary; frontend lanes 待入库/需下架 replace the
  deprecated snapshot change-set confirmation
- spool: images (png/jpg/gif/bmp/webp) accepted, ppt/pptx rejected in favour
  of PDF twins; DingTalk PPT resolves its converted PDF pair
2026-09-30 10:54:07 +08:00

1577 lines
92 KiB
TypeScript
Raw 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, useState } from 'react'
import { TopBarUser } from './auth'
import { DocumentWorkbench } from './DocumentWorkbench'
import { SourceCatalogBrowser } from './SourceCatalogBrowser'
import { WeKnoraMonitor } from './WeKnoraMonitor'
import { SourceLinkManager } from './SourceLinkManager'
import { SystemSettings } from './SystemSettings'
import { WorkspaceContextTabsBar, WorkspaceContextTabsSetter } from './workspaceContext'
import type { WorkspaceContextTab } from './workspaceContext'
import { fetchSourceAssets } from './assets'
import type { LegacyStatus, SourceAssetPage } from './assets'
import { fetchJobs } from './jobs'
import type { Job, JobState } from './jobs'
import { confirmReleaseChangeSet, createReleaseBatch, fetchLatestReleaseChangeSet, fetchReleaseAuditChain, fetchReleaseBatch, fetchReleaseBatches, fetchReleaseCapabilities, fetchReleaseExecution, fetchReleaseExecutions, fetchReleasePlan, fetchReviewCandidates, generateReleaseChangeSet, reviewPublication, sealReleaseBatch } from './reviewRelease'
import type { ReleaseAuditChain, ReleaseBatchDetail, ReleaseBatchPage, ReleaseCapabilities, ReleaseChangeSetDetail, ReleaseExecutionDetail, ReleaseExecutionPage, ReleasePlan, ReleasePlanItem, ReviewCandidatePage, Visibility } from './reviewRelease'
import { fetchSourceConnections, fetchSourceScanDetail, fetchSourceScans, triggerSourceScan } from './sourceConnections'
import type { SourceConnectionPage, SourceScanDetail, SourceScanPage } from './sourceConnections'
import { fetchTestPublications, retryPublication } from './testPublications'
import type { ProcessingState, TestPublicationPage } from './testPublications'
import { closeModule, initialWorkspace, openModule, restoreWorkspace } from './workspace'
import type { ModuleId, WorkspaceState } from './workspace'
const workspaceStorageKey = 'knowledge-governance.workspace.v1'
const modules: ReadonlyArray<{ id: ModuleId; label: string; icon: string }> = [
{ id: 'dashboard', label: '来源与目录', icon: '◫' },
{ id: 'tasks', label: '解析监控', icon: '↻' },
{ id: 'releases', label: '发布管理', icon: '⇧' },
{ id: 'settings', label: '系统设置', icon: '⚙' },
]
interface WorkspaceShellProps {
workspace: WorkspaceState
onOpen: (moduleId: ModuleId) => void
onClose: (moduleId: ModuleId) => void
children: React.ReactNode
}
export function WorkspaceShell(props: WorkspaceShellProps) {
const [navigationOpen, setNavigationOpen] = useState(false)
const [contextTabs, setContextTabs] = useState<WorkspaceContextTab[]>([])
const activeModule = modules.find((item) => item.id === props.workspace.activeTab)
return (
<WorkspaceContextTabsSetter.Provider value={setContextTabs}>
<div className="app-workspace">
<aside className={navigationOpen ? 'sidebar open' : 'sidebar'}>
<div className="brand">
<span className="brand-mark" aria-hidden="true">治</span>
<div>
<strong>知识治理</strong>
<span>governance console</span>
</div>
</div>
<nav className="sidebar-nav" aria-label="功能导航">
{modules.map((module) => (
<button
className={props.workspace.activeTab === module.id ? 'nav-item active' : 'nav-item'}
key={module.id}
type="button"
onClick={() => {
props.onOpen(module.id)
setNavigationOpen(false)
}}
>
<span className="nav-icon" aria-hidden="true">{module.icon}</span>
<span>{module.label}</span>
</button>
))}
</nav>
<div className="sidebar-footer">
<span className="status-dot" aria-hidden="true" />
本地治理环境
</div>
</aside>
{navigationOpen ? (
<button
className="sidebar-backdrop"
type="button"
aria-label="关闭功能导航"
onClick={() => setNavigationOpen(false)}
/>
) : null}
<section className="workspace-main">
<header className="workspace-topbar">
<button
className="mobile-nav-toggle"
type="button"
aria-label="切换功能导航"
aria-expanded={navigationOpen}
onClick={() => setNavigationOpen((open) => !open)}
>
☰
</button>
<div className="workspace-topbar-crumb" aria-label="当前位置">
<span className="crumb-root">知识治理</span>
<span className="crumb-sep" aria-hidden="true">/</span>
<b>{activeModule?.label ?? '工作台'}</b>
</div>
<div className="tab-list" role="tablist" aria-label="已打开页面">
{props.workspace.openTabs.map((tabId) => {
const module = modules.find((item) => item.id === tabId)
if (!module) return null
const active = props.workspace.activeTab === tabId
return (
<div
className={active ? 'workspace-tab active' : 'workspace-tab'}
key={tabId}
>
<button
className="tab-activate"
type="button"
role="tab"
aria-current={active ? 'page' : undefined}
aria-selected={active}
onClick={() => props.onOpen(tabId)}
>
<span aria-hidden="true">{module.icon}</span>
{module.label}
</button>
{tabId !== 'dashboard' ? (
<button
className="tab-close"
type="button"
aria-label={`关闭${module.label}标签`}
onClick={() => props.onClose(tabId)}
>
×
</button>
) : null}
</div>
)
})}
</div>
<WorkspaceContextTabsBar tabs={contextTabs} />
<TopBarUser />
</header>
<div className="workspace-content">{props.children}</div>
</section>
</div>
</WorkspaceContextTabsSetter.Provider>
)
}
const stateLabels: Record<JobState, string> = {
pending: '待处理',
running: '运行中',
retry: '待重试',
completed: '已完成',
failed: '失败',
}
interface JobDashboardProps {
jobs: Job[]
loading: boolean
error: string | null
onRefresh: () => void
}
interface ModulePageProps extends JobDashboardProps {
moduleId: ModuleId
connectionPage?: SourceConnectionPage
connectionLoading?: boolean
connectionError?: string | null
onConnectionRefresh?: () => void
scanningConnectionId?: string | null
onTriggerSourceScan?: (id: string) => void
scanPage?: SourceScanPage
scanDetail?: SourceScanDetail | null
scanLoading?: boolean
scanError?: string | null
selectedScanId?: string | null
onSelectScan?: (connectionID: string, scanID: string) => void
assetPage?: SourceAssetPage
assetLoading?: boolean
assetError?: string | null
assetState?: LegacyStatus | ''
onAssetStateChange?: (state: LegacyStatus | '') => void
onAssetPageChange?: (offset: number) => void
onAssetRefresh?: () => void
publicationPage?: TestPublicationPage
publicationLoading?: boolean
publicationError?: string | null
publicationState?: ProcessingState | ''
retryingId?: string | null
onPublicationStateChange?: (state: ProcessingState | '') => void
onPublicationPageChange?: (offset: number) => void
onPublicationRefresh?: () => void
onRetry?: (id: string) => void
reviewPage?: ReviewCandidatePage
reviewLoading?: boolean
reviewError?: string | null
reviewingId?: string | null
batchPage?: ReleaseBatchPage
batchDetail?: ReleaseBatchDetail | null
batchLoading?: boolean
batchError?: string | null
mutatingBatchId?: string | null
onReview?: ReleaseManagementProps['onReview']
onReviewRefresh?: () => void
onCreateBatch?: ReleaseManagementProps['onCreateBatch']
onSealBatch?: ReleaseManagementProps['onSealBatch']
onSelectBatch?: ReleaseManagementProps['onSelectBatch']
onBatchRefresh?: () => void
releaseCapabilities?: ReleaseCapabilities
releasePlan?: ReleasePlan
releaseChangeSet?: ReleaseChangeSetDetail | null
changeSetBusy?: boolean
changeSetError?: string | null
onGenerateChangeSet?: (name: string) => void
onConfirmChangeSet?: (changeSetID: string) => void
selectedDeleteIDs?: string[]
onToggleDelete?: (publicationID: string) => void
executionPage?: ReleaseExecutionPage
executionDetail?: ReleaseExecutionDetail | null
executionChain?: ReleaseAuditChain | null
executionLoading?: boolean
executionError?: string | null
onSelectExecution?: (executionID: string) => void
onExecutionRefresh?: () => void
}
const emptyAssetPage: SourceAssetPage = { items: [], summary: { total: 0, completed: 0, content_alias: 0, over_limit: 0 }, limit: 50, offset: 0 }
const emptyConnectionPage: SourceConnectionPage = { items: [], summary: { total: 0, enabled: 0, disabled: 0, healthy: 0, degraded: 0, unhealthy: 0, unknown: 0 } }
const emptyScanPage: SourceScanPage = { items: [], total: 0, limit: 20, offset: 0 }
const emptyPublicationPage: TestPublicationPage = { items: [], total: 0, limit: 50, offset: 0 }
const emptyReviewPage: ReviewCandidatePage = { items: [], total: 0, limit: 20, offset: 0 }
const emptyBatchPage: ReleaseBatchPage = { items: [], total: 0, limit: 20, offset: 0 }
const emptyExecutionPage: ReleaseExecutionPage = { items: [], total: 0, limit: 20, offset: 0 }
const disabledReleaseCapabilities: ReleaseCapabilities = { production_release_requests_enabled: false, production_backup_restore_verified: false }
const emptyReleasePlan: ReleasePlan = { items: [], summary: { add: 0, update: 0, delete: 0, blocked: 0, unchanged: 0 } }
export function ModulePage({ moduleId, jobs, loading, error, onRefresh, connectionPage = emptyConnectionPage, connectionLoading = false, connectionError = null, onConnectionRefresh = () => undefined, scanningConnectionId = null, onTriggerSourceScan = () => undefined, scanPage = emptyScanPage, scanDetail = null, scanLoading = false, scanError = null, selectedScanId = null, onSelectScan = () => undefined, assetPage = emptyAssetPage, assetLoading = false, assetError = null, assetState = '', onAssetStateChange = () => undefined, onAssetPageChange = () => undefined, onAssetRefresh = () => undefined, publicationPage = emptyPublicationPage, publicationLoading = false, publicationError = null, publicationState = '', retryingId = null, onPublicationStateChange = () => undefined, onPublicationPageChange = () => undefined, onPublicationRefresh = () => undefined, onRetry = () => undefined, reviewPage = emptyReviewPage, reviewLoading = false, reviewError = null, reviewingId = null, batchPage = emptyBatchPage, batchDetail = null, batchLoading = false, batchError = null, mutatingBatchId = null, onReview = () => undefined, onReviewRefresh = () => undefined, onCreateBatch = () => undefined, onSealBatch = () => undefined, onSelectBatch = () => undefined, onBatchRefresh = () => undefined, releaseCapabilities = disabledReleaseCapabilities, releasePlan = emptyReleasePlan, releaseChangeSet = null, changeSetBusy = false, changeSetError = null, onGenerateChangeSet = () => undefined, onConfirmChangeSet = () => undefined, selectedDeleteIDs = [], onToggleDelete = () => undefined, executionPage = emptyExecutionPage, executionDetail = null, executionChain = null, executionLoading = false, executionError = null, onSelectExecution = () => undefined, onExecutionRefresh = () => undefined }: ModulePageProps) {
if (moduleId === 'tasks') {
return <TestPublications page={publicationPage} loading={publicationLoading} error={publicationError} state={publicationState} retryingId={retryingId} onStateChange={onPublicationStateChange} onPageChange={onPublicationPageChange} onRefresh={onPublicationRefresh} onRetry={onRetry} />
}
if (moduleId === 'knowledge') {
return <KnowledgeInventory page={assetPage} loading={assetLoading} error={assetError} state={assetState} onStateChange={onAssetStateChange} onPageChange={onAssetPageChange} onRefresh={onAssetRefresh} />
}
if (moduleId === 'sources') {
return <SourceConnections page={connectionPage} loading={connectionLoading} error={connectionError} scanningConnectionId={scanningConnectionId} scanPage={scanPage} scanDetail={scanDetail} scanLoading={scanLoading} scanError={scanError} selectedScanId={selectedScanId} onRefresh={onConnectionRefresh} onTriggerScan={onTriggerSourceScan} onSelectScan={onSelectScan} />
}
if (moduleId === 'releases') {
return <ReleaseManagement reviewPage={reviewPage} reviewLoading={reviewLoading} reviewError={reviewError} reviewingId={reviewingId} batchPage={batchPage} batchDetail={batchDetail} batchLoading={batchLoading} batchError={batchError} mutatingBatchId={mutatingBatchId} onReview={onReview} onReviewRefresh={onReviewRefresh} onCreateBatch={onCreateBatch} onSealBatch={onSealBatch} onSelectBatch={onSelectBatch} onBatchRefresh={onBatchRefresh} releaseCapabilities={releaseCapabilities} releasePlan={releasePlan} releaseChangeSet={releaseChangeSet} changeSetBusy={changeSetBusy} changeSetError={changeSetError} onGenerateChangeSet={onGenerateChangeSet} onConfirmChangeSet={onConfirmChangeSet} selectedDeleteIDs={selectedDeleteIDs} onToggleDelete={onToggleDelete} executionPage={executionPage} executionDetail={executionDetail} executionChain={executionChain} executionLoading={executionLoading} executionError={executionError} onSelectExecution={onSelectExecution} onExecutionRefresh={onExecutionRefresh} />
}
if (moduleId === 'settings') {
return <SystemSettings />
}
const counts = {
total: jobs.length,
running: jobs.filter((job) => job.state === 'running').length,
retry: jobs.filter((job) => job.state === 'retry').length,
failed: jobs.filter((job) => job.state === 'failed').length,
completed: jobs.filter((job) => job.state === 'completed').length,
}
return (
<main className="page-shell">
<header className="hero">
<div>
<p className="eyebrow">P2 · 知识治理总览</p>
<h1>治理工作台</h1>
<p className="subtitle">集中查看任务状态与平台安全边界。</p>
</div>
<button type="button" onClick={onRefresh} disabled={loading}>
{loading ? '刷新中…' : '刷新数据'}
</button>
</header>
{error ? <div className="error-banner" role="alert">{error}</div> : null}
<section className="summary-grid" aria-label="任务概览">
<SummaryCard label="任务总数" value={counts.total} tone="blue" />
<SummaryCard label="运行中" value={counts.running} tone="cyan" />
<SummaryCard label="待重试" value={counts.retry} tone="amber" />
<SummaryCard label="失败" value={counts.failed} tone="red" />
<SummaryCard label="已完成" value={counts.completed} tone="green" />
</section>
<section className="safety-strip">
<div>
<strong>运行安全</strong>
<span>PP历史来源清单已接管;本地测试WeKnora已连接,生产WeKnora仍未连接。</span>
</div>
<span className="safe-badge">Release Worker 默认关闭</span>
</section>
<section className="panel dashboard-recent">
<div className="panel-heading">
<div>
<h2>最近任务</h2>
<p>显示最近5条真实队列记录</p>
</div>
</div>
{!loading && !error && jobs.length === 0 ? (
<div className="empty-state">暂无任务。可前往“同步任务”查看队列详情。</div>
) : null}
{jobs.length > 0 ? (
<div className="recent-list">
{jobs.slice(0, 5).map((job) => (
<article className="recent-row" key={job.id}>
<div>
<strong>{job.type}</strong>
<code>{job.id}</code>
</div>
<span className={`status status-${job.state}`}>{stateLabels[job.state]}</span>
<time dateTime={job.updated_at}>{formatTime(job.updated_at)}</time>
</article>
))}
</div>
) : null}
</section>
</main>
)
}
interface KnowledgeInventoryProps {
page: SourceAssetPage
loading: boolean
error: string | null
state: LegacyStatus | ''
onStateChange: (state: LegacyStatus | '') => void
onPageChange: (offset: number) => void
onRefresh: () => void
}
const legacyStatusLabels: Record<LegacyStatus, string> = {
completed: '历史已同步',
content_alias: '内容别名',
over_limit: '超过旧同步上限',
}
const sourceTypeLabels: Record<string, string> = {
pp: 'PP',
alist: 'AList',
dingtalk: '钉钉',
manual: '手工验收',
}
const sourceHealthLabels: Record<string, string> = {
unknown: '未检查',
healthy: '健康',
degraded: '降级',
unhealthy: '异常',
}
interface SourceConnectionsProps {
page: SourceConnectionPage
loading: boolean
error: string | null
scanningConnectionId: string | null
scanPage: SourceScanPage
scanDetail: SourceScanDetail | null
scanLoading: boolean
scanError: string | null
selectedScanId: string | null
onRefresh: () => void
onTriggerScan: (id: string) => void
onSelectScan: (connectionID: string, scanID: string) => void
}
const sourceScanLabels: Record<string, string> = {
pending: '待扫描',
running: '扫描中',
completed: '已完成',
failed: '失败',
}
const sourceScanChangeLabels: Record<string, string> = {
added: '新增内容',
updated: '内容更新',
unavailable: '来源不可用',
}
export function SourceConnections({ page, loading, error, scanningConnectionId, scanPage, scanDetail, scanLoading, scanError, selectedScanId, onRefresh, onTriggerScan, onSelectScan }: SourceConnectionsProps) {
const attention = page.summary.degraded + page.summary.unhealthy
const scannableConnectionID = page.items.find((item) => item.source_type === 'pp')?.id ?? ''
return (
<main className="page-shell">
<header className="hero">
<div>
<p className="eyebrow">连接情况</p>
<h1>来源连接</h1>
<p className="subtitle">查看来源是否可读、多久检查一次。日常文件操作请进入“来源与目录”。</p>
</div>
<button type="button" onClick={onRefresh} disabled={loading}>{loading ? '刷新中…' : '刷新来源'}</button>
</header>
{error ? <div className="error-banner" role="alert">{error}</div> : null}
<section className="summary-grid" aria-label="来源连接概览">
<SummaryCard label="来源连接" value={page.summary.total} tone="blue" />
<SummaryCard label="已启用" value={page.summary.enabled} tone="green" />
<SummaryCard label="已停用" value={page.summary.disabled} tone="cyan" />
<SummaryCard label="健康" value={page.summary.healthy} tone="green" />
<SummaryCard label="需关注" value={attention} tone="amber" />
</section>
<section className="panel">
<div className="panel-heading">
<div><h2>来源连接</h2><p>PP检查的是本机已保存快照,不是实时拉取网站。检查不会修改来源,也不会自动上传或删除文件。</p></div>
<span className="safe-badge">来源只读</span>
</div>
{!loading && !error && page.items.length === 0 ? <div className="empty-state">尚无来源连接。</div> : null}
{page.items.length > 0 ? (
<div className="table-wrap"><table className="source-connections-table"><thead><tr><th>连接</th><th>类型</th><th>状态</th><th>调度</th><th>健康</th><th>对象数</th><th>最近扫描</th><th>操作</th></tr></thead><tbody>
{page.items.map((item) => {
const activeScan = item.last_scan?.state === 'pending' || item.last_scan?.state === 'running'
return <tr key={item.id}>
<td className="source-connection-name"><strong>{item.name.startsWith('PP legacy ') ? 'PP公开文档' : item.name}</strong></td>
<td>{sourceTypeLabels[item.source_type] ?? item.source_type}</td>
<td><span className={`status status-${item.enabled ? 'completed' : 'pending'}`}>{item.enabled ? '已启用' : '已停用'}</span></td>
<td>{item.schedule_configured ? '已配置' : '未配置'}</td>
<td><span className={`status status-${sourceHealthClass(item.health_status)}`}>{sourceHealthLabels[item.health_status] ?? item.health_status}</span></td>
<td>{item.item_count}</td>
<td>{item.last_scan ? <div className="source-scan-summary">
<strong>最近扫描 · {sourceScanLabels[item.last_scan.state] ?? item.last_scan.state}</strong>
<span>观察 {item.last_scan.observed_items} · 未变化 {item.last_scan.unchanged_items}</span>
<span>新增 {item.last_scan.added_items} · 更新 {item.last_scan.updated_items} · 缺失 {item.last_scan.missing_items}</span>
<span>超过上限 {item.last_scan.over_limit_items} · 待上传 {item.last_scan.planned_uploads}</span>
{item.last_scan.error_code ? <code>{item.last_scan.error_code}</code> : null}
</div> : '尚未扫描'}</td>
<td>{item.source_type === 'pp' ? <button type="button" onClick={() => onTriggerScan(item.id)} disabled={loading || scanningConnectionId === item.id || activeScan}>{scanningConnectionId === item.id || activeScan ? '检查中…' : '检查快照变化'}</button> : '暂未支持检查'}</td>
</tr>
})}
</tbody></table></div>
) : null}
</section>
<details className="panel scan-audit-panel"><summary className="panel-heading">查看检查历史与审计记录</summary>
<div className="panel-heading">
<div><h2>扫描历史与变化记录</h2><p>展示安全聚合和治理侧变化标识;不展示来源路径、修订值或快照指纹。</p></div>
<span className="safe-badge">审计只读</span>
</div>
{scanError ? <div className="error-banner" role="alert">{scanError}</div> : null}
{!scanLoading && !scanError && scanPage.items.length === 0 ? <div className="empty-state">当前来源尚无扫描历史。</div> : null}
{scanPage.items.length > 0 ? <div className="scan-audit-grid">
<div className="table-wrap"><table className="source-scan-history-table"><thead><tr><th>扫描</th><th>状态</th><th>观察</th><th>变化</th><th>上限阻断</th><th>操作</th></tr></thead><tbody>
{scanPage.items.map((scan) => <tr key={scan.id} className={selectedScanId === scan.id ? 'selected-row' : undefined}>
<td><code>{scan.id}</code><time dateTime={scan.created_at}>{formatTime(scan.created_at)}</time></td>
<td><span className={`status status-${scan.state}`}>{sourceScanLabels[scan.state] ?? scan.state}</span></td>
<td>{scan.observed_items}</td>
<td>新增 {scan.added_items} · 更新 {scan.updated_items} · 缺失 {scan.missing_items}</td>
<td>{scan.over_limit_items}</td>
<td><button type="button" disabled={scanLoading || !scannableConnectionID} onClick={() => onSelectScan(scannableConnectionID, scan.id)}>{selectedScanId === scan.id ? '已选择' : '查看变化'}</button></td>
</tr>)}
</tbody></table></div>
<div className="source-scan-detail">
<h3>变化记录</h3>
{scanLoading ? <div className="empty-state">加载扫描记录中…</div> : null}
{!scanLoading && !scanDetail ? <div className="empty-state">选择一条扫描查看变化。</div> : null}
{!scanLoading && scanDetail?.changes.length === 0 ? <div className="empty-state">本次扫描未发现新增、更新或不可用变化。</div> : null}
{!scanLoading && scanDetail && scanDetail.changes.length > 0 ? <div className="table-wrap"><table><thead><tr><th>类型</th><th>治理资产</th><th>大小</th><th>记录时间</th></tr></thead><tbody>
{scanDetail.changes.map((change) => <tr key={change.id}>
<td>{sourceScanChangeLabels[change.change_type] ?? change.change_type}</td>
<td><code>{change.source_item_id ?? change.id}</code></td>
<td>{change.observed_size_bytes === null ? '—' : formatBytes(change.observed_size_bytes)}</td>
<td>{formatTime(change.created_at)}</td>
</tr>)}
</tbody></table></div> : null}
</div>
</div> : null}
</details>
</main>
)
}
function sourceHealthClass(status: string) {
if (status === 'healthy') return 'completed'
if (status === 'unhealthy') return 'failed'
if (status === 'degraded') return 'retry'
return 'pending'
}
export function KnowledgeInventory({ page, loading, error, state, onStateChange, onPageChange, onRefresh }: KnowledgeInventoryProps) {
return (
<main className="page-shell">
<header className="hero">
<div>
<p className="eyebrow">P2 · 统一治理清单</p>
<h1>知识资产</h1>
<p className="subtitle">统一展示各类治理来源;清单只读,不会修改或重新上传来源文件。</p>
</div>
<button type="button" onClick={onRefresh} disabled={loading}>{loading ? '刷新中…' : '刷新清单'}</button>
</header>
{error ? <div className="error-banner" role="alert">{error}</div> : null}
<section className="summary-grid asset-summary" aria-label="知识资产概览">
<SummaryCard label="来源对象" value={page.summary.total} tone="blue" />
<SummaryCard label="历史已同步" value={page.summary.completed} tone="green" />
<SummaryCard label="内容别名" value={page.summary.content_alias} tone="cyan" />
<SummaryCard label="超过上限" value={page.summary.over_limit} tone="amber" />
</section>
<section className="panel">
<div className="panel-heading asset-toolbar">
<div><h2>统一来源清单</h2><p>按当前治理版本分页读取,超限项保持阻断。</p></div>
<label>状态
<select value={state} onChange={(event) => onStateChange(event.target.value as LegacyStatus | '')}>
<option value="">全部</option>
<option value="completed">历史已同步</option>
<option value="content_alias">内容别名</option>
<option value="over_limit">超过旧同步上限</option>
</select>
</label>
</div>
{!loading && !error && page.items.length === 0 ? <div className="empty-state">当前筛选没有资产。</div> : null}
{page.items.length > 0 ? (
<div className="table-wrap"><table><thead><tr><th>资产ID</th><th>来源</th><th>大小</th><th>历史状态</th><th>可见性</th><th>测试处理</th><th>更新时间</th></tr></thead><tbody>
{page.items.map((item) => <tr key={item.id}>
<td><code>{item.id}</code></td><td>{sourceTypeLabels[item.source_type] ?? item.source_type}</td><td>{formatBytes(item.size_bytes)}</td>
<td><span className={`status status-${item.legacy_status}`}>{item.legacy_status ? legacyStatusLabels[item.legacy_status] : item.content_state}</span></td>
<td>{item.visibility === 'external' ? '对外' : '对内'}</td><td>{item.has_publication ? item.processing_state : '阻断'}</td><td>{formatTime(item.updated_at)}</td>
</tr>)}
</tbody></table></div>
) : null}
<div className="pagination"><span>第 {Math.floor(page.offset / page.limit) + 1} 页</span><div>
<button type="button" onClick={() => onPageChange(Math.max(0, page.offset - page.limit))} disabled={loading || page.offset === 0}>上一页</button>
<button type="button" onClick={() => onPageChange(page.offset + page.limit)} disabled={loading || page.items.length < page.limit}>下一页</button>
</div></div>
</section>
</main>
)
}
function formatBytes(value: number) {
if (value >= 1024 * 1024 * 1024) return `${(value / (1024 * 1024 * 1024)).toFixed(1)} GiB`
if (value >= 1024 * 1024) return `${(value / (1024 * 1024)).toFixed(1)} MiB`
if (value >= 1024) return `${(value / 1024).toFixed(1)} KiB`
return `${value} B`
}
export function JobDashboard({ jobs, loading, error, onRefresh }: JobDashboardProps) {
const counts = useMemo(
() => ({
total: jobs.length,
running: jobs.filter((job) => job.state === 'running').length,
retry: jobs.filter((job) => job.state === 'retry').length,
failed: jobs.filter((job) => job.state === 'failed').length,
completed: jobs.filter((job) => job.state === 'completed').length,
}),
[jobs],
)
return (
<main className="page-shell">
<header className="hero">
<div>
<p className="eyebrow">P1 · 任务编排基础</p>
<h1>同步任务</h1>
<p className="subtitle">查看持久队列、执行状态、重试次数和最近错误。</p>
</div>
<button type="button" onClick={onRefresh} disabled={loading}>
{loading ? '刷新中…' : '刷新任务'}
</button>
</header>
<section className="summary-grid" aria-label="任务概览">
<SummaryCard label="任务总数" value={counts.total} tone="blue" />
<SummaryCard label="运行中" value={counts.running} tone="cyan" />
<SummaryCard label="待重试" value={counts.retry} tone="amber" />
<SummaryCard label="失败" value={counts.failed} tone="red" />
<SummaryCard label="已完成" value={counts.completed} tone="green" />
</section>
<section className="panel">
<div className="panel-heading">
<div>
<h2>最近任务</h2>
<p>按创建时间倒序显示最近50条任务</p>
</div>
<span className="safe-badge">Release Worker 默认关闭</span>
</div>
{error ? <div className="error-banner" role="alert">{error}</div> : null}
{!loading && !error && jobs.length === 0 ? (
<div className="empty-state">暂无任务。P1可通过API创建demo任务验证队列。</div>
) : null}
{jobs.length > 0 ? (
<div className="table-wrap">
<table>
<thead>
<tr>
<th>任务ID</th>
<th>类型</th>
<th>状态</th>
<th>尝试</th>
<th>更新时间</th>
<th>错误</th>
</tr>
</thead>
<tbody>
{jobs.map((job) => (
<tr key={job.id}>
<td><code>{job.id}</code></td>
<td>{job.type}</td>
<td><span className={`status status-${job.state}`}>{stateLabels[job.state]}</span></td>
<td>{job.attempt}/{job.max_attempts}</td>
<td>{formatTime(job.updated_at)}</td>
<td className="error-cell">{job.last_error || '—'}</td>
</tr>
))}
</tbody>
</table>
</div>
) : null}
</section>
</main>
)
}
const processingLabels: Record<ProcessingState, string> = {
planned: '待入库',
pending: '待处理',
processing: '解析中',
finalizing: '定稿中',
completed: '已完成',
failed: '失败',
stalled: '停滞',
}
interface TestPublicationsProps {
page: TestPublicationPage
loading: boolean
error: string | null
state: ProcessingState | ''
retryingId: string | null
onStateChange: (state: ProcessingState | '') => void
onPageChange: (offset: number) => void
onRefresh: () => void
onRetry: (id: string) => void
}
interface ReleaseManagementProps {
reviewPage: ReviewCandidatePage
reviewLoading: boolean
reviewError: string | null
reviewingId: string | null
batchPage: ReleaseBatchPage
batchDetail: ReleaseBatchDetail | null
batchLoading: boolean
batchError: string | null
mutatingBatchId: string | null
onReview: (publicationID: string, decision: 'approved' | 'rejected', visibility: Visibility, decisionCode: string) => void
onReviewRefresh: () => void
onCreateBatch: (name: string, publicationIDs: string[], deletePublicationIDs: string[]) => void
onSealBatch: (batchID: string) => void
onSelectBatch: (batchID: string) => void
onBatchRefresh: () => void
releaseCapabilities: ReleaseCapabilities
releasePlan: ReleasePlan
releaseChangeSet?: ReleaseChangeSetDetail | null
changeSetBusy?: boolean
changeSetError?: string | null
onGenerateChangeSet?: (name: string) => void
onConfirmChangeSet?: (changeSetID: string) => void
selectedDeleteIDs: string[]
onToggleDelete: (publicationID: string) => void
executionPage: ReleaseExecutionPage
executionDetail: ReleaseExecutionDetail | null
executionChain?: ReleaseAuditChain | null
executionLoading: boolean
executionError: string | null
onSelectExecution: (executionID: string) => void
onExecutionRefresh: () => void
}
const acceptanceLabels: Record<string, string> = {
pending: '待验收',
passed: '通过',
failed: '失败',
manual_required: '需人工确认',
}
const reviewLabels: Record<string, string> = {
pending: '待审核',
approved: '已批准',
rejected: '已驳回',
}
const batchLabels: Record<string, string> = {
draft: '草稿',
sealed: '清单已锁定',
cancelled: '已取消',
}
const executionLabels: Record<string, string> = {
pending: '待执行',
running: '执行中',
completed: '已完成',
failed: '失败',
rolling_back: '正在回滚',
rolled_back: '已回滚',
rollback_failed: '回滚失败',
}
const snapshotLabel = (createdAt: string) => {
const value = new Date(createdAt)
if (Number.isNaN(value.getTime())) return 'Snapshot #已记录'
return `Snapshot #${value.toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 15)}Z`
}
const executionStateDetail = (execution: ReleaseExecutionPage['items'][number], executions: ReleaseExecutionPage['items']) => {
const automaticRollback = execution.operation === 'rollback' && execution.authorized_by === 'system:auto-rollback'
const snapshotSource = automaticRollback ? executions.find((candidate) => candidate.id === execution.prior_execution_id) : execution
const snapshot = snapshotLabel(snapshotSource?.created_at ?? execution.created_at)
if (automaticRollback && (execution.state === 'rolled_back' || execution.state === 'completed')) return `已恢复 ${snapshot}`
if (automaticRollback && (execution.state === 'pending' || execution.state === 'running' || execution.state === 'rolling_back')) return `正在执行自动回滚 · ${snapshot}`
if (automaticRollback && (execution.state === 'failed' || execution.state === 'rollback_failed')) return `自动回滚失败 · ${snapshot}(发布已升级为整体恢复,需快照还原授权)`
if (execution.operation === 'publish' && execution.state === 'pending') return '等待创建生产快照'
if (execution.operation === 'publish' && (execution.state === 'running' || execution.state === 'rolling_back')) return `正在同步 ${execution.completed_item_count} / ${execution.item_count}`
if (execution.operation === 'publish' && execution.failure_level === 'batch') return '本批后续已停止,正在补偿本批已发布项'
if (execution.operation === 'publish' && execution.failure_level === 'single_item') return '单项失败,后续项未推进'
if (execution.operation === 'publish' && execution.failure_level === 'overall') return '需整体快照恢复(等待授权)'
return ''
}
const releaseItemLabels: Record<string, string> = {
pending: '等待开始',
staged: '内容已准备',
activated: '已切换,等待验证',
verified: '发布并验证通过',
failed: '发布失败',
rolled_back: '已恢复上一版本',
}
const releaseItemResult = (item: ReleaseExecutionDetail['items'][number]) => {
if (item.action === 'delete' && item.state === 'verified' && item.production_revision === 'absent') return { detail: '删除并验证通过', outcome: '已从生产检索中移除' }
if (item.action === 'delete' && item.state === 'rolled_back') return { detail: '删除操作已回滚', outcome: '已恢复生产知识' }
return { detail: releaseItemLabels[item.state] ?? item.state, outcome: item.state === 'verified' ? '生产可用' : item.state === 'rolled_back' ? '已恢复' : '处理中' }
}
export const reviewGateLabel = (item: Pick<ReviewCandidatePage['items'][number], 'review_state' | 'gate_status'>) => item.review_state === 'approved' && item.gate_status === 'ready' ? '测试已通过' : item.gate_status === 'ready' ? '可以审核' : '暂时不能审核'
function releaseFailureMessage(code: string) {
if (!code) return ''
const labels: Record<string, string> = {
release_contract_mismatch: '目标环境与测试环境不一致,已停止发布',
release_verification_failed: '发布后的检索验证未通过',
release_item_failed: '部分知识发布失败',
release_retryable: '遇到临时故障,系统将自动重试',
release_manifest_mismatch: '发布结果与冻结的发布清单不一致,已降级为失败',
release_rollback_failed: '自动回滚失败,需整体快照恢复(等待授权)',
}
return labels[code] ?? '执行失败,请联系管理员查看技术记录'
}
const releaseFlowSteps = [
{ title: '1. 查看来源变化', kind: '只读查看' },
{ title: '2. 确认测试结果', kind: '只读查看' },
{ title: '3. 审核发布内容', kind: '普通业务操作' },
{ title: '4. 创建发布批次', kind: '普通业务操作' },
{ title: '5. 锁定发布清单', kind: '普通业务操作' },
{ title: '6. 生产负责人确认', kind: '生产危险操作' },
{ title: '7. 发布并验证', kind: '生产危险操作' },
{ title: '8. 必要时回滚', kind: '生产危险操作' },
] as const
function releaseGuidance(props: ReleaseManagementProps, pending: number) {
const approved = props.reviewPage.items.filter((item) => item.review_state === 'approved' && item.gate_status === 'ready').length
const drafts = props.batchPage.items.filter((batch) => batch.state === 'draft').length
const sealed = props.batchPage.items.filter((batch) => batch.state === 'sealed').length
const activeExecutions = props.executionPage.items.filter((execution) => execution.state === 'pending' || execution.state === 'running').length
const completedExecutions = props.executionPage.items.filter((execution) => execution.state === 'completed').length
if (pending > 0) return {
step: 3,
title: `现在要做:审核 ${pending} 项知识`,
reason: `还有 ${pending} 项等待审核;已批准文件可先创建批次`,
action: '逐条选择“批准”或“驳回”(操作自动记在当前登录人名下)',
after: '第 4 步,创建发布批次',
impact: '普通业务操作,不会影响生产',
href: '#review-actions',
button: '前往审核列表',
}
if (drafts > 0) return {
step: 5,
title: `现在要做:锁定 ${drafts} 个草稿批次`,
reason: '暂时不能继续:草稿内容还可以变化,发布清单尚未锁定',
action: '核对批次内容,然后点击“锁定清单(不会上线)”',
after: '第 6 步,等待生产负责人确认',
impact: '普通业务操作,不会影响生产',
href: '#batch-actions',
button: '查看草稿批次',
}
if (approved > 0 && props.batchPage.total === 0) return {
step: 4,
title: `现在要做:把 ${approved} 项已批准知识加入批次`,
reason: '暂时不能继续:已批准内容还没有组成一次发布清单',
action: '勾选已批准内容,填写批次名称并创建草稿',
after: '第 5 步,锁定本次发布清单',
impact: '普通业务操作,不会影响生产',
href: '#review-actions',
button: '创建发布批次',
}
if (sealed > 0 && props.executionPage.total === 0) return {
step: 6,
title: `等待生产负责人确认 ${sealed} 个已锁定批次`,
reason: !props.releaseCapabilities.production_release_requests_enabled
? '暂时不能继续:生产发布功能处于安全锁定状态'
: !props.releaseCapabilities.production_backup_restore_verified
? '暂时不能继续:生产快照恢复验证尚未通过'
: '暂时不能继续:生产负责人还没有确认本次上线',
action: '普通用户无需操作;生产负责人核对影响范围后单独确认',
after: '第 7 步,系统发布并验证',
impact: '生产危险操作,当前页面不能执行',
href: '#production-status',
button: '查看安全状态',
}
if (activeExecutions > 0) return {
step: 7,
title: `正在发布并验证 ${activeExecutions} 个批次`,
reason: '暂时不能继续:系统仍在复制并核对生产知识',
action: '等待系统完成;如果失败,请查看人类可读的失败原因',
after: '第 8 步,仅在发现问题时申请回滚',
impact: '生产危险操作,只读查看进度',
href: '#production-status',
button: '查看发布进度',
}
if (completedExecutions > 0) return {
step: 8,
title: '发布已经完成并验证',
reason: '当前没有必须处理的阻断',
action: '正常情况下无需操作;确认发布错误时再申请回滚',
after: '流程完成',
impact: '回滚是生产危险操作,必须由生产负责人再次确认',
href: '#production-status',
button: '查看发布结果',
}
return {
step: 2,
title: '现在要做:确认测试结果',
reason: '暂时不能继续:目前没有可以审核的已通过知识',
action: '前往“解析监控”查看处理结果,并核对搜索效果',
after: '第 3 步,审核发布内容',
impact: '只读查看,不会影响生产',
href: '#review-actions',
button: '查看当前结果',
}
}
export function ReleaseManagement(props: ReleaseManagementProps) {
/* R3 pagination probe */
const changeSet = props.releaseChangeSet ?? null
const changeSetBusy = props.changeSetBusy ?? false
const changeSetError = props.changeSetError ?? null
const onGenerateChangeSet = props.onGenerateChangeSet ?? (() => undefined)
const onConfirmChangeSet = props.onConfirmChangeSet ?? (() => undefined)
const [batchName, setBatchName] = useState('')
const [selectedIDs, setSelectedIDs] = useState<string[]>([])
const [deleteConfirmed, setDeleteConfirmed] = useState(false)
const [visibilityByID, setVisibilityByID] = useState<Record<string, Visibility>>({})
const [planActionFilter, setPlanActionFilter] = useState<'' | 'add' | 'update' | 'delete' | 'blocked'>('')
const [planScopeFilter, setPlanScopeFilter] = useState<'' | Visibility>('')
const [planOnlyReleasable, setPlanOnlyReleasable] = useState(false)
const [planPage, setPlanPage] = useState(0)
const planPageSize = 25
const ready = props.reviewPage.items.filter((item) => item.gate_status === 'ready').length
const pending = props.reviewPage.items.filter((item) => item.review_state === 'pending').length
const selectedCount = selectedIDs.length + props.selectedDeleteIDs.length
const confirmedSelection = selectedIDs.length > 0 || (props.selectedDeleteIDs.length > 0 && deleteConfirmed)
const guidance = releaseGuidance(props, pending)
const productionStatus = !props.releaseCapabilities.production_release_requests_enabled
? '生产操作权限:已关闭'
: !props.releaseCapabilities.production_backup_restore_verified
? '生产操作权限:已阻断'
: '生产操作权限:等待负责人确认'
const batchBlocker = [
selectedCount === 0 ? '请先勾选已批准或待删除的知识' : '',
props.selectedDeleteIDs.length > 0 && !deleteConfirmed ? '请确认所选删除项会停止生产检索' : '',
selectedCount > 0 && !confirmedSelection ? '至少 1 项动作通过确认' : '',
!batchName.trim() ? '请填写批次名称' : '',
].filter(Boolean).join(';')
const toggleSelected = (publicationID: string) => {
setSelectedIDs((current) => current.includes(publicationID) ? current.filter((id) => id !== publicationID) : [...current, publicationID])
}
return <main className="page-shell release-page">
<header className="hero compact">
<div>
<h1>发布管理</h1>
<p className="subtitle">测试知识库与生产知识库的同步。生产发布仍由独立门禁、备份和负责人确认保护。</p>
</div>
<div className="release-actions"><button type="button" onClick={() => { props.onReviewRefresh(); props.onBatchRefresh(); props.onExecutionRefresh() }} disabled={props.reviewLoading || props.batchLoading || props.executionLoading}>刷新当前页面</button></div>
</header>
<nav className="module-tabs" aria-label="发布管理分区"><a className="active" href="#release-plan">发布计划</a><a href="#batch-actions">发布清单</a><a href="#release-execution">执行进度与历史</a></nav>
<section className="release-snapshot-callout"><span aria-hidden="true">ⓘ</span><div><strong>{props.releaseCapabilities.production_backup_restore_verified ? '发布前将创建可恢复快照' : '生产发布当前不可执行'}</strong><small>{props.releaseCapabilities.production_backup_restore_verified ? '发布失败时系统会按已验证的快照执行回滚。' : '尚未通过生产备份恢复验证,当前只能审核和锁定发布清单。'}</small></div></section>
<details className="release-help"><summary>查看审核与发布说明</summary>
<section className="release-journey" aria-label="发布流程">
<div className="journey-heading"><div><span>操作顺序</span><h2>从检查到发布,只走这 8 步</h2></div><p>蓝色是当前步骤;绿色表示已完成;红色步骤会修改生产环境。</p></div>
<ol className="journey-steps">
{releaseFlowSteps.map((item, index) => {
const number = index + 1
const state = number < guidance.step ? 'done' : number === guidance.step ? 'current' : 'upcoming'
const danger = number >= 6
return <li key={item.title} className={`journey-step ${state}${danger ? ' danger' : ''}`} aria-current={state === 'current' ? 'step' : undefined}>
<span className="step-number">{number < guidance.step ? '✓' : number}</span>
<strong>{item.title}</strong>
<small>{item.kind}</small>
</li>
})}
</ol>
</section>
<section className="current-guidance" aria-label="当前阶段">
<div className="guidance-step">当前在第 {guidance.step} 步,共 8 步</div>
<div className="guidance-copy">
<h2>{guidance.title}</h2>
<strong>{guidance.reason}</strong>
{guidance.step === 3 ? <div className="current-checklist"><b>完成本步的 3 件事</b><ol><li>只审核本次准备发布的文件</li><li>勾选要发布的已批准知识</li><li>填写批次名称并创建草稿</li></ol></div> : null}
<p>{`现在先做:${guidance.action}`}</p>
<p>{`完成后进入:${guidance.after}`}</p>
<span>{guidance.impact}</span>
</div>
<a className="primary-link" href={guidance.href}>{guidance.step === 3 ? '滚动到审核列表' : guidance.button}</a>
</section>
</details>
<section className="safety-strip" id="production-status">
<div><strong>{productionStatus}</strong><span>{props.releaseCapabilities.production_release_requests_enabled && !props.releaseCapabilities.production_backup_restore_verified ? '生产发布已阻断:先完成生产快照并通过恢复验证。' : '锁定清单只表示内容不再变化,不会自动上线;普通业务操作不会改动生产知识。'}</span></div>
<span className="safe-badge">修改生产内容:关闭</span>
<details className="technical-status"><summary>查看技术状态</summary><p>生产请求门禁{props.releaseCapabilities.production_release_requests_enabled ? '已开启' : '关闭'};快照恢复验证{props.releaseCapabilities.production_backup_restore_verified ? '已通过' : '未通过'};Release Worker保持关闭。</p></details>
</section>
<section className="panel release-plan-panel" id="release-plan">
<div className="panel-heading"><div><h2>自动发布计划</h2><p>来源与目录 → 测试知识库 → 生产知识库。来源标注是最终 Truth Source。</p></div><span className="safe-badge">按知识级别同步</span></div>
<div className="release-plan-summary"><span>{`新增 ${props.releasePlan.summary.add}`}</span><span>{`更新 ${props.releasePlan.summary.update}`}</span><span>{`删除 ${props.releasePlan.summary.delete}`}</span><span>{`阻断 ${props.releasePlan.summary.blocked}`}</span><span>{`未变化 ${props.releasePlan.summary.unchanged}`}</span></div>
{(() => {
const filtered = props.releasePlan.items.filter((item) => {
if (planActionFilter === 'blocked' ? item.can_release : planActionFilter ? item.action !== planActionFilter : false) return false
if (planScopeFilter && item.target_scope !== planScopeFilter) return false
if (planOnlyReleasable && !item.can_release) return false
return true
})
const pageCount = Math.max(1, Math.ceil(filtered.length / planPageSize))
const safePage = Math.min(planPage, pageCount - 1)
const pageItems = filtered.slice(safePage * planPageSize, safePage * planPageSize + planPageSize)
const actionLabel = (item: ReleasePlanItem) => item.action === 'add' ? '新增' : item.action === 'update' ? '更新' : item.action === 'delete' ? '删除' : '等待测试'
return <>
<div className="release-plan-filters" role="search">
<label>动作<select value={planActionFilter} onChange={(event) => { setPlanActionFilter(event.target.value as typeof planActionFilter); setPlanPage(0) }}><option value="">全部</option><option value="add">新增</option><option value="update">更新</option><option value="delete">删除</option><option value="blocked">仅阻断</option></select></label>
<label>目标<select value={planScopeFilter} onChange={(event) => { setPlanScopeFilter(event.target.value as typeof planScopeFilter); setPlanPage(0) }}><option value="">全部</option><option value="internal">对内</option><option value="external">对外</option></select></label>
<label className="filter-check"><input type="checkbox" checked={planOnlyReleasable} onChange={(event) => { setPlanOnlyReleasable(event.target.checked); setPlanPage(0) }} />仅可发布</label>
<span className="filter-count">{`筛选 ${filtered.length} / 全部 ${props.releasePlan.items.length}`}</span>
</div>
{pageItems.length ? <div className="table-wrap"><table className="release-plan-table"><thead><tr><th>选择</th><th>知识</th><th>目标</th><th>计划动作</th><th>测试状态</th><th>生产状态</th><th>能否发布</th></tr></thead><tbody>{pageItems.map((item, index) => <tr key={`${item.publication_id}-${item.title}-${item.target_scope}-${index}`} className={item.action === 'delete' && item.can_release ? 'plan-delete' : item.can_release ? '' : 'plan-blocked'}><td>{item.action === 'delete' && item.can_release ? <input type="checkbox" aria-label={`选择删除${item.title}`} checked={props.selectedDeleteIDs.includes(item.publication_id)} onChange={() => { props.onToggleDelete(item.publication_id); setDeleteConfirmed(false) }} /> : '—'}</td><td><strong>{item.title}</strong></td><td>{item.target_scope === 'internal' ? '对内知识库' : '对外知识库'}</td><td>{actionLabel(item)}</td><td>{item.test_state === 'ready' ? '已通过' : item.test_state === 'not_required' ? '无需测试' : '未就绪'}</td><td>{item.production_state === 'present' ? '已存在' : '不存在'}</td><td>{item.can_release ? item.action === 'delete' ? '将从生产检索中移除' : '可加入发布批次' : item.blocker === 'source_unavailable' ? '来源当前不可用,保留生产知识' : '测试未就绪,当前阻断'}</td></tr>)}</tbody></table></div> : filtered.length ? <div className="empty-state">当前筛选没有发布变更。</div> : <div className="empty-state">来源、测试与生产状态一致,当前没有发布变更。</div>}
{pageCount > 1 ? <div className="release-plan-pager"><button type="button" className="secondary-action" disabled={safePage === 0} onClick={() => setPlanPage(safePage - 1)}>上一页</button><span>{`第 ${safePage + 1} / ${pageCount} 页 · 每页 ${planPageSize} 条`}</span><button type="button" className="secondary-action" disabled={safePage >= pageCount - 1} onClick={() => setPlanPage(safePage + 1)}>下一页</button></div> : null}
</>
})()}
{(() => {
const manifestShort = changeSet ? `${changeSet.manifest_sha256.slice(0, 8)}…${changeSet.manifest_sha256.slice(-6)}` : ''
const frozenActionLabel = (action: string) => action === 'add' ? '新增' : action === 'update' ? '更新' : action === 'delete' ? '删除' : action === 'blocked' ? '阻断' : '不变'
return <div className="release-changeset-panel">
<div className="release-changeset-heading"><div><h3>冻结发布计划集(R1)</h3><p>生成即固化:来源刷新不会改变已确认清单;正式批次只能引用已确认版本。</p></div>
{changeSet ? <span className={`status status-${changeSet.state === 'confirmed' ? 'completed' : 'pending'}`}>v{changeSet.number} · {changeSet.state === 'confirmed' ? '已确认' : changeSet.state === 'consumed' ? '已消费' : changeSet.state === 'cancelled' ? '已取消' : '待确认'}</span> : <span className="status status-pending">尚未生成</span>}
</div>
{changeSet ? <div className="release-changeset-meta">
<span>{`清单 ${changeSet.items.length} 项(新增${changeSet.add_count}·更新${changeSet.update_count}·删除${changeSet.delete_count}·阻断${changeSet.blocked_count})`}</span>
<span title={changeSet.manifest_sha256}>{`摘要 ${manifestShort}`}</span>
<span>{`绑定快照 ${changeSet.source_snapshot_ids.length} 个`}</span>
<span>{`生成人 ${changeSet.created_by} · ${new Date(changeSet.created_at).toLocaleString('zh-CN', { hour12: false })}`}</span>
{changeSet.confirmed_by ? <span>{`确认人 ${changeSet.confirmed_by} · ${changeSet.confirmed_at ? new Date(changeSet.confirmed_at).toLocaleString('zh-CN', { hour12: false }) : ''}`}</span> : null}
</div> : null}
{changeSet && changeSet.state === 'planned' ? <details className="release-changeset-items"><summary>查看冻结清单({changeSet.items.length}项)</summary><ul>{changeSet.items.map((item) => <li key={item.seq}>{`${item.seq}. ${item.title} · ${item.target_scope === 'internal' ? '对内' : '对外'} · ${frozenActionLabel(item.action)}${item.can_release ? '' : '(阻断:' + (item.blocker === 'source_unavailable' ? '来源不可用' : '测试未就绪') + ')'}`}</li>)}</ul></details> : null}
{changeSetError ? <p className="form-error">{changeSetError}</p> : null}
<div className="release-changeset-actions">
<button type="button" className="secondary-action" disabled={changeSetBusy} title="把当前实时发布计划固化为新版本(相同计划自动去重)" onClick={() => onGenerateChangeSet(batchName.trim() || `发布计划 ${new Date().toLocaleDateString('zh-CN')}`)}>生成新版本</button>
{changeSet && changeSet.state === 'planned' ? <button type="button" disabled={changeSetBusy} onClick={() => onConfirmChangeSet(changeSet.id)}>确认冻结(此后不可更改)</button> : null}
{changeSet && changeSet.state === 'confirmed' ? <small className="safe-badge">创建批次将自动绑定 v{changeSet.number} 并校验清单</small> : <small>草稿批次需先由上方“确认冻结”固定目标</small>}
</div>
</div>
})()}
{props.selectedDeleteIDs.length > 0 ? <label className="delete-confirmation"><input type="checkbox" aria-label="确认删除生产知识" checked={deleteConfirmed} onChange={(event) => setDeleteConfirmed(event.target.checked)} /><span><strong>我确认所选删除项会停止生产检索</strong><small>发布前会创建可恢复快照;失败会自动回滚。</small></span></label> : null}
</section>
<section className="summary-grid" aria-label="审核概览">
<SummaryCard label="审核候选" value={props.reviewPage.total} tone="blue" />
<SummaryCard label="测试可用" value={ready} tone="green" />
<SummaryCard label="待审核" value={pending} tone="amber" />
<SummaryCard label={props.selectedDeleteIDs.length > 0 && !deleteConfirmed ? `已选择删除:${props.selectedDeleteIDs.length}(待确认)` : '已选入批次'} value={selectedCount} tone="cyan" />
</section>
<section className="panel review-panel" id="review-actions">
<div className="panel-heading release-toolbar">
<div><h2>第 3 步:审核要发布的知识</h2><p>先确认测试结果和对内/对外范围,再批准或驳回。批准后才能勾选加入批次。</p></div>
</div>
{batchBlocker ? <div className="button-reason" role="note"><strong>{`为什么按钮不能点:${batchBlocker}`}</strong></div> : null}
<div className="review-decision-guide" aria-label="审核判断标准">
<h3>如何决定批准或驳回</h3>
<p className="approve-guide">可以批准:基础测试通过,你已确认搜索结果相关,而且发布范围正确</p>
<p className="reject-guide">应该驳回:内容错误、过期、敏感、搜索结果不相关,或者你无法确认</p>
</div>
{props.reviewError ? <div className="error-banner" role="alert">{props.reviewError}</div> : null}
{!props.reviewLoading && !props.reviewError && props.reviewPage.items.length === 0 ? <div className="empty-state">当前没有带最新验收结果的审核候选。</div> : null}
{props.reviewPage.items.length > 0 ? <div className="table-wrap"><table className="review-table"><thead><tr><th>选择</th><th>知识内容</th><th>测试结果</th><th>能否继续</th><th>发布范围</th><th>审核状态</th><th>操作</th></tr></thead><tbody>
{props.reviewPage.items.map((item) => {
const visibility = visibilityByID[item.publication_id] ?? (item.decided_visibility || item.current_visibility)
const selectable = item.review_state === 'approved' && item.gate_status === 'ready'
return <tr key={item.publication_id}>
<td><input type="checkbox" aria-label={`选择${item.title}`} checked={selectedIDs.includes(item.publication_id)} disabled={!selectable} onChange={() => toggleSelected(item.publication_id)} /></td>
<td><strong>{item.title}</strong><span>{sourceTypeLabels[item.source_type] ?? item.source_type}</span></td>
<td className="acceptance-summary">
<strong>{item.knowledge_exists === 'passed' && item.chunks_present === 'passed' ? '基础测试通过' : '基础测试未通过'}</strong>
<span>{item.retrieval_hit === 'manual_required' ? '搜索效果需人工确认' : `搜索测试${acceptanceLabels[item.retrieval_hit]}`}</span>
<details><summary>查看测试详情</summary><small>知识读取:{acceptanceLabels[item.knowledge_exists]};内容处理:{acceptanceLabels[item.chunks_present]};搜索验证:{acceptanceLabels[item.retrieval_hit]}</small></details>
</td>
<td><span className={`status status-${item.gate_status === 'ready' ? 'completed' : 'failed'}`}>{reviewGateLabel(item)}</span></td>
<td><select value={visibility} onChange={(event) => setVisibilityByID((current) => ({ ...current, [item.publication_id]: event.target.value as Visibility }))}><option value="internal">仅内部员工</option><option value="external">允许外部用户</option></select></td>
<td><span className={`status status-${item.review_state === 'approved' ? 'completed' : item.review_state === 'rejected' ? 'failed' : 'pending'}`}>{reviewLabels[item.review_state]}</span>{item.reviewer_ref ? <small>{item.reviewer_ref}</small> : null}</td>
<td><div className="row-actions"><button type="button" disabled={item.gate_status !== 'ready' || props.reviewingId === item.publication_id} onClick={() => props.onReview(item.publication_id, 'approved', visibility, 'approved_for_release')}>批准</button><button type="button" className="secondary-action" disabled={props.reviewingId === item.publication_id} onClick={() => props.onReview(item.publication_id, 'rejected', visibility, 'needs_correction')}>驳回</button></div></td>
</tr>
})}
</tbody></table></div> : null}
<div className="batch-requirements" aria-label="创建批次条件"><strong>创建批次还需要</strong><span className={props.selectedDeleteIDs.length === 0 || deleteConfirmed ? 'met' : 'unmet'}>确认所选发布动作</span><span className={confirmedSelection ? 'met' : 'unmet'}>至少 1 项动作通过确认</span><span className={batchName.trim() ? 'met' : 'unmet'}>填写批次名称</span></div>
<div className="batch-create-bar"><label>批次名称<input value={batchName} onChange={(event) => setBatchName(event.target.value)} placeholder="例如:9月第一批知识" /></label><span>已选 {selectedCount} 项{props.selectedDeleteIDs.length > 0 && !deleteConfirmed ? '(删除待确认)' : ''}</span><button type="button" title={batchBlocker || '创建后仍可检查和调整'} disabled={Boolean(batchBlocker) || props.batchLoading} onClick={() => props.onCreateBatch(batchName, selectedIDs, props.selectedDeleteIDs)}>创建草稿批次</button></div>
</section>
<section className="panel batch-panel" id="batch-actions">
<div className="panel-heading"><div><h2>第 4–5 步:创建并锁定发布清单</h2><p>草稿可以继续核对;点击“锁定清单(不会上线)”后,本次内容不再变化,但仍不会发布到生产。</p></div><span className="safe-badge">锁定清单 ≠ 上线</span></div>
{props.batchError ? <div className="error-banner" role="alert">{props.batchError}</div> : null}
{!props.batchLoading && !props.batchError && props.batchPage.items.length === 0 ? <div className="empty-state">尚无草稿或已锁定的发布清单。</div> : null}
{props.batchPage.items.length > 0 ? <div className="batch-grid"><div className="table-wrap"><table><thead><tr><th>批次名称</th><th>状态</th><th>知识数量</th><th>内容状态</th><th>操作</th></tr></thead><tbody>
{props.batchPage.items.map((batch) => <tr key={batch.id}><td><strong>{batch.name}</strong></td><td><span className={`status status-${batch.state === 'sealed' ? 'completed' : 'pending'}`}>{batchLabels[batch.state]}</span></td><td>{batch.item_count}</td><td>{batch.state === 'sealed' ? '内容已锁定' : '仍可检查调整'}</td><td><div className="row-actions"><button type="button" className="secondary-action" onClick={() => props.onSelectBatch(batch.id)}>查看内容</button>{batch.state === 'draft' ? <button type="button" disabled={props.mutatingBatchId === batch.id} onClick={() => props.onSealBatch(batch.id)}>锁定清单(不会上线)</button> : null}</div></td></tr>)}
</tbody></table></div><div className="batch-detail"><h3>本批次包含</h3>{props.batchDetail ? <>{props.batchDetail.items.map((item) => <div className="batch-detail-row" key={item.publication_id}><span><strong>{item.title}</strong><small>{item.action === 'delete' ? '删除生产知识' : '新增或更新生产知识'}</small></span><b>{item.decided_visibility === 'internal' ? '仅内部员工' : '允许外部用户'}</b></div>)}{props.batchDetail.items.length === 0 ? <div className="empty-state">批次没有知识。</div> : null}</> : <div className="empty-state">点击“查看内容”核对本次发布清单。</div>}</div></div> : null}
</section>
<section className="panel execution-panel" id="release-execution">
<div className="panel-heading"><div><h2>第 6–8 步:生产确认、发布验证与回滚</h2><p>这里仅供查看生产负责人确认后的发布结果。普通用户不能在本页面发起生产发布或回滚。</p></div><span className="safe-badge">{props.releaseCapabilities.production_release_requests_enabled ? '等待生产负责人确认' : '生产操作已锁定'}</span></div>
{props.executionError ? <div className="error-banner" role="alert">{props.executionError}</div> : null}
{!props.executionLoading && !props.executionError && props.executionPage.items.length === 0 ? <div className="empty-state">尚无生产发布或回滚执行记录。</div> : null}
{props.executionPage.items.length > 0 ? <div className="batch-grid execution-grid"><div className="table-wrap"><table><thead><tr><th>开始时间</th><th>操作</th><th>状态</th><th>批次进度</th><th>完成进度</th><th>授权人</th><th>操作</th></tr></thead><tbody>
{props.executionPage.items.map((execution) => <tr key={execution.id}><td>{formatTime(execution.created_at)}</td><td>{execution.operation === 'publish' ? '发布' : '回滚'}</td><td><span className={`status status-${execution.state}`}>{executionLabels[execution.state]}</span>{executionStateDetail(execution, props.executionPage.items) ? <small>{executionStateDetail(execution, props.executionPage.items)}</small> : null}{execution.error_code ? <small>{releaseFailureMessage(execution.error_code)}</small> : null}</td><td>{execution.total_batches>0?`批次 ${execution.current_batch} / ${execution.total_batches}`:'等待开始'}<small>每批最多 {execution.batch_size} 项</small></td><td>{execution.completed_item_count}/{execution.item_count}{execution.failed_item_count ? <small>失败 {execution.failed_item_count}</small> : null}</td><td>{execution.authorized_by}</td><td><button type="button" className="secondary-action" onClick={() => props.onSelectExecution(execution.id)}>查看结果</button></td></tr>)}
</tbody></table></div><div className="batch-detail execution-detail"><h3>每项知识的结果</h3>{props.executionDetail ? <>{props.executionDetail.items.map((item) => { const result = releaseItemResult(item); return <div className="batch-detail-row execution-detail-row" key={item.publication_id}><span><strong>{item.title}</strong><small>{result.detail}{item.error_code ? ` · ${releaseFailureMessage(item.error_code)}` : ''}</small></span><span><b>{result.outcome}</b></span></div> })}{props.executionDetail.items.length === 0 ? <div className="empty-state">发布尚无逐项结果。</div> : null}</> : <div className="empty-state">点击“查看结果”核对每项知识。</div>}</div></div> : null}
{props.executionChain ? <div className="release-audit-chain">
<h3>发布审计链</h3>
<div className="audit-chain-line"><span>批次</span><b>{props.executionChain.release_batch_name || '未绑定批次'}</b><small>{`创建 ${props.executionChain.created_by || '—'} · 锁定 ${props.executionChain.sealed_by || '—'} · 授权 ${props.executionChain.authorized_by || '—'}`}</small></div>
{props.executionChain.release_change_set_id ? <div className="audit-chain-line"><span>发布计划集</span><b>{props.executionChain.release_change_set_name}</b><small>{`${props.executionChain.release_change_set_state === 'confirmed' ? '已确认' : props.executionChain.release_change_set_state} · 确认人 ${props.executionChain.release_change_set_confirmed_by || '—'} · 摘要 ${props.executionChain.manifest_sha256.slice(0, 8)}…${props.executionChain.manifest_sha256.slice(-6)}`}</small></div> : null}
{props.executionChain.snapshots.length ? <div className="audit-chain-line"><span>来源快照</span><b>{props.executionChain.snapshots.map((snap) => `${snap.source_name}(${snap.file_count})`).join('、')}</b></div> : null}
{props.executionChain.catalog_change_sets.length ? <div className="audit-chain-line"><span>来源变更集</span><b>{props.executionChain.catalog_change_sets.map((set) => `${set.id}·${set.state}`).join('、')}</b></div> : null}
{props.executionChain.rollback_execution_id ? <div className="audit-chain-line"><span>补偿回滚</span><b>已关联回滚执行</b></div> : null}
{props.executionChain.prior_execution_id ? <div className="audit-chain-line"><span>上游发布</span><b>由发布执行补偿而来</b></div> : null}
</div> : null}
</section>
</main>
}
function TestPublications({ page, loading, error, state, retryingId, onStateChange, onPageChange, onRefresh, onRetry }: TestPublicationsProps) {
const [view, setView] = useState<'overview' | 'internal' | 'external' | 'failed'>('overview')
const visibleItems = page.items.filter((item) => view === 'internal' ? item.target_scope === 'internal' : view === 'external' ? item.target_scope === 'external' : view === 'failed' ? item.processing_state === 'failed' || item.processing_state === 'stalled' : true)
const internalCount = page.items.filter((item) => item.target_scope === 'internal').length
const externalCount = page.items.filter((item) => item.target_scope === 'external').length
const processingCount = page.items.filter((item) => item.processing_state === 'processing' || item.processing_state === 'finalizing').length
const problemCount = page.items.filter((item) => item.processing_state === 'failed' || item.processing_state === 'stalled').length
return (
<main className="page-shell parsing-monitor-page">
<header className="hero compact">
<div>
<h1>解析监控</h1>
<p className="subtitle">查看测试知识库中每份资料的上传、解析和验收状态。</p>
</div>
<button type="button" onClick={onRefresh} disabled={loading}>{loading ? '刷新中…' : '刷新状态'}</button>
</header>
<nav className="module-tabs" aria-label="解析监控分区"><button type="button" className={view === 'overview' ? 'active' : ''} onClick={() => setView('overview')}>总体概览</button><button type="button" className={view === 'internal' ? 'active' : ''} onClick={() => setView('internal')}>对内知识库</button><button type="button" className={view === 'external' ? 'active' : ''} onClick={() => setView('external')}>对外知识库</button><button type="button" className={view === 'failed' ? 'active' : ''} onClick={() => setView('failed')}>失败列表</button></nav>
{error ? <div className="error-banner" role="alert">{error}</div> : null}
<section className="summary-grid monitor-summary-grid" aria-label="当前页解析概览"><SummaryCard label="对内资料" value={internalCount} tone="green" /><SummaryCard label="对外资料" value={externalCount} tone="blue" /><SummaryCard label="解析中" value={processingCount} tone="cyan" /><SummaryCard label="失败或停滞" value={problemCount} tone="red" /></section>
<section className="panel parsing-monitor-panel">
<div className="panel-heading asset-toolbar">
<div><h2>{view === 'failed' ? '失败与停滞文件' : '解析队列'}</h2><p>当前筛选共 {visibleItems.length} 条;仅返回治理安全投影,不含来源地址或凭据。</p></div>
<label>状态
<select value={state} onChange={(event) => onStateChange(event.target.value as ProcessingState | '')}>
<option value="">全部</option>
<option value="pending">待处理</option>
<option value="processing">解析中</option>
<option value="finalizing">定稿中</option>
<option value="completed">已完成</option>
<option value="failed">失败</option>
<option value="stalled">停滞</option>
</select>
</label>
</div>
{!loading && !error && visibleItems.length === 0 ? <div className="empty-state">当前筛选没有测试发布记录。</div> : null}
{visibleItems.length > 0 ? (
<div className="table-wrap"><table><thead><tr><th>发布</th><th>标题</th><th>处理状态</th><th>重试次数</th><th>错误码</th><th>更新时间</th><th>操作</th></tr></thead><tbody>
{visibleItems.map((item) => (
<tr key={item.id}>
<td><code>{item.id}</code></td>
<td>{item.title}</td>
<td><span className={`status status-${item.processing_state}`}>{processingLabels[item.processing_state]}</span></td>
<td>{item.retry_count}</td>
<td className="error-cell">{item.last_error || '—'}</td>
<td>{formatTime(item.updated_at)}</td>
<td>{item.can_retry ? <button type="button" onClick={() => onRetry(item.id)} disabled={retryingId === item.id}>{retryingId === item.id ? '重试中…' : '重试'}</button> : '—'}</td>
</tr>
))}
</tbody></table></div>
) : null}
<div className="pagination"><span>第 {Math.floor(page.offset / page.limit) + 1} 页</span><div>
<button type="button" onClick={() => onPageChange(Math.max(0, page.offset - page.limit))} disabled={loading || page.offset === 0}>上一页</button>
<button type="button" onClick={() => onPageChange(page.offset + page.limit)} disabled={loading || page.items.length < page.limit}>下一页</button>
</div></div>
</section>
</main>
)
}
function SummaryCard({ label, value, tone }: { label: string; value: number; tone: string }) {
return (
<article className={`summary-card tone-${tone}`}>
<span>{label}</span>
<strong>{value}</strong>
</article>
)
}
function formatTime(value: string) {
if (!value) return '—'
const date = new Date(value)
return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN', { hour12: false })
}
export default function App() {
const [jobs, setJobs] = useState<Job[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [connectionPage, setConnectionPage] = useState<SourceConnectionPage>(emptyConnectionPage)
const [connectionLoading, setConnectionLoading] = useState(true)
const [connectionError, setConnectionError] = useState<string | null>(null)
const [scanningConnectionId, setScanningConnectionId] = useState<string | null>(null)
const [scanPage, setScanPage] = useState<SourceScanPage>(emptyScanPage)
const [scanDetail, setScanDetail] = useState<SourceScanDetail | null>(null)
const [scanLoading, setScanLoading] = useState(false)
const [scanError, setScanError] = useState<string | null>(null)
const [selectedScanId, setSelectedScanId] = useState<string | null>(null)
const [assetPage, setAssetPage] = useState<SourceAssetPage>(emptyAssetPage)
const [assetLoading, setAssetLoading] = useState(true)
const [assetError, setAssetError] = useState<string | null>(null)
const [assetState, setAssetState] = useState<LegacyStatus | ''>('')
const [assetOffset, setAssetOffset] = useState(0)
const [publicationPage, setPublicationPage] = useState<TestPublicationPage>(emptyPublicationPage)
const [publicationLoading, setPublicationLoading] = useState(true)
const [publicationError, setPublicationError] = useState<string | null>(null)
const [publicationState, setPublicationState] = useState<ProcessingState | ''>('')
const [publicationOffset, setPublicationOffset] = useState(0)
const [retryingId, setRetryingId] = useState<string | null>(null)
const [reviewPage, setReviewPage] = useState<ReviewCandidatePage>(emptyReviewPage)
const [reviewLoading, setReviewLoading] = useState(true)
const [reviewError, setReviewError] = useState<string | null>(null)
const [reviewingId, setReviewingId] = useState<string | null>(null)
const [batchPage, setBatchPage] = useState<ReleaseBatchPage>(emptyBatchPage)
const [batchDetail, setBatchDetail] = useState<ReleaseBatchDetail | null>(null)
const [batchLoading, setBatchLoading] = useState(true)
const [batchError, setBatchError] = useState<string | null>(null)
const [mutatingBatchId, setMutatingBatchId] = useState<string | null>(null)
const [releaseCapabilities, setReleaseCapabilities] = useState<ReleaseCapabilities>(disabledReleaseCapabilities)
const [releasePlan, setReleasePlan] = useState<ReleasePlan>(emptyReleasePlan)
const [releaseChangeSet, setReleaseChangeSet] = useState<ReleaseChangeSetDetail | null>(null)
const [changeSetBusy, setChangeSetBusy] = useState(false)
const [changeSetError, setChangeSetError] = useState<string | null>(null)
const [selectedDeleteIDs, setSelectedDeleteIDs] = useState<string[]>([])
const [executionPage, setExecutionPage] = useState<ReleaseExecutionPage>(emptyExecutionPage)
const [executionDetail, setExecutionDetail] = useState<ReleaseExecutionDetail | null>(null)
const [executionChain, setExecutionChain] = useState<ReleaseAuditChain | null>(null)
const [executionLoading, setExecutionLoading] = useState(true)
const [executionError, setExecutionError] = useState<string | null>(null)
const [workspace, setWorkspace] = useState<WorkspaceState>(() => {
if (typeof window === 'undefined') return initialWorkspace
try {
return restoreWorkspace(window.localStorage.getItem(workspaceStorageKey))
} catch {
return initialWorkspace
}
})
const load = useCallback(async (signal?: AbortSignal) => {
setLoading(true)
setError(null)
try {
setJobs(await fetchJobs(signal))
} catch (cause) {
if (cause instanceof DOMException && cause.name === 'AbortError') return
setError(cause instanceof Error ? cause.message : '加载任务失败')
} finally {
setLoading(false)
}
}, [])
const loadAssets = useCallback(async (signal?: AbortSignal) => {
setAssetLoading(true)
setAssetError(null)
try {
setAssetPage(await fetchSourceAssets({ state: assetState, limit: 50, offset: assetOffset }, signal))
} catch (cause) {
if (cause instanceof DOMException && cause.name === 'AbortError') return
setAssetError(cause instanceof Error ? cause.message : '加载知识资产失败')
} finally {
setAssetLoading(false)
}
}, [assetOffset, assetState])
const loadConnections = useCallback(async (signal?: AbortSignal) => {
setConnectionLoading(true)
setConnectionError(null)
try {
setConnectionPage(await fetchSourceConnections(signal))
} catch (cause) {
if (cause instanceof DOMException && cause.name === 'AbortError') return
setConnectionError(cause instanceof Error ? cause.message : '加载来源连接失败')
} finally {
setConnectionLoading(false)
}
}, [])
const loadSourceScans = useCallback(async (connectionID: string, signal?: AbortSignal) => {
setScanLoading(true)
setScanError(null)
try {
const page = await fetchSourceScans(connectionID, 20, 0, signal)
setScanPage(page)
const latest = page.items[0]
setSelectedScanId(latest?.id ?? null)
setScanDetail(latest ? await fetchSourceScanDetail(connectionID, latest.id, signal) : null)
} catch (cause) {
if (cause instanceof DOMException && cause.name === 'AbortError') return
setScanError(cause instanceof Error ? cause.message : '加载扫描记录失败')
} finally {
setScanLoading(false)
}
}, [])
const handleSelectScan = useCallback(async (connectionID: string, scanID: string) => {
setSelectedScanId(scanID)
setScanLoading(true)
setScanError(null)
try {
setScanDetail(await fetchSourceScanDetail(connectionID, scanID))
} catch (cause) {
setScanError(cause instanceof Error ? cause.message : '加载扫描详情失败')
} finally {
setScanLoading(false)
}
}, [])
const handleTriggerSourceScan = useCallback(async (connectionID: string) => {
setScanningConnectionId(connectionID)
setConnectionError(null)
try {
await triggerSourceScan(connectionID)
await loadConnections()
} catch (cause) {
setConnectionError(cause instanceof Error ? cause.message : '触发来源扫描失败')
} finally {
setScanningConnectionId(null)
}
}, [loadConnections])
const loadPublications = useCallback(async (signal?: AbortSignal) => {
setPublicationLoading(true)
setPublicationError(null)
try {
setPublicationPage(await fetchTestPublications({ processing_state: publicationState, limit: 50, offset: publicationOffset }, signal))
} catch (cause) {
if (cause instanceof DOMException && cause.name === 'AbortError') return
setPublicationError(cause instanceof Error ? cause.message : '加载测试发布失败')
} finally {
setPublicationLoading(false)
}
}, [publicationOffset, publicationState])
const handleRetry = useCallback(async (id: string) => {
setRetryingId(id)
try {
await retryPublication(id)
await loadPublications()
} catch (cause) {
setPublicationError(cause instanceof Error ? cause.message : '重试失败')
} finally {
setRetryingId(null)
}
}, [loadPublications])
const loadReviews = useCallback(async (signal?: AbortSignal) => {
setReviewLoading(true)
setReviewError(null)
try {
setReviewPage(await fetchReviewCandidates('', 20, 0, signal))
} catch (cause) {
if (cause instanceof DOMException && cause.name === 'AbortError') return
setReviewError(cause instanceof Error ? cause.message : '加载审核队列失败')
} finally {
setReviewLoading(false)
}
}, [])
const loadBatches = useCallback(async (signal?: AbortSignal) => {
setBatchLoading(true)
setBatchError(null)
try {
const page = await fetchReleaseBatches('', 20, 0, signal)
setBatchPage(page)
setBatchDetail(page.items[0] ? await fetchReleaseBatch(page.items[0].id, signal) : null)
} catch (cause) {
if (cause instanceof DOMException && cause.name === 'AbortError') return
setBatchError(cause instanceof Error ? cause.message : '加载封批列表失败')
} finally {
setBatchLoading(false)
}
}, [])
const handleReview = useCallback(async (publicationID: string, decision: 'approved' | 'rejected', visibility: Visibility, decisionCode: string) => {
setReviewingId(publicationID)
setReviewError(null)
try {
await reviewPublication(publicationID, decision, visibility, decisionCode)
await loadReviews()
} catch (cause) {
setReviewError(cause instanceof Error ? cause.message : '提交审核决定失败')
} finally {
setReviewingId(null)
}
}, [loadReviews])
const reloadChangeSet = useCallback(async () => {
setReleaseChangeSet(await fetchLatestReleaseChangeSet().catch(() => null))
}, [])
const handleGenerateChangeSet = useCallback(async (name: string) => {
setChangeSetBusy(true)
setChangeSetError(null)
try {
await generateReleaseChangeSet(name)
await reloadChangeSet()
} catch (cause) {
setChangeSetError(cause instanceof Error ? cause.message : '生成发布计划集失败')
} finally {
setChangeSetBusy(false)
}
}, [reloadChangeSet])
const handleConfirmChangeSet = useCallback(async (changeSetID: string) => {
setChangeSetBusy(true)
setChangeSetError(null)
try {
await confirmReleaseChangeSet(changeSetID)
await reloadChangeSet()
} catch (cause) {
setChangeSetError(cause instanceof Error ? cause.message : '确认发布计划集失败')
} finally {
setChangeSetBusy(false)
}
}, [reloadChangeSet])
const handleCreateBatch = useCallback(async (name: string, publicationIDs: string[], deletePublicationIDs: string[]) => {
setMutatingBatchId('creating')
setBatchError(null)
try {
const batch = await createReleaseBatch(name, publicationIDs, deletePublicationIDs, releaseChangeSet?.state === 'confirmed' ? releaseChangeSet.id : '')
setSelectedDeleteIDs([])
await loadBatches()
setBatchDetail(await fetchReleaseBatch(batch.id))
} catch (cause) {
setBatchError(cause instanceof Error ? cause.message : '创建封批失败')
} finally {
setMutatingBatchId(null)
}
}, [loadBatches, releaseChangeSet])
const handleSealBatch = useCallback(async (batchID: string) => {
setMutatingBatchId(batchID)
setBatchError(null)
try {
await sealReleaseBatch(batchID)
await loadBatches()
setBatchDetail(await fetchReleaseBatch(batchID))
} catch (cause) {
setBatchError(cause instanceof Error ? cause.message : '封批失败')
} finally {
setMutatingBatchId(null)
}
}, [loadBatches])
const handleSelectBatch = useCallback(async (batchID: string) => {
setBatchLoading(true)
setBatchError(null)
try {
setBatchDetail(await fetchReleaseBatch(batchID))
} catch (cause) {
setBatchError(cause instanceof Error ? cause.message : '加载封批详情失败')
} finally {
setBatchLoading(false)
}
}, [])
const loadReleaseExecutions = useCallback(async (signal?: AbortSignal) => {
setExecutionLoading(true)
setExecutionError(null)
try {
const [capabilities, page, plan, changeSet] = await Promise.all([
fetchReleaseCapabilities(signal),
fetchReleaseExecutions('', '', 20, 0, signal),
fetchReleasePlan(signal),
fetchLatestReleaseChangeSet(signal).catch(() => null),
])
setReleaseCapabilities(capabilities)
setExecutionPage(page)
setReleasePlan(plan)
setReleaseChangeSet(changeSet)
setSelectedDeleteIDs((current) => current.filter((publicationID) => plan.items.some((item) => item.publication_id === publicationID && item.action === 'delete' && item.can_release)))
setExecutionDetail(page.items[0] ? await fetchReleaseExecution(page.items[0].id, signal) : null)
} catch (cause) {
if (cause instanceof DOMException && cause.name === 'AbortError') return
setExecutionError(cause instanceof Error ? cause.message : '加载生产发布审计失败')
} finally {
setExecutionLoading(false)
}
}, [])
const handleSelectExecution = useCallback(async (executionID: string) => {
setExecutionLoading(true)
setExecutionError(null)
try {
const [detail, chain] = await Promise.all([fetchReleaseExecution(executionID), fetchReleaseAuditChain(executionID)])
setExecutionDetail(detail)
setExecutionChain(chain)
} catch (cause) {
setExecutionError(cause instanceof Error ? cause.message : '加载生产发布详情失败')
} finally {
setExecutionLoading(false)
}
}, [])
const ppConnection = connectionPage.items.find((item) => item.source_type === 'pp')
const ppConnectionID = ppConnection?.id ?? ''
const ppLastScanID = ppConnection?.last_scan?.id ?? ''
const ppLastScanState = ppConnection?.last_scan?.state ?? ''
useEffect(() => {
const controller = new AbortController()
void load(controller.signal)
return () => controller.abort()
}, [load])
useEffect(() => {
const controller = new AbortController()
void loadAssets(controller.signal)
return () => controller.abort()
}, [loadAssets])
useEffect(() => {
const controller = new AbortController()
void loadConnections(controller.signal)
return () => controller.abort()
}, [loadConnections])
useEffect(() => {
if (!ppConnectionID) return
const controller = new AbortController()
void loadSourceScans(ppConnectionID, controller.signal)
return () => controller.abort()
}, [loadSourceScans, ppConnectionID, ppLastScanID, ppLastScanState])
useEffect(() => {
if (!connectionPage.items.some((item) => item.last_scan?.state === 'pending' || item.last_scan?.state === 'running')) return
const timer = window.setTimeout(() => void loadConnections(), 1000)
return () => window.clearTimeout(timer)
}, [connectionPage, loadConnections])
useEffect(() => {
const controller = new AbortController()
void loadPublications(controller.signal)
return () => controller.abort()
}, [loadPublications])
useEffect(() => {
const controller = new AbortController()
void loadReviews(controller.signal)
return () => controller.abort()
}, [loadReviews])
useEffect(() => {
const controller = new AbortController()
void loadBatches(controller.signal)
return () => controller.abort()
}, [loadBatches])
useEffect(() => {
const controller = new AbortController()
void loadReleaseExecutions(controller.signal)
return () => controller.abort()
}, [loadReleaseExecutions])
useEffect(() => {
try {
window.localStorage.setItem(workspaceStorageKey, JSON.stringify(workspace))
} catch {
// Storage can be unavailable in privacy modes; tab navigation still works in memory.
}
}, [workspace])
return (
<WorkspaceShell
workspace={workspace}
onOpen={(moduleId) => setWorkspace((current) => openModule(current, moduleId))}
onClose={(moduleId) => setWorkspace((current) => closeModule(current, moduleId))}
>
{workspace.activeTab === 'dashboard' ? <SourceCatalogBrowser /> : workspace.activeTab === 'tasks' ? <WeKnoraMonitor /> : workspace.activeTab === 'sources' ? <SourceLinkManager /> : workspace.activeTab === 'settings' ? <SystemSettings /> : workspace.activeTab === 'knowledge' ? <DocumentWorkbench
mode="attention"
connections={connectionPage.items}
/> : <ModulePage
moduleId={workspace.activeTab}
jobs={jobs}
loading={loading}
error={error}
onRefresh={() => void load()}
connectionPage={connectionPage}
connectionLoading={connectionLoading}
connectionError={connectionError}
onConnectionRefresh={() => {
void loadConnections()
if (ppConnectionID) void loadSourceScans(ppConnectionID)
}}
scanningConnectionId={scanningConnectionId}
onTriggerSourceScan={(id) => void handleTriggerSourceScan(id)}
scanPage={scanPage}
scanDetail={scanDetail}
scanLoading={scanLoading}
scanError={scanError}
selectedScanId={selectedScanId}
onSelectScan={(connectionID, scanID) => void handleSelectScan(connectionID, scanID)}
assetPage={assetPage}
assetLoading={assetLoading}
assetError={assetError}
assetState={assetState}
onAssetStateChange={(state) => {
setAssetState(state)
setAssetOffset(0)
}}
onAssetPageChange={setAssetOffset}
onAssetRefresh={() => void loadAssets()}
publicationPage={publicationPage}
publicationLoading={publicationLoading}
publicationError={publicationError}
publicationState={publicationState}
retryingId={retryingId}
onPublicationStateChange={(state) => {
setPublicationState(state)
setPublicationOffset(0)
}}
onPublicationPageChange={setPublicationOffset}
onPublicationRefresh={() => void loadPublications()}
onRetry={(id) => void handleRetry(id)}
reviewPage={reviewPage}
reviewLoading={reviewLoading}
reviewError={reviewError}
reviewingId={reviewingId}
batchPage={batchPage}
batchDetail={batchDetail}
batchLoading={batchLoading}
batchError={batchError}
mutatingBatchId={mutatingBatchId}
onReview={(publicationID, decision, visibility, decisionCode) => void handleReview(publicationID, decision, visibility, decisionCode)}
onReviewRefresh={() => void loadReviews()}
onCreateBatch={(name, publicationIDs, deletePublicationIDs) => void handleCreateBatch(name, publicationIDs, deletePublicationIDs)}
onSealBatch={(batchID) => void handleSealBatch(batchID)}
onSelectBatch={(batchID) => void handleSelectBatch(batchID)}
onBatchRefresh={() => void loadBatches()}
releaseCapabilities={releaseCapabilities}
releasePlan={releasePlan}
releaseChangeSet={releaseChangeSet}
changeSetBusy={changeSetBusy}
changeSetError={changeSetError}
onGenerateChangeSet={handleGenerateChangeSet}
onConfirmChangeSet={handleConfirmChangeSet}
selectedDeleteIDs={selectedDeleteIDs}
onToggleDelete={(publicationID) => setSelectedDeleteIDs((current) => current.includes(publicationID) ? current.filter((id) => id !== publicationID) : [...current, publicationID])}
executionPage={executionPage}
executionDetail={executionDetail}
executionChain={executionChain}
executionLoading={executionLoading}
executionError={executionError}
onSelectExecution={(executionID) => void handleSelectExecution(executionID)}
onExecutionRefresh={() => void loadReleaseExecutions()}
/>}
</WorkspaceShell>
)
}