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
This commit is contained in:
姚章浩
2026-09-13 22:17:12 +08:00
parent f6cb90cd70
commit 63f3b2c503
38 changed files with 1597 additions and 307 deletions
+62 -97
View File
@@ -6,8 +6,6 @@ import type { KnowledgeProgress, MonitorFilePage, MonitorOverview, MonitorStatus
import { fetchJobFailures, fetchTestPublications, retryPublication, retryPublicationsBatch, startTestPublications } from './testPublications'
import type { JobFailure, ProcessingState, TestPublication, TestPublicationPage } from './testPublications'
import { fetchActiveUISettings, settingsRefreshDelays } from './uiSettings'
import { confirmCatalogChangeSet, fetchCatalogSources, fetchLatestCatalogChangeSet } from './sourceCatalog'
import type { CatalogChangeSetDetail } from './sourceCatalog'
import { WorkspaceContextTabsSetter } from './workspaceContext'
import './weknoraMonitor.css'
@@ -15,15 +13,15 @@ const emptyQueue: TestPublicationPage = { items: [], total: 0, limit: 50, offset
const gb = (value: number) => `${(value / 1073741824).toFixed(1)}`
const scope = (value: string) => value === 'internal' ? '对内' : value === 'external' ? '对外' : '混合'
const duration = (seconds: number) => seconds <= 0 ? '完成' : seconds < 60 ? `${seconds}秒` : seconds < 3600 ? `${Math.floor(seconds / 60)}分钟` : `${(seconds / 3600).toFixed(1)}小时`
const serviceState = (state: string) => state === 'healthy' ? '正常' : state === 'degraded' ? '异常' : state === 'unknown' ? '未接入' : '不可用'
const statusLabels: Record<MonitorStatus, string> = { completed: 'completed', pending: 'pending', processing: 'processing', finalizing: 'finalizing', failed: 'failed', cancelled: 'cancelled' }
const processingLabels: Record<ProcessingState, string> = { pending: '等待解析', processing: '解析中', finalizing: '索引与增强', completed: '成功', failed: '失败', stalled: '停滞' }
const processingLabels: Record<ProcessingState, string> = { planned: '待入库', pending: '等待解析', processing: '解析中', finalizing: '索引与增强', completed: '成功', failed: '失败', stalled: '停滞' }
const secondsSince = (iso: string) => Math.max(0, Math.round((Date.now() - new Date(iso).getTime()) / 1000))
const adviceFor = (stage: string, code: string) => {
if (stage === '文档解析') return '建议先在 WeKnora 手动解析该文件确认格式,再决定是否重试。'
if (stage === '索引 / 增强') return '多为 MinerU 容量或超时问题,确认服务恢复接单后重试。'
if (stage === 'WeKnora 上传') return '上传失败,确认 WeKnora 可达后重试;重复提交不会创建第二份知识。'
if (stage === '源头取件') return '文件尚未从源头取回:钉钉来源需可导出的登录会话,AList/PP 需直连可用;恢复后系统会自动重试。'
if (stage === 'Hash / 文件校验' || stage === 'OSS') return '文件或暂存校验问题,重新入队会重新拉取来源文件。'
if (stage === '测试知识移除') return '移除失败,请先在测试知识库确认该文档当前状态。'
if (stage === '治理策略') return '按治理策略阻止,请先在来源目录修正对内/对外标注。'
@@ -31,25 +29,26 @@ const adviceFor = (stage: string, code: string) => {
return '确认错误码后可直接重试;尝试次数耗尽将进入死信队列。'
}
const pipelineStages = ['下载', 'Hash', 'OSS', '文档解析', 'WeKnora 上传', '索引', '完成']
const pipelineStages = ['源头取件', 'Hash', 'OSS', '文档解析', 'WeKnora 上传', '索引', '完成']
const stageIndex = (label: string) => label === 'Hash / 文件校验' ? 1 : label === 'OSS' ? 2 : label === '文档解析' ? 3 : label === 'WeKnora 上传' ? 4 : label === '索引 / 增强' || label === '测试知识移除' || label === '治理策略' || label === '处理链路' ? 5 : -1
function chainSteps(item: TestPublication) {
const broken = item.processing_state === 'failed' || item.processing_state === 'stalled'
const stopAt = broken ? stageIndex(failureStage(item)) : -1
const activeAt = item.processing_state === 'completed' ? 7 : item.processing_state === 'finalizing' ? 5 : item.processing_state === 'processing' ? 3 : 0
const activeAt = item.processing_state === 'completed' ? 7 : item.processing_state === 'finalizing' ? 5 : item.processing_state === 'processing' ? 3 : item.processing_state === 'planned' && !item.can_start ? 0 : item.processing_state === 'pending' ? 1 : 0
return pipelineStages.map((stage, index) => {
if (stopAt >= 0 && index === stopAt) return { stage, state: 'bad' as const }
if (stopAt >= 0) return { stage, state: index < stopAt ? 'done' as const : 'todo' as const }
if (index < activeAt) return { stage, state: 'done' as const }
if (index === activeAt && item.processing_state !== 'pending' && item.processing_state !== 'completed') return { stage, state: 'active' as const }
if (item.processing_state === 'pending' && index === 0) return { stage, state: 'active' as const }
if (index === activeAt && item.processing_state !== 'pending' && item.processing_state !== 'completed' && item.processing_state !== 'planned') return { stage, state: 'active' as const }
if ((item.processing_state === 'pending' || (item.processing_state === 'planned' && !item.can_start)) && index === 0) return { stage, state: item.can_start || item.processing_state === 'pending' ? 'done' as const : 'active' as const }
return { stage, state: 'todo' as const }
})
}
function failureStage(item: TestPublication) {
const code = item.last_error
if (code.includes('artifact') || code.includes('hash')) return 'Hash / 文件校验'
if (code.includes('artifact') || code.includes('fetch')) return '源头取件'
if (code.includes('hash')) return 'Hash / 文件校验'
if (code.includes('oss')) return 'OSS'
if (code.includes('upload')) return 'WeKnora 上传'
if (code.includes('parse')) return '文档解析'
@@ -64,10 +63,6 @@ interface ViewProps {
files: MonitorFilePage | null
queue?: TestPublicationPage
plans?: TestPublication[]
changeSets?: CatalogChangeSetDetail[]
confirmingSetID?: string | null
confirmMessage?: string
onConfirmChangeSet?: (changeSetID: string, itemSeqs: number[], reason: string) => void
selectedKB: KnowledgeProgress | null
status: MonitorStatus | ''
queueStatus?: ProcessingState | ''
@@ -88,33 +83,20 @@ interface ViewProps {
onLaneChange?: (lane: string) => void
onRetry?: (id: string) => void
onBatchRetry?: (ids: string[]) => void
onStart?: (ids: string[], reason: string) => void
onStart?: (ids: string[]) => void
onRefresh: () => void
}
function ChangeSetCard({changeSet,confirming,message,onConfirm}:{changeSet:CatalogChangeSetDetail;confirming:boolean;message:string;onConfirm?:(changeSetID:string,itemSeqs:number[],reason:string)=>void}){
const [open,setOpen]=useState(false)
const [selected,setSelected]=useState<number[]>([])
const actionable=changeSet.items.filter(item=>item.action!=='no_change')
const confirmable=changeSet.state==='planned'&&actionable.length>0&&Boolean(onConfirm)
const toggle=(seq:number)=>setSelected(current=>current.includes(seq)?current.filter(value=>value!==seq):[...current,seq])
return <article><div><strong>{changeSet.source_name}</strong><small>{new Date(changeSet.created_at).toLocaleString('zh-CN',{hour12:false})}</small>{changeSet.state!=='planned'?<span className="scope-badge internal">已确认</span>:null}</div><div className="persisted-change-counts"><span>新增 {changeSet.add_count}</span><span>更新 {changeSet.update_count}</span><span>移动 {changeSet.move_count}</span><span>范围变化 {changeSet.move_scope_count}</span><span>删除 {changeSet.delete_count}</span><span>未变化 {changeSet.no_change_count}</span></div>{actionable.length?<details open={open} onToggle={event=>setOpen((event.target as HTMLDetailsElement).open)}><summary>预览并选择变更文件</summary><div className="changeset-selection">{actionable.map(item=><label key={item.seq} className="changeset-choice"><input type="checkbox" aria-label={`选择${item.title}`} disabled={!confirmable} checked={selected.includes(item.seq)} onChange={()=>toggle(item.seq)} /><b>{item.action==='add'?'新增':item.action==='update'?'更新':item.action==='move'?'移动(改名)':item.action==='move_scope'?'范围变化':'删除'}</b><span>{item.title}</span><small>{item.new_path||item.old_path}</small>{item.action==='delete'&&item.reason_code==='source_missing'?<small>来源缺失</small>:null}</label>)}</div>{confirmable?<div className="changeset-confirm"><button disabled={confirming||selected.length===0} onClick={()=>onConfirm?.(changeSet.id,[...selected].sort((a,b)=>a-b),'人工确认快照差异执行')}>确认处理({selected.length})</button></div>:null}{message?<p role="status">{message}</p>:null}</details>:null}</article>
}
export function WeKnoraMonitorView({
overview,
files,
queue = emptyQueue,
plans = queue.items,
changeSets = [],
confirmingSetID = null,
confirmMessage = '',
onConfirmChangeSet,
selectedKB,
status,
queueStatus = '',
queueScope = '',
lane = 'attention',
lane = 'waiting',
onLaneChange = () => undefined,
loading,
error,
@@ -133,8 +115,9 @@ export function WeKnoraMonitorView({
onStart = () => undefined,
onRefresh,
}: ViewProps) {
const [startReason, setStartReason] = useState('已核对来源快照与测试知识库差异')
const [selectedRetryIDs, setSelectedRetryIDs] = useState<string[]>([])
const [selectedStartIDs, setSelectedStartIDs] = useState<string[]>([])
const [selectedRetryIDs, setSelectedRetryIDs] = useState<string[]>([])
const toggleStartSelection = (id: string) => setSelectedStartIDs((current) => current.includes(id) ? current.filter((value) => value !== id) : [...current, id])
const toggleRetrySelection = (id: string) => setSelectedRetryIDs((current) => current.includes(id) ? current.filter((value) => value !== id) : [...current, id])
const stages: Array<[MonitorStatus, number]> = selectedKB ? [
['completed', selectedKB.completed], ['pending', selectedKB.pending], ['finalizing', selectedKB.finalizing],
@@ -146,65 +129,73 @@ export function WeKnoraMonitorView({
}), [queue.items])
const retryableIDs = queue.items.filter((item) => item.can_retry).map((item) => item.id)
const batchTargets = selectedRetryIDs.length ? retryableIDs.filter((id) => selectedRetryIDs.includes(id)) : retryableIDs
const pendingPlans = plans.filter((item) => item.can_start)
const addedPlans = pendingPlans.filter((item) => item.change_type === 'added').length
const updatedPlans = pendingPlans.filter((item) => item.change_type === 'updated').length
const startablePlans = plans.filter((item) => item.can_start)
const startTargets = selectedStartIDs.length ? startablePlans.filter((item) => selectedStartIDs.includes(item.id)).map((item) => item.id) : startablePlans.map((item) => item.id)
const attentionItems = queue.items.filter((item) => item.processing_state === 'failed' || item.processing_state === 'stalled')
const inflightItems = queue.items.filter((item) => item.processing_state === 'processing' || item.processing_state === 'finalizing' || (item.processing_state === 'pending' && !item.can_start))
const doneTodayItems = queue.items.filter((item) => item.processing_state === 'completed')
const waitingItems = queue.items.filter((item) => item.processing_state === 'pending' && !item.can_start)
const laneCounts: Record<string, number> = { attention: attentionItems.length + failures.length, changes: changeSets.filter((set) => set.state === 'planned').length, inflight: inflightItems.length, pending: waitingItems.length, done: doneTodayItems.length, queue: queue.total }
const queueFiltered = waitingItems
const queueFilteredAll = orderedQueue
const doneItems = queue.items.filter((item) => item.processing_state === 'completed')
const plannedItems = queue.items.filter((item) => item.processing_state === 'planned')
const fetchingPlanned = plannedItems.filter((item) => !item.can_start)
const laneCounts: Record<string, number> = {
waiting: startablePlans.length + fetchingPlanned.length,
attention: attentionItems.length + failures.length,
removal: (overview?.knowledge_bases || []).reduce((total, kb) => total + (kb.needs_removal || 0), 0),
inflight: inflightItems.length,
done: doneItems.length,
queue: queue.total,
}
const laneTitles: Record<string, string> = { waiting: '待入库', attention: '需人工处理', removal: '需下架', inflight: '处理中', done: '已完成', queue: '全部任务' }
const actionTask = (item: TestPublication) => <article className="inbox-task" key={item.id}>
<div className="inbox-task-mark">{item.can_retry ? <input type="checkbox" aria-label={`选择重试${item.title}`} checked={selectedRetryIDs.includes(item.id)} onChange={() => toggleRetrySelection(item.id)} /> : null}</div>
<div className="inbox-task-mark">{item.can_start ? <input type="checkbox" aria-label={`选择入库${item.title}`} checked={selectedStartIDs.length === 0 || selectedStartIDs.includes(item.id)} onChange={() => toggleStartSelection(item.id)} /> : item.can_retry ? <input type="checkbox" aria-label={`选择重试${item.title}`} checked={selectedRetryIDs.includes(item.id)} onChange={() => toggleRetrySelection(item.id)} /> : null}</div>
<div>
<h4>{item.title} <span className={`scope-badge ${item.target_scope}`}>{scope(item.target_scope)}</span> {item.change_type === 'added' ? <span className="task-badge add">新增</span> : item.change_type === 'updated' ? <span className="task-badge update">更新</span> : null}</h4>
<div className="why">{item.processing_state === 'failed' || item.processing_state === 'stalled' ? <>{item.processing_state === 'stalled' ? '任务停滞:' : '为什么失败:'}错误码 <code>{item.last_error || '—'}</code> · 第{item.retry_count + 1}次尝试 · 已停留{duration(secondsSince(item.updated_at))} · 失败阶段 {failureStage(item)}</> : <>状态 <code>{item.can_start ? '等待人工确认' : processingLabels[item.processing_state]}</code>{item.last_error ? <> · 最近错误 <code>{item.last_error}</code></> : null} · 已停留{duration(secondsSince(item.updated_at))}</>}</div>
<div className="why">{item.processing_state === 'failed' || item.processing_state === 'stalled' ? <>{item.processing_state === 'stalled' ? '任务停滞:' : '为什么失败:'}错误码 <code>{item.last_error || '—'}</code> · 第{item.retry_count + 1}次尝试 · 已停留{duration(secondsSince(item.updated_at))} · 失败阶段 {failureStage(item)}</> : <>状态 <code>{processingLabels[item.processing_state]}</code>{item.last_error ? <> · 最近错误 <code>{item.last_error}</code></> : null} · 已停留{duration(secondsSince(item.updated_at))}</>}</div>
<div className="task-chain" aria-label={`处理链${item.title}`}>{chainSteps(item).map((step) => <span key={step.stage} className={`chain-step ${step.state}`}>{step.stage}{step.state === 'done' ? ' ✓' : step.state === 'bad' ? ' ✗' : step.state === 'active' ? ` 中 ${duration(secondsSince(item.updated_at))}` : ''}</span>)}</div>
<div className={item.processing_state === 'failed' || item.processing_state === 'stalled' ? 'errline' : 'tiny muted-line'}>{item.processing_state === 'failed' || item.processing_state === 'stalled' ? adviceFor(failureStage(item), item.last_error) : item.can_start ? '确认后将创建解析任务' : '无需操作,等待自动处理'}{item.change_set_id ? <> · 来源变更集 <code>{item.change_set_id}</code></> : null} · <code>{item.id}</code></div>
<div className={item.processing_state === 'failed' || item.processing_state === 'stalled' ? 'errline' : 'tiny muted-line'}>{item.processing_state === 'failed' || item.processing_state === 'stalled' ? adviceFor(failureStage(item), item.last_error) : item.processing_state === 'planned' && !item.can_start ? '正在从源头取回文件,完成后自动进入可处理状态' : item.can_start ? '文件已就绪,等待开始处理' : '无需操作,等待自动处理'} · <code>{item.id}</code></div>
</div>
<div className="inbox-task-actions">{item.can_start ? <button className="primary" disabled={starting || !startReason.trim()} onClick={() => onStart([item.id], startReason.trim())}>确认并解析</button> : null}{item.can_retry ? <button className="primary" disabled={retryingIDs.includes(item.id)} onClick={() => onRetry(item.id)}>{retryingIDs.includes(item.id) ? '重试中…' : '重试'}</button> : null}</div>
<div className="inbox-task-actions">{item.can_retry ? <button className="primary" disabled={retryingIDs.includes(item.id)} onClick={() => onRetry(item.id)}>{retryingIDs.includes(item.id) ? '重试中…' : '重试'}</button> : null}</div>
</article>
const emptyLane = (text: string) => <div className="empty-state">{text}</div>
return <main className="page-shell weknora-monitor inbox-layout">
<header className="hero compact"><div><h1>解析监控</h1><p className="subtitle">今天需要我做什么,一目了然;处理链进度、失败原因与建议直接摆在任务卡片上。</p></div><span className="monitor-meta">{overview ? `快照 ${new Date(overview.observed_at).toLocaleString('zh-CN', { hour12: false })}` : ''} · 队列 等待{queue.total}条</span><button onClick={onRefresh} disabled={loading}>{loading ? '刷新中…' : '刷新'}</button></header>
<header className="hero compact"><div><h1>解析监控</h1><p className="subtitle">站在知识库视角看差异:来源与目录里标好的对内/对外文件应不应该在这里,还差哪一步,一目了然。</p></div><span className="monitor-meta">{overview ? `快照 ${new Date(overview.observed_at).toLocaleString('zh-CN', { hour12: false })}` : ''} · 队列 等待{queue.total}条{overview?.pipeline ? ` · 取件中 ${overview.pipeline.fetch_pending}${overview.pipeline.fetch_failed ? ` · 取件失败 ${overview.pipeline.fetch_failed}` : ''}` : ''}</span><button onClick={onRefresh} disabled={loading}>{loading ? '刷新中…' : '刷新'}</button></header>
{error ? <div className="error-banner" role="alert">{error}</div> : null}
{overview?.simulated ? <div className="simulation-banner"><strong>本地模拟数据</strong><span>资源和知识库汇总用于确认页面流程,不代表测试服务器真实数据;任务卡片来自真实治理 API。</span></div> : null}
<div className="inbox-grid">
<nav className="inbox-nav" aria-label="解析监控收件箱">
<h2>今天需要我做什么</h2>
{[['attention', '需人工处理', 'blocked'], ['changes', '等待我确认的差异', ''], ['inflight', '处理中', ''], ['pending', '排队等待', ''], ['done', '已完成', 'okall']].map(([value, label, tone]) => <button key={value} className={`${lane === value ? 'active' : ''} ${laneCounts[value] ? tone : ''}`} aria-label={`切换到${label}`} onClick={() => onLaneChange(value)}><span>{label}</span><em className="lane-count">{laneCounts[value]}</em></button>)}
<h2>知识库差异</h2>
{[['waiting', '待入库', 'blocked'], ['attention', '需人工处理', ''], ['removal', '需下架', ''], ['inflight', '处理中', ''], ['done', '已完成', 'okall']].map(([value, label, tone]) => <button key={value} className={`${lane === value ? 'active' : ''} ${laneCounts[value] ? tone : ''}`} aria-label={`切换到${label}`} onClick={() => onLaneChange(value)}><span>{label}</span><em className="lane-count">{laneCounts[value]}</em></button>)}
<button className={`${lane === 'queue' ? 'active' : ''}`} aria-label="切换到全部任务" onClick={() => onLaneChange('queue')}><span>全部任务</span><em className="lane-count">{queue.total}</em></button>
</nav>
<div className="inbox-work">
{lane === 'waiting' ? <section className="inbox-section" aria-label="待入库">
<div className="section-head"><h2>待入库({startablePlans.length + fetchingPlanned.length})</h2><span className="spacer" /><button className="primary" disabled={starting || !startTargets.length} onClick={() => onStart(startTargets)}>{starting ? '正在生成任务…' : `开始处理(${startTargets.length})`}</button></div>
<p className="tiny">来源目录中标记对内/对外的文件会自动出现在这里;“开始处理”按系统设置的并发上限(当前 {overview?.pipeline?.concurrency ?? 2})创建解析任务,无需再确认。</p>
{startMessage ? <p className="difference-message" role="status">{startMessage}</p> : null}
{plannedItems.length ? plannedItems.map(actionTask) : emptyLane('还没有标记入库的文件。去“来源与目录”把文件或目录标为对内/对外即可。')}
{fetchingPlanned.length ? <p className="tiny">其中 {fetchingPlanned.length} 项仍在从源头取件,取回后自动可处理。</p> : null}
</section> : null}
{lane === 'attention' ? <section className="inbox-section" aria-label="需人工处理">
<div className="section-head"><h2>需要你出手({attentionItems.length})</h2><span className="spacer" /><button className="danger" disabled={!batchTargets.length || retryingIDs.length > 0} onClick={() => onBatchRetry(batchTargets)}>{retryingIDs.length ? '重试中…' : `批量重试所选(${batchTargets.length})`}</button></div>
{batchMessage ? <p className="queue-batch-message" role="status">{batchMessage}</p> : null}
{attentionItems.length ? attentionItems.map(actionTask) : emptyLane('没有失败或停滞的任务。')}
<div className="section-head sub"><h3>死信(尝试耗尽,不可自动重试)</h3><span className="tiny">原始任务与审计行保留不动;重新入队会创建新尝试</span></div>
{failures.length ? <ul className="dlq-list">{failures.map((failure) => <li key={failure.id}><span className="monitor-status failed">{failure.error_code}</span><b>{failure.job_type === 'test.upload' ? '上传解析' : failure.job_type}</b>{failure.publication_id ? <code>{failure.publication_id}</code> : null}<small>{failure.attempt}/{failure.max_attempts_at_failure} 次 · {new Date(failure.created_at).toLocaleString('zh-CN', { hour12: false })}</small>{failure.publication_id ? <button disabled={retryingIDs.includes(failure.publication_id)} onClick={() => onBatchRetry([failure.publication_id as string])}>重新入队</button> : null}</li>)}</ul> : emptyLane('当前没有等待处理的死信记录。')}
{failures.length ? <ul className="dlq-list">{failures.map((failure) => <li key={failure.id}><span className="monitor-status failed">{failure.error_code}</span><b>{failure.job_type === 'test.upload' ? '上传解析' : failure.job_type === 'artifact.fetch' ? '源头取件' : failure.job_type}</b>{failure.publication_id ? <code>{failure.publication_id}</code> : null}<small>{failure.attempt}/{failure.max_attempts_at_failure} 次 · {new Date(failure.created_at).toLocaleString('zh-CN', { hour12: false })}</small>{failure.publication_id ? <button disabled={retryingIDs.includes(failure.publication_id)} onClick={() => onBatchRetry([failure.publication_id as string])}>重新入队</button> : null}</li>)}</ul> : emptyLane('当前没有等待处理的死信记录。')}
</section> : null}
{lane === 'changes' ? <section className="inbox-section" aria-label="等待确认的差异">
<div className="section-head"><h2>持久快照差异 · 等待确认({changeSets.filter((set) => set.state === 'planned').length} 个来源)</h2><span className="tiny">刷新来源 ≠ 马上导入知识库;勾选变更项并确认后才创建解析任务</span></div>
{changeSets.length ? <div className="persisted-change-grid">{changeSets.map(changeSet => <ChangeSetCard key={changeSet.id} changeSet={changeSet} confirming={confirmingSetID === changeSet.id} message={confirmingSetID === changeSet.id ? confirmMessage : ''} onConfirm={onConfirmChangeSet} />)}</div> : emptyLane('当前没有持久快照差异。')}
<div className="difference-confirmation">
<label>确认原因<input value={startReason} onChange={(event) => setStartReason(event.target.value)} /></label>
<button disabled={starting || !pendingPlans.length || !startReason.trim()} onClick={() => onStart(pendingPlans.map((item) => item.id), startReason.trim())}>{starting ? '正在生成任务…' : `开始处理(${pendingPlans.length})`}</button>
</div>
<p className="tiny">待确认 {pendingPlans.length} · 新增 {addedPlans} · 更新 {updatedPlans}</p>
{startMessage ? <p className="difference-message" role="status">{startMessage}</p> : null}
{lane === 'removal' ? <section className="inbox-section" aria-label="需下架">
<div className="section-head"><h2>需下架({laneCounts.removal})</h2><span className="tiny">来源目录里被改为“禁止导入”或撤销标注、但仍在知识库中可检索的文件</span></div>
{(overview?.knowledge_bases || []).some((kb) => kb.needs_removal > 0) ? <ul className="dlq-list">{(overview?.knowledge_bases || []).filter((kb) => kb.needs_removal > 0).map((kb) => <li key={kb.id}><span className="monitor-status failed">需下架</span><b>{kb.name}</b><small>{kb.needs_removal} 份仍在检索中</small></li>)}</ul> : emptyLane('没有标注为禁止但仍留在知识库里的文件。')}
<p className="tiny">下架在“知识清单”里操作(停用检索,可恢复);这里只负责把差异暴露出来。</p>
</section> : null}
{lane === 'inflight' ? <section className="inbox-section" aria-label="处理中">
<div className="section-head"><h2>处理中({inflightItems.length})</h2><span className="tiny">无需操作,仅供查看</span></div>
{inflightItems.length ? inflightItems.map(actionTask) : emptyLane('当前没有正在处理或索引增强的任务。')}
{overview ? <>
<div className="pipeline-strip" aria-label="解析处理链">下载 → Hash → OSS → 文档解析 → WeKnora 上传 → 索引 → 完成</div>
<div className="pipeline-strip" aria-label="解析处理链">源头取件 → Hash → OSS → 文档解析 → WeKnora 上传 → 索引 → 完成</div>
<div className="monitor-kb-layout" id="monitor-kb-progress">
<aside className="monitor-kb-list"><h2>知识库解析进度</h2>{overview.knowledge_bases.map((kb) => <button key={kb.id} className={selectedKB?.id === kb.id ? 'active' : ''} onClick={() => onSelectKB(kb)}><span><b>{kb.name}</b><small>{scope(kb.visibility)} · 已导入 {kb.imported}</small></span><strong>{kb.completed}完成</strong></button>)}</aside>
<aside className="monitor-kb-list"><h2>知识库解析进度</h2>{overview.knowledge_bases.map((kb) => <button key={kb.id} className={selectedKB?.id === kb.id ? 'active' : ''} onClick={() => onSelectKB(kb)}><span><b>{kb.name}</b><small>{scope(kb.visibility)} · 已导入 {kb.imported}{kb.planned ? ` · 待入库 ${kb.planned}` : ''}</small></span><strong>{kb.completed}完成</strong></button>)}</aside>
<div className="monitor-kb-detail">{selectedKB ? <>
<div className="monitor-kb-heading"><div><h2>{selectedKB.name}</h2><span>{scope(selectedKB.visibility)} · 已导入 {selectedKB.imported}</span></div><div><span>对内 {selectedKB.internal_completed} / {selectedKB.internal_imported}</span><span>对外 {selectedKB.external_completed} / {selectedKB.external_imported}</span></div></div>
<div className="monitor-kb-heading"><div><h2>{selectedKB.name}</h2><span>{scope(selectedKB.visibility)} · 已导入 {selectedKB.imported}{selectedKB.planned ? ` · 待入库 ${selectedKB.planned}` : ''}</span></div><div><span>对内 {selectedKB.internal_completed} / {selectedKB.internal_imported}</span><span>对外 {selectedKB.external_completed} / {selectedKB.external_imported}</span></div></div>
<div className="monitor-stage-tabs"><button className={status === '' ? 'active' : ''} onClick={() => onStatus('')}>全部 {selectedKB.imported}</button>{stages.filter(([, count]) => count > 0).map(([value, count]) => <button className={status === value ? 'active' : ''} key={value} onClick={() => onStatus(value)}>{statusLabels[value]} {count}</button>)}</div>
<p className="finalizing-note"><b>finalizing:</b>基础解析、切片和向量通常已完成,Wiki、摘要或图谱仍在生成;不能算全部完成。</p>
{files?.sample_only ? <p className="sample-note">当前只展示本地模拟文件样例;真实模式会列出所选状态下的实际文件。</p> : null}
@@ -213,17 +204,13 @@ export function WeKnoraMonitorView({
</div>
</> : null}
</section> : null}
{lane === 'pending' ? <section className="inbox-section" aria-label="排队等待">
<div className="section-head"><h2>排队等待({queueFiltered.length})</h2><span className="spacer" /><label>目标知识库<select aria-label="队列目标知识库" value={queueScope} onChange={(event) => onQueueScope(event.target.value as 'internal' | 'external' | '')}><option value="">内/外全部</option><option value="internal">对内知识库</option><option value="external">对外知识库</option></select></label></div>
{queueFiltered.length ? queueFiltered.map(actionTask) : emptyLane('当前筛选没有排队任务。')}
</section> : null}
{lane === 'done' ? <section className="inbox-section" aria-label="已完成">
<div className="section-head"><h2>已完成({doneTodayItems.length})</h2><span className="tiny">最近一页数据中的成功任务</span></div>
{doneTodayItems.length ? doneTodayItems.map(actionTask) : emptyLane('当前页没有已完成任务;用全部任务视图翻页查看。')}
<div className="section-head"><h2>已完成({doneItems.length})</h2><span className="tiny">最近一页数据中的成功任务</span></div>
{doneItems.length ? doneItems.map(actionTask) : emptyLane('当前页没有已完成任务;用全部任务视图翻页查看。')}
</section> : null}
{lane === 'queue' ? <section className="inbox-section" aria-label="全部任务">
<div className="section-head"><h2>全部任务({queue.total})</h2><span className="spacer" /><label>目标知识库<select aria-label="队列目标知识库" value={queueScope} onChange={(event) => onQueueScope(event.target.value as 'internal' | 'external' | '')}><option value="">内/外全部</option><option value="internal">对内知识库</option><option value="external">对外知识库</option></select><select aria-label="队列状态" value={queueStatus} onChange={(event) => onQueueStatus(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>
{queueFilteredAll.length ? queueFilteredAll.map(actionTask) : !loading ? emptyLane('当前筛选没有解析任务。') : null}
<div className="section-head"><h2>全部任务({queue.total})</h2><span className="spacer" /><label>目标知识库<select aria-label="队列目标知识库" value={queueScope} onChange={(event) => onQueueScope(event.target.value as 'internal' | 'external' | '')}><option value="">内/外全部</option><option value="internal">对内知识库</option><option value="external">对外知识库</option></select><select aria-label="队列状态" value={queueStatus} onChange={(event) => onQueueStatus(event.target.value as ProcessingState | '')}><option value="">全部状态</option><option value="planned">待入库</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>
{orderedQueue.length ? orderedQueue.map(actionTask) : !loading ? emptyLane('当前筛选没有解析任务。') : null}
</section> : null}
{metrics ? <footer className="monitor-strip" aria-label="真实运行指标"><div>1小时·成功 <b className={metrics.short_window.failure_rate !== null && metrics.short_window.failure_rate > 5 ? 'bad' : 'good'}>{metrics.short_window.success_rate === null ? '数据不足' : `${metrics.short_window.success_rate}%`}</b></div><div>24小时·成功 <b>{metrics.long_window.success_rate === null ? '数据不足' : `${metrics.long_window.success_rate}%`}</b></div><div>p50 {metrics.short_window.duration_p50_seconds === null ? '—' : duration(Math.round(metrics.short_window.duration_p50_seconds))} · p95 {metrics.short_window.duration_p95_seconds === null ? '—' : duration(Math.round(metrics.short_window.duration_p95_seconds))}</div><div>Worker {metrics.active_workers} · 等待 {metrics.queue.pending} · 运行 {metrics.queue.running}{metrics.queue.failed ? <span className="bad"> · 失败 {metrics.queue.failed}</span> : null}</div>{overview?.health.map((service) => <div key={service.key}>{service.name} <b className={service.readiness === 'ready' ? 'good' : service.readiness === 'blocked' || service.readiness === 'down' ? 'bad' : ''}>{service.readiness === 'ready' ? '可接单' : service.readiness === 'degraded' ? '降级' : service.readiness === 'not_configured' ? '未配置' : service.readiness === 'down' ? '不可达' : '阻断'}</b></div>)}{overview ? <div>CPU {overview.host.cpu_percent.toFixed(0)}% · 内存 {gb(overview.host.memory_used_bytes)}/{gb(overview.host.memory_total_bytes)}GB</div> : null}</footer> : null}
</div>
@@ -237,14 +224,10 @@ export function WeKnoraMonitor() {
const [files, setFiles] = useState<MonitorFilePage | null>(null)
const [queue, setQueue] = useState<TestPublicationPage>(emptyQueue)
const [plans, setPlans] = useState<TestPublication[]>([])
const [changeSets, setChangeSets] = useState<CatalogChangeSetDetail[]>([])
const [confirmingSetID, setConfirmingSetID] = useState<string | null>(null)
const [lastConfirmSetID, setLastConfirmSetID] = useState<string | null>(null)
const [confirmMessage, setConfirmMessage] = useState('')
const [status, setStatus] = useState<MonitorStatus | ''>('')
const [queueStatus, setQueueStatus] = useState<ProcessingState | ''>('')
const [queueScope, setQueueScope] = useState<'internal' | 'external' | ''>('')
const [lane, setLane] = useState<'attention' | 'changes' | 'inflight' | 'pending' | 'done' | 'queue'>('attention')
const [lane, setLane] = useState<'waiting' | 'attention' | 'removal' | 'inflight' | 'done' | 'queue'>('waiting')
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [documentRevision, setDocumentRevision] = useState(0)
@@ -283,13 +266,9 @@ export function WeKnoraMonitor() {
const controller = new AbortController(); setLoading(true)
void Promise.all([
fetchTestPublications({ processing_state: queueStatus, target_scope: queueScope, limit: 50, offset: 0 }, controller.signal),
fetchTestPublications({ processing_state: 'pending', limit: 100, offset: 0 }, controller.signal),
fetchCatalogSources(controller.signal).then(async sources => {
const results=await Promise.allSettled(sources.map(source=>fetchLatestCatalogChangeSet(source.connection_id,'',20,0,controller.signal)))
return results.flatMap(result=>result.status==='fulfilled'?[result.value]:[])
}),
]).then(([queuePage, planPage, latestChangeSets]) => {
if (!controller.signal.aborted) { setQueue(queuePage); setPlans(planPage.items.filter((item) => item.can_start)); setChangeSets(latestChangeSets); setError(null) }
fetchTestPublications({ processing_state: 'planned', limit: 100, offset: 0 }, controller.signal),
]).then(([queuePage, planPage]) => {
if (!controller.signal.aborted) { setQueue(queuePage); setPlans(planPage.items); setError(null) }
}).catch((cause) => { if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载解析队列失败') }).finally(() => { if (!controller.signal.aborted) setLoading(false) })
return () => controller.abort()
}, [queueStatus, queueScope, documentRevision])
@@ -360,12 +339,12 @@ export function WeKnoraMonitor() {
}
}
const startPlans = async (ids: string[], reason: string) => {
const startPlans = async (ids: string[]) => {
setStarting(true)
setStartMessage('')
try {
const result = await startTestPublications(ids, reason)
setStartMessage(`已确认 ${result.selected} 项;新建解析任务 ${result.started} 项;已开始 ${result.already_started} 项;不可处理 ${result.unavailable} 项。`)
const result = await startTestPublications(ids, '开始处理')
setStartMessage(`已提交 ${result.selected} 项;新建解析任务 ${result.started} 项;已在队列 ${result.already_started} 项;不可处理 ${result.unavailable} 项(多为源头取件未完成,稍后自动重试)。`)
setError(null)
setDocumentRevision((value) => value + 1)
} catch (cause) {
@@ -374,19 +353,5 @@ export function WeKnoraMonitor() {
setStarting(false)
}
}
const confirmChangeSet = async (changeSetID: string, itemSeqs: number[], reason: string) => {
if (confirmingSetID) return
setConfirmingSetID(changeSetID); setLastConfirmSetID(changeSetID); setConfirmMessage('')
try {
const {result,operation} = await confirmCatalogChangeSet(changeSetID, itemSeqs, reason)
setConfirmMessage(`已${operation==='replayed'?'沿用上次结果':'提交'}:确认 ${result.confirmed_items} 项;新建上传任务 ${result.uploads_created} 个;已有任务 ${result.uploads_existing} 个;请求移除 ${result.removals_requested} 份;内容未就绪 ${result.skipped_no_artifact} 份;缺少目标知识库 ${result.skipped_no_target} 份;未变化 ${result.no_change_ignored} 项已忽略。`)
setDocumentRevision((value) => value + 1)
} catch (cause) {
setConfirmMessage(cause instanceof Error ? cause.message : '确认快照差异失败')
} finally {
setConfirmingSetID(null)
}
}
return <WeKnoraMonitorView overview={overview} files={files} queue={queue} plans={plans} changeSets={changeSets} confirmingSetID={confirmingSetID ?? lastConfirmSetID} confirmMessage={confirmMessage} onConfirmChangeSet={(id,seqs,reason)=>void confirmChangeSet(id,seqs,reason)} selectedKB={selected} status={status} queueStatus={queueStatus} queueScope={queueScope} loading={loading} error={error} retryingIDs={retryingIDs} starting={starting} startMessage={startMessage} batchMessage={batchMessage} failures={failures} metrics={metrics} onSelectKB={(kb) => { setSelected(kb); setStatus(''); setFiles(null) }} onStatus={(value) => { setStatus(value); setFiles(null) }} onQueueStatus={setQueueStatus} onQueueScope={setQueueScope} lane={lane} onLaneChange={(value) => setLane(value as typeof lane)} onRetry={(id) => void retryOne(id)} onBatchRetry={(ids) => void retryBatch(ids)} onStart={(ids, reason) => void startPlans(ids, reason)} onRefresh={() => { setDocumentRevision((value) => value + 1); setResourceRevision((value) => value + 1) }} />
}
return <WeKnoraMonitorView overview={overview} files={files} queue={queue} plans={plans} selectedKB={selected} status={status} queueStatus={queueStatus} queueScope={queueScope} loading={loading} error={error} retryingIDs={retryingIDs} starting={starting} startMessage={startMessage} batchMessage={batchMessage} failures={failures} metrics={metrics} onSelectKB={(kb) => { setSelected(kb); setStatus(''); setFiles(null) }} onStatus={(value) => { setStatus(value); setFiles(null) }} onQueueStatus={setQueueStatus} onQueueScope={setQueueScope} lane={lane} onLaneChange={(value) => setLane(value as typeof lane)} onRetry={(id) => void retryOne(id)} onBatchRetry={(ids) => void retryBatch(ids)} onStart={(ids) => void startPlans(ids)} onRefresh={() => { setDocumentRevision((value) => value + 1); setResourceRevision((value) => value + 1) }} />
}