import { useCallback, useEffect, useMemo, useState } from 'react' import { TopBarUser, useOptionalAuth } from './auth' import { DocumentWorkbench } from './DocumentWorkbench' import { SourceCatalogBrowser } from './SourceCatalogBrowser' import { WeKnoraMonitor } from './WeKnoraMonitor' import { VersionHistory } from './VersionHistory' import { ReleaseTargets } from './ReleaseTargets' import { QAOperations } from './QAOperations' 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, productionConfirmationPhrases, reviewPublication, runProductionAction, sealReleaseBatch, reviewPublicationsBatch, runPublishNow, } from './reviewRelease' import type { ProductionActionKind } 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 { 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: 'qaops', label: '问答运营', icon: '▤' }, { id: 'releases', label: '发布管理', icon: '⇧' }, { id: 'settings', label: '系统设置', icon: '⚙' }, { id: 'versions', label: '版本记录', icon: '⌥' }, ] interface WorkspaceShellProps { workspace: WorkspaceState onOpen: (moduleId: ModuleId) => void children: React.ReactNode } export function WorkspaceShell(props: WorkspaceShellProps) { const [navigationOpen, setNavigationOpen] = useState(false) const [contextTabs, setContextTabs] = useState([]) const activeModule = modules.find((item) => item.id === props.workspace.activeTab) return (
{navigationOpen ? (
知识治理 {activeModule?.label ?? '工作台'}
{props.children}
) } const stateLabels: Record = { 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'] onBatchReview?: ReleaseManagementProps['onBatchReview'] reviewBatchMessage?: string 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 pendingReleaseAction?: PendingReleaseAction | null releaseActionPhrase?: string releaseActionBusy?: boolean releaseActionError?: string | null releaseActionMessage?: string | null onStartReleaseAction?: ( kind: ProductionActionKind, id: string, label: string, ids?: string[], deleteIDs?: string[] ) => void onReleaseActionPhrase?: (value: string) => void onSubmitReleaseAction?: () => void onCancelReleaseAction?: () => void } // 页面上的生产动作:管理员会话 + 服务端逐字核对的固定确认语句。 export interface PendingReleaseAction { kind: ProductionActionKind id: string label: string /** publish_now 专用:这次要发布哪些条目(含待删除)。 */ publicationIDs?: string[] deletePublicationIDs?: string[] } 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, test_auto_review_policy: '', } 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, onBatchReview = () => undefined, reviewBatchMessage = '', 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, pendingReleaseAction = null, releaseActionPhrase = '', releaseActionBusy = false, releaseActionError = null, releaseActionMessage = null, onStartReleaseAction = () => undefined, onReleaseActionPhrase = () => undefined, onSubmitReleaseAction = () => undefined, onCancelReleaseAction = () => undefined, }: ModulePageProps) { if (moduleId === 'tasks') { return ( ) } if (moduleId === 'knowledge') { return ( ) } if (moduleId === 'sources') { return ( ) } if (moduleId === 'releases') { return (
文档级发布(旧流程,折叠保留):单篇文档发布成功不等于整库发布成功
) } if (moduleId === 'settings') { return } 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 (

P2 · 知识治理总览

治理工作台

集中查看任务状态与平台安全边界。

{error ? (
{error}
) : null}
运行安全 PP历史来源清单已接管;生产写入: {releaseCapabilities.production_release_requests_enabled ? releaseCapabilities.production_backup_restore_verified ? '已开启' : '已开启(快照恢复未验证,仍被阻断)' : '关闭'} ;测试 / 生产 WeKnora 连接状态以「系统设置 → 服务配置」的实时探测为准。
Release Worker 默认关闭

最近任务

显示最近5条真实队列记录

{!loading && !error && jobs.length === 0 ? (
暂无任务。可前往“同步任务”查看队列详情。
) : null} {jobs.length > 0 ? (
{jobs.slice(0, 5).map((job) => (
{job.type} {job.id}
{stateLabels[job.state]}
))}
) : null}
) } interface KnowledgeInventoryProps { page: SourceAssetPage loading: boolean error: string | null state: LegacyStatus | '' onStateChange: (state: LegacyStatus | '') => void onPageChange: (offset: number) => void onRefresh: () => void } const legacyStatusLabels: Record = { completed: '历史已同步', content_alias: '内容别名', over_limit: '超过旧同步上限', } const sourceTypeLabels: Record = { pp: 'PP', alist: 'AList', dingtalk: '钉钉', manual: '手工验收', } const sourceHealthLabels: Record = { 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 = { pending: '待扫描', running: '扫描中', completed: '已完成', failed: '失败', } const sourceScanChangeLabels: Record = { 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 (

连接情况

来源连接

查看来源是否可读、多久检查一次。日常文件操作请进入“来源与目录”。

{error ? (
{error}
) : null}

来源连接

PP检查的是本机已保存快照,不是实时拉取网站。检查不会修改来源,也不会自动上传或删除文件。

来源只读
{!loading && !error && page.items.length === 0 ?
尚无来源连接。
: null} {page.items.length > 0 ? (
{page.items.map((item) => { const activeScan = item.last_scan?.state === 'pending' || item.last_scan?.state === 'running' return ( ) })}
连接 类型 状态 调度 健康 对象数 最近扫描 操作
{item.name.startsWith('PP legacy ') ? 'PP公开文档' : item.name} {sourceTypeLabels[item.source_type] ?? item.source_type} {item.enabled ? '已启用' : '已停用'} {item.schedule_configured ? '已配置' : '未配置'} {sourceHealthLabels[item.health_status] ?? item.health_status} {item.item_count} {item.last_scan ? (
最近扫描 · {sourceScanLabels[item.last_scan.state] ?? item.last_scan.state} 观察 {item.last_scan.observed_items} · 未变化 {item.last_scan.unchanged_items} 新增 {item.last_scan.added_items} · 更新 {item.last_scan.updated_items} · 缺失{' '} {item.last_scan.missing_items} 超过上限 {item.last_scan.over_limit_items} · 待上传 {item.last_scan.planned_uploads} {item.last_scan.error_code ? {item.last_scan.error_code} : null}
) : ( '尚未扫描' )}
{item.source_type === 'pp' ? ( ) : ( '暂未支持检查' )}
) : null}
查看检查历史与审计记录

扫描历史与变化记录

展示安全聚合和治理侧变化标识;不展示来源路径、修订值或快照指纹。

审计只读
{scanError ? (
{scanError}
) : null} {!scanLoading && !scanError && scanPage.items.length === 0 ? (
当前来源尚无扫描历史。
) : null} {scanPage.items.length > 0 ? (
{scanPage.items.map((scan) => ( ))}
扫描 状态 观察 变化 上限阻断 操作
{scan.id} {sourceScanLabels[scan.state] ?? scan.state} {scan.observed_items} 新增 {scan.added_items} · 更新 {scan.updated_items} · 缺失 {scan.missing_items} {scan.over_limit_items}

变化记录

{scanLoading ?
加载扫描记录中…
: null} {!scanLoading && !scanDetail ?
选择一条扫描查看变化。
: null} {!scanLoading && scanDetail?.changes.length === 0 ? (
本次扫描未发现新增、更新或不可用变化。
) : null} {!scanLoading && scanDetail && scanDetail.changes.length > 0 ? (
{scanDetail.changes.map((change) => ( ))}
类型 治理资产 大小 记录时间
{sourceScanChangeLabels[change.change_type] ?? change.change_type} {change.source_item_id ?? change.id} {change.observed_size_bytes === null ? '—' : formatBytes(change.observed_size_bytes)} {formatTime(change.created_at)}
) : null}
) : null}
) } 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 (

P2 · 统一治理清单

知识资产

统一展示各类治理来源;清单只读,不会修改或重新上传来源文件。

{error ? (
{error}
) : null}

统一来源清单

按当前治理版本分页读取,超限项保持阻断。

{!loading && !error && page.items.length === 0 ?
当前筛选没有资产。
: null} {page.items.length > 0 ? (
{page.items.map((item) => ( ))}
资产ID 来源 大小 历史状态 可见性 测试处理 更新时间
{item.id} {sourceTypeLabels[item.source_type] ?? item.source_type} {formatBytes(item.size_bytes)} {item.legacy_status ? legacyStatusLabels[item.legacy_status] : item.content_state} {item.visibility === 'external' ? '对外' : '对内'} {item.has_publication ? item.processing_state : '阻断'} {formatTime(item.updated_at)}
) : null}
第 {Math.floor(page.offset / page.limit) + 1} 页
) } 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 (

P1 · 任务编排基础

同步任务

查看持久队列、执行状态、重试次数和最近错误。

最近任务

按创建时间倒序显示最近50条任务

Release Worker 默认关闭
{error ? (
{error}
) : null} {!loading && !error && jobs.length === 0 ? (
暂无任务。P1可通过API创建demo任务验证队列。
) : null} {jobs.length > 0 ? (
{jobs.map((job) => ( ))}
任务ID 类型 状态 尝试 更新时间 错误
{job.id} {job.type} {stateLabels[job.state]} {job.attempt}/{job.max_attempts} {formatTime(job.updated_at)} {job.last_error || '—'}
) : null}
) } const processingLabels: Record = { planned: '待入库', pending: '待处理', processing: '解析中', finalizing: '定稿中', completed: '已完成', failed: '失败', stalled: '停滞', cancelled: '已取消', } 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 /** P0-3 批量审核:一次对多条候选下同一个决定。 */ onBatchReview?: ( publicationIDs: string[], decision: 'approved' | 'rejected', visibility: Visibility, decisionCode: string ) => void /** 批量审核的结果消息(如实说明哪几条没批成)。 */ reviewBatchMessage?: string 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 pendingReleaseAction?: PendingReleaseAction | null releaseActionPhrase?: string releaseActionBusy?: boolean releaseActionError?: string | null releaseActionMessage?: string | null onStartReleaseAction?: ( kind: ProductionActionKind, id: string, label: string, ids?: string[], deleteIDs?: string[] ) => void onReleaseActionPhrase?: (value: string) => void onSubmitReleaseAction?: () => void onCancelReleaseAction?: () => void } const releaseActionLabels: Record = { authorize: '授权发布', retry: '重排执行', rollback: '回滚发布', publish_now: '发布到生产', } const acceptanceLabels: Record = { pending: '待验收', passed: '通过', failed: '失败', manual_required: '需人工确认', } const reviewLabels: Record = { pending: '待审核', approved: '已批准', rejected: '已驳回', } const batchLabels: Record = { draft: '草稿', sealed: '清单已锁定', cancelled: '已取消', } const executionLabels: Record = { 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 = { 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) => item.review_state === 'approved' && item.gate_status === 'ready' ? '测试已通过' : item.gate_status === 'ready' ? '可以审核' : '暂时不能审核' function releaseFailureMessage(code: string) { if (!code) return '' const labels: Record = { release_contract_mismatch: '目标环境与测试环境不一致,已停止发布', release_verification_failed: '发布后的检索验证未通过', release_item_failed: '部分知识发布失败', release_retryable: '遇到临时故障,系统将自动重试', release_manifest_mismatch: '发布结果与冻结的发布清单不一致,已降级为失败', release_rollback_failed: '自动回滚失败,需整体快照恢复(等待授权)', release_target_snapshot_missing: '缺少目标知识库的发布前快照留档,已拒绝发布(先跑 scripts/target_kb_snapshot.sh)', } 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: '生产危险操作' }, ] 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: 4, title: `现在要做:锁定 ${drafts} 个草稿批次`, reason: '暂时不能继续:草稿内容还可以变化,发布清单尚未锁定', action: '核对批次内容,然后点击“锁定清单(不会上线)”', after: '第 5 步,等待生产负责人确认', 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: '查看当前结果', } } // 审核策略文案:让运维一眼看到"现在自动批准到什么程度",而不是靠猜。 function autoReviewNote(policy: string): string { if (policy === 'off') return '审核策略:全部人工审核(验收通过也不会自动批准)。' if (policy === 'internal') return '审核策略:对内知识验收通过后由系统自动批准(记为 system:auto);对外仍需人工。' if (policy === 'all') return '审核策略:对内对外都在验收通过后由系统自动批准;对外发布请另行把关。' return '' } export function ReleaseManagement(props: ReleaseManagementProps) { /* R3 pagination probe */ const auth = useOptionalAuth() const isAdmin = auth?.identity?.role === 'admin' 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([]) const [deleteConfirmed, setDeleteConfirmed] = useState(false) const [visibilityByID, setVisibilityByID] = useState>({}) 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 ? '生产操作权限:已阻断' : '生产操作权限:等待负责人确认' // 建批只绑定"已确认"的版本;所选知识不在那份清单里时必定 422(今天实测的坑)。 // P0-1 之后建批会自己冻结当前计划,所以不再有"所选知识不在冻结清单里"这种阻断。 // P0-1 之后不再有"所选知识不在已冻结清单里"这种阻断:清单在建批那一刻才冻结。 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] ) } // 待发布 = 已批准且门禁通过,可以直接发。待审核 = 尚未决定(对内通常已由系统自动批准,所以多为空)。 const publishReady = props.reviewPage.items.filter( (item) => item.review_state === 'approved' && item.gate_status === 'ready' ) const pendingItems = props.reviewPage.items.filter((item) => item.review_state === 'pending') const rejectedItems = props.reviewPage.items.filter((item) => item.review_state === 'rejected') const publishableSelected = selectedIDs.filter((id) => publishReady.some((item) => item.publication_id === id)) const selectedDeleteIDs = props.selectedDeleteIDs.filter(() => deleteConfirmed) const publishSelectedIDs = [...publishableSelected, ...selectedDeleteIDs] const startPublish = (ids: string[], label: string, deleteIDs: string[] = []) => props.onStartReleaseAction?.('publish_now', 'publish-now', label, ids, deleteIDs) // 计划表筛选与分页(默认视图里这块在「更多」里,保留筛选与分页以免一次渲染上百行)。 const planFiltered = props.releasePlan.items.filter((item) => { if (planOnlyReleasable && !item.can_release) return false if (planActionFilter === 'blocked' ? item.can_release : planActionFilter ? item.action !== planActionFilter : false) return false if (planScopeFilter && item.target_scope !== planScopeFilter) return false return true }) const actionLabel = (item: ReleasePlanItem) => item.action === 'add' ? '新增' : item.action === 'update' ? '更新' : item.action === 'delete' ? '删除' : '等待测试' const planPageCount = Math.max(1, Math.ceil(planFiltered.length / planPageSize)) const planSafePage = Math.min(planPage, planPageCount - 1) const planPageItems = planFiltered.slice(planSafePage * planPageSize, planSafePage * planPageSize + planPageSize) return (

发布管理

挑一条知识点“发布到生产”,输入确认语句即可。生产发布仍由门禁、备份快照与负责人确认保护。

{productionStatus} {props.releaseCapabilities.production_backup_restore_verified ? '发布前会创建可恢复快照;失败自动按快照回滚。' : '生产发布已阻断:先完成生产快照并通过恢复验证。'}
{props.releaseCapabilities.production_release_requests_enabled ? '修改生产内容:待确认' : '修改生产内容:关闭'}
查看技术状态

{`生产请求门禁${props.releaseCapabilities.production_release_requests_enabled ? '已开启' : '已关闭'};快照恢复验证${props.releaseCapabilities.production_backup_restore_verified ? '已通过' : '未通过'}。`}

{props.releaseActionError ? (
{props.releaseActionError}
) : null} {props.releaseActionMessage ? (

{props.releaseActionMessage}

) : null}

待发布({publishReady.length} {props.selectedDeleteIDs.length ? ` + 下架 ${props.selectedDeleteIDs.length}` : ''})

已批准、可直接发布到生产的知识。点单条后面的按钮即可发布。

{autoReviewNote(props.releaseCapabilities.test_auto_review_policy) ? (

{autoReviewNote(props.releaseCapabilities.test_auto_review_policy)}

) : null}
{props.reviewBatchMessage ? {props.reviewBatchMessage} : null}
{props.reviewError ? (
{props.reviewError}
) : null} {!props.reviewLoading && publishReady.length === 0 ? (
没有待发布的已批准知识。到「来源与目录」标注后,在「解析监控」处理完成即可发布。
) : null} {publishReady.length > 0 ? (
{publishReady.map((item) => ( ))}
选择 知识 目标 测试 审核 操作
toggleSelected(item.publication_id)} /> {item.title} {sourceTypeLabels[item.source_type] ?? item.source_type} {item.current_visibility === 'internal' ? '对内知识库' : '对外知识库'} {item.knowledge_exists === 'passed' && item.chunks_present === 'passed' ? '通过' : '未通过'} 已批准 {item.reviewer_ref ? {item.reviewer_ref} : null}
) : null} {pendingItems.length > 0 ? ( <>

待你审核({pendingItems.length})

先确认测试结果与发布范围,再批准或驳回。可批准的多条可一次批。

{batchBlocker ? (
{`为什么按钮不能点:${batchBlocker}`}
) : null}
{pendingItems.map((item) => { const visibility = visibilityByID[item.publication_id] ?? (item.decided_visibility || item.current_visibility) return ( ) })}
选择 知识 测试结果 能否继续 发布范围 操作
toggleSelected(item.publication_id)} /> {item.title} {sourceTypeLabels[item.source_type] ?? item.source_type} {item.knowledge_exists === 'passed' && item.chunks_present === 'passed' ? '基础测试通过' : '基础测试未通过'} {item.retrieval_hit === 'manual_required' ? '搜索效果需人工确认' : `搜索测试${acceptanceLabels[item.retrieval_hit]}`} {reviewGateLabel(item)}
) : null} {rejectedItems.length > 0 ? (
已驳回({rejectedItems.length})
    {rejectedItems.map((item) => (
  • {item.title}
  • ))}
) : null}

发布记录

最近 20 条生产发布与回滚。生产确认、发布验证与回滚都由 Release Worker 完成,这里只读展示结果。

{props.releaseCapabilities.production_release_requests_enabled ? '生产操作可执行(待确认)' : '生产操作已锁定'} Release Worker 默认关闭
{props.pendingReleaseAction ? (

{releaseActionLabels[props.pendingReleaseAction.kind]}「{props.pendingReleaseAction.label}」—— 请输入固定确认语句 {productionConfirmationPhrases[props.pendingReleaseAction.kind]} 后执行。

props.onReleaseActionPhrase?.(event.target.value)} placeholder={productionConfirmationPhrases[props.pendingReleaseAction.kind]} aria-label="生产动作确认语句" />
) : null} {props.executionError ? (
{props.executionError}
) : null} {!props.executionLoading && !props.executionError && props.executionPage.items.length === 0 ? (
还没有发布记录。发布一条知识后,这里会出现执行进度与逐项结果。
) : null} {props.executionPage.items.length > 0 ? (
{props.executionPage.items.map((execution) => ( ))}
开始时间 操作 状态 批次进度 完成进度 授权人 操作
{formatTime(execution.created_at)} {execution.operation === 'publish' ? '发布' : '回滚'} {executionLabels[execution.state]} {executionStateDetail(execution, props.executionPage.items) ? ( {executionStateDetail(execution, props.executionPage.items)} ) : null} {execution.error_code ? {releaseFailureMessage(execution.error_code)} : null} {execution.total_batches > 0 ? `批次 ${execution.current_batch} / ${execution.total_batches}` : '等待开始'} 每批最多 {execution.batch_size} 项 {execution.completed_item_count}/{execution.item_count} {execution.failed_item_count ? 失败 {execution.failed_item_count} : null} {execution.authorized_by}
{isAdmin && execution.state === 'failed' ? ( ) : null} {isAdmin && execution.operation === 'publish' && execution.state === 'completed' ? ( ) : null}

每项知识的结果

{props.executionDetail ? ( <> {props.executionDetail.items.map((item) => { const result = releaseItemResult(item) return (
{item.title} {result.detail} {item.target_knowledge_base_id ? ` · 目标库 ${item.target_knowledge_base_id.slice(0, 8)}…` : ''} {item.error_code ? ` · ${releaseFailureMessage(item.error_code)}` : ''} {result.outcome}
) })} {props.executionDetail.items.length === 0 ? (
发布尚无逐项结果。
) : null} ) : (
点击“查看结果”核对每项知识。
)}
) : null} {props.executionChain ? (

发布审计链

批次 {props.executionChain.release_batch_name || '未绑定批次'} {`创建 ${props.executionChain.created_by || '—'} · 锁定 ${props.executionChain.sealed_by || '—'} · 授权 ${props.executionChain.authorized_by || '—'}`}
{props.executionChain.release_change_set_id ? (
发布计划集 {props.executionChain.release_change_set_name} {`${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)}`}
) : null} {props.executionChain.snapshots.length ? (
来源快照 {props.executionChain.snapshots.map((snap) => `${snap.source_name}(${snap.file_count})`).join('、')}
) : null} {props.executionChain.rollback_execution_id ? (
补偿回滚 已关联回滚执行
) : null}
) : null}
更多 · 发布计划、下架与批次清单

发布计划

来源与目录 → 测试知识库 → 生产知识库。来源标注是最终 Truth Source。

按知识级别同步
新增 {props.releasePlan.summary.add} 更新 {props.releasePlan.summary.update} 删除 {props.releasePlan.summary.delete} 阻断 {props.releasePlan.summary.blocked} 未变化 {props.releasePlan.summary.unchanged}
{`筛选 ${planFiltered.length} / 全部 ${props.releasePlan.items.length}`}
{planPageItems.length ? (
{planPageItems.map((item, index) => ( ))}
选择 知识 目标 计划动作 测试状态 生产状态 能否发布
{item.action === 'delete' && item.can_release ? ( { props.onToggleDelete(item.publication_id) setDeleteConfirmed(false) }} /> ) : ( '—' )} {item.title} {item.target_scope === 'internal' ? '对内知识库' : '对外知识库'} {actionLabel(item)} {item.test_state === 'ready' ? '已通过' : item.test_state === 'not_required' ? '无需测试' : '未就绪'} {item.production_state === 'present' ? '已存在' : '不存在'} {item.can_release ? item.action === 'delete' ? '将从生产检索中移除' : '可加入发布批次' : item.blocker === 'source_unavailable' ? '来源当前不可用,保留生产知识' : '测试未就绪,当前阻断'}
) : planFiltered.length ? (
当前筛选没有发布变更。
) : (
来源、测试与生产状态一致,当前没有发布变更。
)} {planPageCount > 1 ? (
{`第 ${planSafePage + 1} / ${planPageCount} 页 · 每页 ${planPageSize} 条`}
) : null}

冻结发布计划集

建批时自动冻结当前计划;同一份计划复用同一版本。

{changeSet ? changeSet.state === 'confirmed' ? `v${changeSet.number} · 已确认` : `v${changeSet.number} · 待确认` : '尚未生成'}
{changeSet ? (

{`清单 ${changeSet.item_count} 项(新增${changeSet.add_count}·更新${changeSet.update_count}·删除${changeSet.delete_count}·阻断${changeSet.blocked_count})· 摘要 ${changeSet.manifest_sha256.slice(0, 8)}…`}

) : null} {changeSetError ?

{changeSetError}

: null}
{changeSet ? ( 建批时自动冻结当前计划,无需手动确认冻结 ) : ( 建批时会自动冻结当前发布计划 )}
已选 {selectedCount} 项{props.selectedDeleteIDs.length > 0 && !deleteConfirmed ? '(删除待确认)' : ''}
创建批次还需要 确认所选发布动作 至少 1 项动作通过确认 填写批次名称

批次清单

建批即锁定;锁定 ≠ 上线。日常发布直接在上面「待发布」里点按钮;已锁定的批次也可以在这里逐条做生产确认。

锁定清单 ≠ 上线
{props.batchError ? (
{props.batchError}
) : null} {props.batchPage.items.length === 0 ? (
还没有批次。用上面的发布计划表创建,或直接在「待发布」里一键发布。
) : (
{props.batchPage.items.map((batch) => ( ))}
批次名称 状态 知识数量 内容状态 操作
{batch.name} {batchLabels[batch.state]} {batch.item_count} {batch.state === 'sealed' ? '内容已锁定' : '仍可检查调整'}
{batch.state === 'draft' ? ( ) : null} {batch.state === 'sealed' && isAdmin ? ( ) : null}

本批次包含

{props.batchDetail ? ( <> {props.batchDetail.items.map((item) => (
{item.title} {item.action === 'delete' ? '删除生产知识' : '新增或更新生产知识'} {item.decided_visibility === 'internal' ? '仅内部员工' : '允许外部用户'}
))} {props.batchDetail.items.length === 0 ?
批次没有知识。
: null} ) : (
点击“查看内容”核对本次发布清单。
)}
)}
) } 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 (

解析监控

查看测试知识库中每份资料的上传、解析和验收状态。

{error ? (
{error}
) : null}

{view === 'failed' ? '失败与停滞文件' : '解析队列'}

当前筛选共 {visibleItems.length} 条;仅返回治理安全投影,不含来源地址或凭据。

{!loading && !error && visibleItems.length === 0 ? (
当前筛选没有测试发布记录。
) : null} {visibleItems.length > 0 ? (
{visibleItems.map((item) => ( ))}
发布 标题 处理状态 重试次数 错误码 更新时间 操作
{item.id} {item.title} {processingLabels[item.processing_state]} {item.retry_count} {item.last_error || '—'} {formatTime(item.updated_at)} {item.can_retry ? ( ) : ( '—' )}
) : null}
第 {Math.floor(page.offset / page.limit) + 1} 页
) } function SummaryCard({ label, value, tone }: { label: string; value: number; tone: string }) { return (
{label} {value}
) } 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([]) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) const [connectionPage, setConnectionPage] = useState(emptyConnectionPage) const [connectionLoading, setConnectionLoading] = useState(true) const [connectionError, setConnectionError] = useState(null) const [scanningConnectionId, setScanningConnectionId] = useState(null) const [scanPage, setScanPage] = useState(emptyScanPage) const [scanDetail, setScanDetail] = useState(null) const [scanLoading, setScanLoading] = useState(false) const [scanError, setScanError] = useState(null) const [selectedScanId, setSelectedScanId] = useState(null) const [assetPage, setAssetPage] = useState(emptyAssetPage) const [assetLoading, setAssetLoading] = useState(true) const [assetError, setAssetError] = useState(null) const [assetState, setAssetState] = useState('') const [assetOffset, setAssetOffset] = useState(0) const [publicationPage, setPublicationPage] = useState(emptyPublicationPage) const [publicationLoading, setPublicationLoading] = useState(true) const [publicationError, setPublicationError] = useState(null) const [publicationState, setPublicationState] = useState('') const [publicationOffset, setPublicationOffset] = useState(0) const [retryingId, setRetryingId] = useState(null) const [reviewPage, setReviewPage] = useState(emptyReviewPage) const [reviewLoading, setReviewLoading] = useState(true) const [reviewError, setReviewError] = useState(null) const [reviewingId, setReviewingId] = useState(null) const [batchPage, setBatchPage] = useState(emptyBatchPage) const [batchDetail, setBatchDetail] = useState(null) const [batchLoading, setBatchLoading] = useState(true) const [batchError, setBatchError] = useState(null) const [mutatingBatchId, setMutatingBatchId] = useState(null) const [releaseCapabilities, setReleaseCapabilities] = useState(disabledReleaseCapabilities) const [releasePlan, setReleasePlan] = useState(emptyReleasePlan) const [releaseChangeSet, setReleaseChangeSet] = useState(null) const [changeSetBusy, setChangeSetBusy] = useState(false) const [changeSetError, setChangeSetError] = useState(null) const [selectedDeleteIDs, setSelectedDeleteIDs] = useState([]) const [executionPage, setExecutionPage] = useState(emptyExecutionPage) const [executionDetail, setExecutionDetail] = useState(null) const [executionChain, setExecutionChain] = useState(null) const [executionLoading, setExecutionLoading] = useState(true) const [executionError, setExecutionError] = useState(null) const [pendingReleaseAction, setPendingReleaseAction] = useState(null) const [releaseActionPhrase, setReleaseActionPhrase] = useState('') const [releaseActionBusy, setReleaseActionBusy] = useState(false) const [releaseActionError, setReleaseActionError] = useState(null) const [releaseActionMessage, setReleaseActionMessage] = useState(null) const [workspace, setWorkspace] = useState(() => { 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 [reviewMessage, setReviewMessage] = useState('') // P0-3 批量审核:逐条其实都由服务端处理,这里只管调用与如实回报。 const handleBatchReview = useCallback( async ( publicationIDs: string[], decision: 'approved' | 'rejected', visibility: Visibility, decisionCode: string ) => { setReviewingId('batch') setBatchError(null) try { const result = await reviewPublicationsBatch(publicationIDs, decision, visibility, decisionCode) const label = decision === 'approved' ? '批准' : '驳回' setReviewMessage( result.skipped > 0 ? `已${label} ${result.decided} 项;${result.skipped} 项当时不可审核(${result.skipped_ids.join('、')})` : `已${label} ${result.decided} 项` ) await loadReviews() } catch (cause) { setBatchError(cause instanceof Error ? cause.message : '批量审核失败') } finally { setReviewingId(null) } }, [loadReviews] ) const handleCreateBatch = useCallback( async (name: string, publicationIDs: string[], deletePublicationIDs: string[]) => { setMutatingBatchId('creating') setBatchError(null) try { // 不传版本 id:服务端在"建批这一下"冻结当前计划(同摘要复用同一版本), // 操作员因此不必先「生成新版本」再「确认冻结」。 // seal=true:建批即锁定(P0-3),草稿态不再单独占一步。 const batch = await createReleaseBatch(name, publicationIDs, deletePublicationIDs, '', true) 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) } }, []) // 页面上的生产动作:点按钮 → 逐字输入固定确认语句 → 提交。服务端同时校验 // 管理员会话、请求门禁与确认语句;Bearer 通道留给运维脚本,行为不变。 const handleStartReleaseAction = useCallback( (kind: ProductionActionKind, id: string, label: string, ids?: string[], deleteIDs?: string[]) => { setPendingReleaseAction({ kind, id, label, publicationIDs: ids, deletePublicationIDs: deleteIDs }) setReleaseActionPhrase('') setReleaseActionError(null) setReleaseActionMessage(null) }, [] ) const handleCancelReleaseAction = useCallback(() => { setPendingReleaseAction(null) setReleaseActionPhrase('') setReleaseActionError(null) }, []) const handleSubmitReleaseAction = useCallback(async () => { if (!pendingReleaseAction) return setReleaseActionBusy(true) setReleaseActionError(null) setReleaseActionMessage(null) try { if (pendingReleaseAction.kind === 'publish_now') { // 名称留空由服务端兜底;这里给一个可读的默认名(确定性内容,重放指纹一致)。 const defaultName = `立即发布 · ${new Date().toLocaleDateString('zh-CN')}` const result = await runPublishNow( pendingReleaseAction.publicationIDs ?? [], pendingReleaseAction.deletePublicationIDs ?? [], defaultName, releaseActionPhrase.trim() ) setReleaseActionMessage( `已受理发布:批次 ${result.batch_name || result.batch_id} · 执行 ${result.execution_id}` ) } else { const summary = await runProductionAction( pendingReleaseAction.kind, pendingReleaseAction.id, releaseActionPhrase.trim() ) setReleaseActionMessage( `${releaseActionLabels[pendingReleaseAction.kind]}已受理:执行 ${summary.id}(${summary.state || 'pending'}) · ${summary.item_count} 项` ) } setPendingReleaseAction(null) setReleaseActionPhrase('') await loadReleaseExecutions() } catch (cause) { setReleaseActionError(cause instanceof Error ? cause.message : '生产操作失败') } finally { setReleaseActionBusy(false) } }, [pendingReleaseAction, releaseActionPhrase, loadReleaseExecutions]) 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 ( setWorkspace((current) => openModule(current, moduleId))} > {workspace.activeTab === 'dashboard' ? ( ) : workspace.activeTab === 'tasks' ? ( ) : workspace.activeTab === 'sources' ? ( ) : workspace.activeTab === 'settings' ? ( ) : workspace.activeTab === 'knowledge' ? ( ) : workspace.activeTab === 'versions' ? ( ) : workspace.activeTab === 'qaops' ? ( ) : ( 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) } onBatchReview={handleBatchReview} reviewBatchMessage={reviewMessage} 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()} pendingReleaseAction={pendingReleaseAction} releaseActionPhrase={releaseActionPhrase} releaseActionBusy={releaseActionBusy} releaseActionError={releaseActionError} releaseActionMessage={releaseActionMessage} onStartReleaseAction={handleStartReleaseAction} onReleaseActionPhrase={setReleaseActionPhrase} onSubmitReleaseAction={() => void handleSubmitReleaseAction()} onCancelReleaseAction={handleCancelReleaseAction} /> )} ) }