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
+1
View File
@@ -607,6 +607,7 @@ export function JobDashboard({ jobs, loading, error, onRefresh }: JobDashboardPr
}
const processingLabels: Record<ProcessingState, string> = {
planned: '待入库',
pending: '待处理',
processing: '解析中',
finalizing: '定稿中',
+1 -1
View File
@@ -8,7 +8,7 @@ import type { SourceConnectionListItem } from './sourceConnections'
const monitor:MonitorOverview={mode:'simulation',simulated:true,observed_at:'2026-09-08T12:00:00Z',host:{cpu_percent:42,memory_used_bytes:1,memory_total_bytes:2,disk_used_bytes:1,disk_total_bytes:2,gpu_state:'unknown',gpu_detail:'未接入真实GPU监控',simulated:true},services:[{key:'mineru',name:'MinerU',state:'healthy',detail:'模拟',latency_ms:1,observed_at:'2026-09-08T12:00:00Z',simulated:true}],knowledge_bases:[],health:[{key:'mineru',name:'MinerU',liveness:'up',readiness:'blocked',reason:'服务可达但容量已满(429),暂时不可接单',latency_ms:30,observed_at:'2026-09-08T12:00:00Z',last_success_at:'2026-09-08T11:59:00Z',consecutive_failures:2,configured:true,applicable:true}]}
const sources:CatalogSource[]=[{connection_id:'ding-1',source_type:'dingtalk',name:'公司级技术支持知识库',root_node_id:'root-1',folder_count:1079,file_count:3444,observed_at:'2026-09-09T09:30:32Z',snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:0}]
const connections:SourceConnectionListItem[]=[{id:'conn-ding',source_type:'dingtalk',name:'公司级技术支持知识库',enabled:true,schedule_configured:true,health_status:'healthy',item_count:3444,updated_at:'2026-09-09T09:30:32Z',next_refresh_at:'2026-09-12T10:00:00Z'},{id:'conn-man',source_type:'manual',name:'本地手工验收',enabled:false,schedule_configured:false,health_status:'unknown',item_count:5,updated_at:'2026-09-09T09:30:32Z',next_refresh_at:null}]
const settings:UISettings={id:'settings-default',state:'active',document_refresh_seconds:15,resource_refresh_seconds:30,stalled_after_seconds:1800,finalizing_after_seconds:7200,updated_by:'system:migration',created_at:'2026-09-10T08:00:00Z',activated_at:'2026-09-10T08:00:00Z',retired_at:null,error_code:''}
const settings:UISettings={id:'settings-default',state:'active',document_refresh_seconds:15,resource_refresh_seconds:30,stalled_after_seconds:1800,finalizing_after_seconds:7200,ingestion_concurrency:2,updated_by:'system:migration',created_at:'2026-09-10T08:00:00Z',activated_at:'2026-09-10T08:00:00Z',retired_at:null,error_code:''}
describe('SystemSettingsView',()=>{
it('separates document-engineer settings from locked administrator and production controls',()=>{
const html=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时" onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} />)
+6 -3
View File
@@ -138,6 +138,7 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr
const [resourceRefresh, setResourceRefresh] = useState<30 | 60>(settings?.resource_refresh_seconds ?? 30)
const [stalled, setStalled] = useState<1800 | 3600>(settings?.stalled_after_seconds ?? 1800)
const [finalizing, setFinalizing] = useState<7200 | 14400>(settings?.finalizing_after_seconds ?? 7200)
const [concurrency, setConcurrency] = useState<number>(settings?.ingestion_concurrency ?? 2)
const [dirty, setDirty] = useState(false)
useEffect(() => {
@@ -146,6 +147,7 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr
setResourceRefresh(settings.resource_refresh_seconds)
setStalled(settings.stalled_after_seconds)
setFinalizing(settings.finalizing_after_seconds)
setConcurrency(settings.ingestion_concurrency)
setDirty(false)
}, [settings])
@@ -183,10 +185,11 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr
<label>资源刷新间隔<select value={resourceRefresh} onChange={(event) => { setResourceRefresh(Number(event.target.value) as 30 | 60); setDirty(true) }}><option value={30}>30秒</option><option value={60}>1分钟</option></select></label>
<label>解析停滞判定<select value={stalled} onChange={(event) => { setStalled(Number(event.target.value) as 1800 | 3600); setDirty(true) }}><option value={1800}>30分钟</option><option value={3600}>1小时</option></select></label>
<label>finalizing 告警<select value={finalizing} onChange={(event) => { setFinalizing(Number(event.target.value) as 7200 | 14400); setDirty(true) }}><option value={7200}>2小时</option><option value={14400}>4小时</option></select></label>
<label>入库并发上限<select value={concurrency} onChange={(event) => { setConcurrency(Number(event.target.value)); setDirty(true) }}><option value={1}>1(谨慎,MinerU 并发 1)</option><option value={2}>2</option><option value={3}>3</option><option value={4}>4</option><option value={6}>6</option><option value={8}>8</option></select></label>
</div>
<button onClick={() => { setDirty(false); onSave({ document_refresh_seconds: documentRefresh, resource_refresh_seconds: resourceRefresh, stalled_after_seconds: stalled, finalizing_after_seconds: finalizing }) }} disabled={!canSave}>{saving ? '正在验证并应用…' : '保存并应用刷新与告警参数'}</button>
<button onClick={() => { setDirty(false); onSave({ document_refresh_seconds: documentRefresh, resource_refresh_seconds: resourceRefresh, stalled_after_seconds: stalled, finalizing_after_seconds: finalizing, ingestion_concurrency: concurrency }) }} disabled={!canSave}>{saving ? '正在验证并应用…' : '保存并应用刷新与告警参数'}</button>
{visibleSaveMessage(saveMessage, dirty) ? <p className="success-message" role="status">{saveMessage}</p> : null}
<small>当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源 {secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)}、finalizing {secondsLabel(settings.finalizing_after_seconds)}。</small>
<small>当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源 {secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)}、finalizing {secondsLabel(settings.finalizing_after_seconds)}、入库并发 {settings.ingestion_concurrency}。</small>
</section> : null}
</div>
</div> : null}
@@ -214,7 +217,7 @@ export function SystemSettings() {
const save = async (input: UISettingsCandidateInput) => {
setSaving(true); setSaveMessage(null); setError(null)
try { const candidate = await createUISettingsCandidate(input); const active = await activateUISettings(candidate.id); setSettings(active); setSaveMessage(`刷新与告警参数已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${secondsLabel(active.stalled_after_seconds)}、finalizing ${secondsLabel(active.finalizing_after_seconds)};旧版本已保留用于审计。`) }
try { const candidate = await createUISettingsCandidate(input); const active = await activateUISettings(candidate.id); setSettings(active); setSaveMessage(`刷新与告警参数已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${secondsLabel(active.stalled_after_seconds)}、finalizing ${secondsLabel(active.finalizing_after_seconds)}、入库并发 ${active.ingestion_concurrency};旧版本已保留用于审计。`) }
catch (cause) { setError(cause instanceof Error ? cause.message : '保存系统设置失败') }
finally { setSaving(false) }
}
+22 -31
View File
@@ -3,15 +3,13 @@ import { describe,expect,it,vi } from 'vitest'
import { WeKnoraMonitorView } from './WeKnoraMonitor'
import type { MonitorFilePage,MonitorOverview,RunMetrics } from './monitor'
import type { TestPublicationPage } from './testPublications'
import type { CatalogChangeSetDetail } from './sourceCatalog'
const overview:MonitorOverview={mode:'simulation',simulated:true,observed_at:'2026-09-08T12:00:00Z',host:{cpu_percent:42,memory_used_bytes:19971597926,memory_total_bytes:34359738368,disk_used_bytes:128849018880,disk_total_bytes:536870912000,gpu_state:'unknown',gpu_detail:'未接入真实GPU监控',simulated:true},services:[{key:'weknora',name:'WeKnora API',state:'healthy',detail:'模拟连接正常',latency_ms:86,observed_at:'2026-09-08T12:00:00Z',simulated:true},{key:'mineru',name:'MinerU',state:'healthy',detail:'模拟处理中2,队列5',latency_ms:24,observed_at:'2026-09-08T12:00:00Z',simulated:true},{key:'postgres',name:'PostgreSQL',state:'unknown',detail:'未接入真实监控',latency_ms:0,observed_at:'2026-09-08T12:00:00Z',simulated:true},{key:'redis',name:'Redis / MQ',state:'unknown',detail:'未接入真实监控',latency_ms:0,observed_at:'2026-09-08T12:00:00Z',simulated:true},{key:'oss',name:'OSS',state:'unknown',detail:'未接入真实监控',latency_ms:0,observed_at:'2026-09-08T12:00:00Z',simulated:true}],knowledge_bases:[{id:'kb-sim',name:'公司级技术支持知识库',visibility:'mixed',imported:5750,completed:4530,pending:450,processing:50,finalizing:714,failed:6,cancelled:0,internal_imported:4200,internal_completed:3300,external_imported:1550,external_completed:1230}],health:[]}
const overview:MonitorOverview={mode:'simulation',simulated:true,observed_at:'2026-09-08T12:00:00Z',host:{cpu_percent:42,memory_used_bytes:19971597926,memory_total_bytes:34359738368,disk_used_bytes:128849018880,disk_total_bytes:536870912000,gpu_state:'unknown',gpu_detail:'未接入真实GPU监控',simulated:true},services:[{key:'weknora',name:'WeKnora API',state:'healthy',detail:'模拟连接正常',latency_ms:86,observed_at:'2026-09-08T12:00:00Z',simulated:true},{key:'mineru',name:'MinerU',state:'healthy',detail:'模拟处理中2,队列5',latency_ms:24,observed_at:'2026-09-08T12:00:00Z',simulated:true},{key:'postgres',name:'PostgreSQL',state:'unknown',detail:'未接入真实监控',latency_ms:0,observed_at:'2026-09-08T12:00:00Z',simulated:true},{key:'redis',name:'Redis / MQ',state:'unknown',detail:'未接入真实监控',latency_ms:0,observed_at:'2026-09-08T12:00:00Z',simulated:true},{key:'oss',name:'OSS',state:'unknown',detail:'未接入真实监控',latency_ms:0,observed_at:'2026-09-08T12:00:00Z',simulated:true}],knowledge_bases:[{id:'kb-sim',name:'公司级技术支持知识库',visibility:'mixed',imported:5750,completed:4530,pending:450,processing:50,finalizing:714,failed:6,cancelled:0,planned:120,needs_removal:3,stale_planned:0,internal_imported:4200,internal_completed:3300,external_imported:1550,external_completed:1230}],pipeline:{fetch_pending:4,fetch_failed:1,fetch_missing:0,concurrency:2},health:[]}
const files:MonitorFilePage={items:[{name:'[模拟] 产品参数总表.xlsx',directory:'02|产品资料',visibility:'external',status:'finalizing',stage_detail:'基础检索可用,Wiki与图谱仍在生成',elapsed_seconds:2100,error_code:''}],total:1,limit:20,offset:0,sample_only:true}
const metrics:RunMetrics={observed_at:'2026-09-12T00:00:00Z',active_workers:2,worker_source:'pg_lease',queue:{pending:3,running:4,retry:1,failed:2,oldest_pending_age_seconds:120},short_window:{window_seconds:3600,jobs_started:50,jobs_completed:48,jobs_failed:6,success_rate:88.9,failure_rate:11.1,duration_avg_seconds:55,duration_p50_seconds:30,duration_p95_seconds:1800},long_window:{window_seconds:86400,jobs_started:500,jobs_completed:482,jobs_failed:18,success_rate:96.4,failure_rate:3.6,duration_avg_seconds:70,duration_p50_seconds:45,duration_p95_seconds:2400}}
const queue:TestPublicationPage={items:[{id:'tp-plan',title:'API.docx',ingest_state:'pending',processing_state:'pending',retrieval_state:'unpublished',target_scope: 'internal', change_set_id: 'cs-1', change_type:'added',can_start:true,retry_count:0,last_error:'',can_retry:false,updated_at:'2026-09-09T10:01:00Z'},{id:'tp-failed',title:'CR20A.pdf',ingest_state:'uploaded',processing_state:'failed',retrieval_state:'unpublished',target_scope: 'external', change_set_id: 'cs-1', change_type:'updated',can_start:false,retry_count:1,last_error:'remote_parse_failed',can_retry:true,updated_at:'2026-09-09T10:00:00Z'}],total:2,limit:50,offset:0}
const changeSets:CatalogChangeSetDetail[]=[{id:'cs-1',connection_id:'conn-1',source_name:'国内工业',state:'planned',add_count:2,update_count:1,move_count:1,move_scope_count:1,delete_count:1,no_change_count:10,created_at:'2026-09-10T00:00:00Z',items:[{action:'delete',title:'旧手册.pdf',old_path:'旧目录/旧手册.pdf',new_path:'',reason_code:'source_missing',seq:7}],total:15,limit:20,offset:0}]
const baseProps={overview,files,queue,changeSets,selectedKB:overview.knowledge_bases[0],status:'' as const,queueStatus:'' as const,queueScope:'' as const,loading:false,error:null as string|null,retryingIDs:[] as string[],starting:false,startMessage:'',onSelectKB:vi.fn(),onStatus:vi.fn(),onQueueStatus:vi.fn(),onQueueScope:vi.fn(),lane:'queue',onLaneChange:vi.fn(),metrics,onRetry:vi.fn(),onBatchRetry:vi.fn(),onStart:vi.fn(),onRefresh:vi.fn()}
const queue:TestPublicationPage={items:[{id:'tp-plan',title:'API.docx',ingest_state:'pending',processing_state:'planned',retrieval_state:'unpublished',target_scope: 'internal', change_set_id: '', change_type:'added',can_start:true,retry_count:0,last_error:'',can_retry:false,updated_at:'2026-09-09T10:01:00Z'},{id:'tp-fetch',title:'焊接手册.pdf',ingest_state:'pending',processing_state:'planned',retrieval_state:'unpublished',target_scope:'external',change_set_id:'',change_type:'added',can_start:false,retry_count:0,last_error:'',can_retry:false,updated_at:'2026-09-09T10:02:00Z'},{id:'tp-failed',title:'CR20A.pdf',ingest_state:'uploaded',processing_state:'failed',retrieval_state:'unpublished',target_scope: 'external', change_set_id: '', change_type:'updated',can_start:false,retry_count:1,last_error:'remote_parse_failed',can_retry:true,updated_at:'2026-09-09T10:00:00Z'}],total:3,limit:50,offset:0}
const plans=queue.items.filter((item)=>item.can_start)
const baseProps={overview,files,queue,plans,selectedKB:overview.knowledge_bases[0],status:'' as const,queueStatus:'' as const,queueScope:'' as const,loading:false,error:null as string|null,retryingIDs:[] as string[],starting:false,startMessage:'',onSelectKB:vi.fn(),onStatus:vi.fn(),onQueueStatus:vi.fn(),onQueueScope:vi.fn(),lane:'queue',onLaneChange:vi.fn(),metrics,onRetry:vi.fn(),onBatchRetry:vi.fn(),onStart:vi.fn(),onRefresh:vi.fn()}
describe('WeKnoraMonitorView',()=>{
it('filters the processing queue by target knowledge base and shows each task target',()=>{
const html=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} queueScope="internal" onQueueScope={vi.fn()} />)
@@ -20,42 +18,35 @@ describe('WeKnoraMonitorView',()=>{
expect(html).toContain('对外知识库</option>')
expect(html).toContain('<option value="internal" selected="">对内知识库')
expect(html).toContain('目标知识库')
// the one internal task row shows its target (select option matches are not counted)
expect(html).toContain('scope-badge internal">对内')
expect(html).toContain('scope-badge external">对外')
})
it('offers explicit change-set confirmation with selection and result message (actor comes from session)',()=>{
const html=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='changes' changeSets={changeSets} confirmingSetID='cs-1' confirmMessage='已提交:确认 2 项;新建上传任务 2 个' onConfirmChangeSet={vi.fn()} />)
expect(html).toContain('预览并选择变更文件')
expect(html).toContain('aria-label="选择旧手册.pdf"')
expect(html).toContain('确认处理(0)')
expect(html).not.toContain('操作人<input')
expect(html).toContain('已提交:确认 2 项;新建上传任务 2 个')
it('treats the catalog annotation as the only decision: 待入库 lists plans with one 开始处理 button and no reason form',()=>{
const waiting=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane="waiting" onStart={vi.fn()} />)
expect(waiting).toContain('待入库(2)')
expect(waiting).toContain('开始处理(1)')
expect(waiting).toContain('并发上限(当前 2)')
expect(waiting).not.toContain('确认原因')
expect(waiting).not.toContain('操作人<input')
expect(waiting).toContain('正在从源头取回文件')
})
it('hides confirmation controls after the change set leaves planned state',()=>{
const confirmed=[{...changeSets[0],state:'confirmed' as const}]
const html=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='changes' changeSets={confirmed} onConfirmChangeSet={vi.fn()} />)
expect(html).toContain('已确认')
expect(html).not.toContain('确认处理')
expect(html).toContain('aria-label="选择旧手册.pdf" disabled')
it('shows knowledge-base removal demand from blocked-but-live items',()=>{
const removal=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane="removal" />)
expect(removal).toContain('需下架(3)')
expect(removal).toContain('3 份仍在检索中')
})
it('shows a plainly labelled simulation with per-lane inbox controls',()=>{
const changes=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='changes' />)
for(const text of ['本地模拟数据','持久快照差异','国内工业','新增 2','更新 1','移动 1','删除 1','未变化 10','旧手册.pdf','确认原因','开始处理(1)','刷新来源 ≠ 马上导入知识库','不代表测试服务器真实数据'])expect(changes).toContain(text)
expect(changes).not.toContain('操作人<input')
it('shows inbox lanes for the knowledge-base diff view',()=>{
const attention=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='attention' />)
for(const text of ['需要你出手','CR20A.pdf','tp-failed'.slice(0,0)+'remote_parse_failed','失败阶段 文档解析','批量重试所选(1)','死信(尝试耗尽,不可自动重试)','下载 ✓','文档解析 ✗','建议先在 WeKnora 手动解析该文件确认格式'])expect(attention).toContain(text)
for(const text of ['需要你出手','CR20A.pdf','remote_parse_failed','失败阶段 文档解析','批量重试所选(1)','死信(尝试耗尽,不可自动重试)'])expect(attention).toContain(text)
const inflight=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='inflight' />)
for(const text of ['处理中','知识库解析进度','已导入 5750','completed 4530','pending 450','finalizing 714','对内 3300 / 4200','对外 1230 / 1550','[模拟] 产品参数总表.xlsx','基础检索可用,Wiki与图谱仍在生成','下载 → Hash → OSS → 文档解析 → WeKnora 上传 → 索引 → 完成'])expect(inflight).toContain(text)
for(const text of ['处理中','知识库解析进度','已导入 5750','待入库 120','对内 3300 / 4200','对外 1230 / 1550','源头取件 → Hash'])expect(inflight).toContain(text)
const queueView=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='queue' />)
expect(queueView).toContain('全部任务(2)')
expect(queueView).toContain('确认并解析')
expect(queueView).toContain('全部任务(3)')
expect(queueView).toContain('重试')
expect(queueView).toContain('等待人工确认')
expect(queueView).toContain('1小时·成功')
expect(queueView).toContain('88.9%')
const nav=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='pending' />)
for(const text of ['今天需要我做什么','需人工处理','等待我确认的差异','排队等待','已完成','全部任务'])expect(nav).toContain(text)
const nav=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='waiting' />)
for(const text of ['待入库','需人工处理','需下架','处理中','已完成','全部任务'])expect(nav).toContain(text)
})
it('does not show simulated success totals after a load error without data',()=>{
const html=renderToStaticMarkup(<WeKnoraMonitorView overview={null} files={null} selectedKB={null} status="" queueStatus="" queueScope="" loading={false} error="加载失败" onSelectKB={vi.fn()} onStatus={vi.fn()} onQueueStatus={vi.fn()} onQueueScope={vi.fn()} onRefresh={vi.fn()} />)
+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) }} />
}
+3 -2
View File
@@ -1,9 +1,10 @@
export type MonitorStatus='completed'|'pending'|'processing'|'finalizing'|'failed'|'cancelled'
export interface MonitorHost{cpu_percent:number;memory_used_bytes:number;memory_total_bytes:number;disk_used_bytes:number;disk_total_bytes:number;gpu_state:string;gpu_detail:string;simulated:boolean}
export interface MonitorService{key:string;name:string;state:string;detail:string;latency_ms:number;observed_at:string;simulated:boolean}
export interface KnowledgeProgress{id:string;name:string;visibility:string;imported:number;completed:number;pending:number;processing:number;finalizing:number;failed:number;cancelled:number;internal_imported:number;internal_completed:number;external_imported:number;external_completed:number}
export interface KnowledgeProgress{id:string;name:string;visibility:string;imported:number;completed:number;pending:number;processing:number;finalizing:number;failed:number;cancelled:number;planned:number;needs_removal:number;stale_planned:number;internal_imported:number;internal_completed:number;external_imported:number;external_completed:number}
export interface ServiceHealth{key:string;name:string;liveness:string;readiness:string;reason:string;latency_ms:number;observed_at:string;last_success_at:string|null;consecutive_failures:number;configured:boolean;applicable:boolean}
export interface MonitorOverview{mode:string;simulated:boolean;observed_at:string;host:MonitorHost;services:MonitorService[];knowledge_bases:KnowledgeProgress[];health:ServiceHealth[]}
export interface IngestionPipeline{fetch_pending:number;fetch_failed:number;fetch_missing:number;concurrency:number}
export interface MonitorOverview{mode:string;simulated:boolean;observed_at:string;host:MonitorHost;services:MonitorService[];knowledge_bases:KnowledgeProgress[];pipeline?:IngestionPipeline;health:ServiceHealth[]}
export interface MonitorFile{name:string;directory:string;visibility:string;status:MonitorStatus;stage_detail:string;elapsed_seconds:number;error_code:string}
export interface MonitorFilePage{items:MonitorFile[];total:number;limit:number;offset:number;sample_only:boolean}
const record=(value:unknown):value is Record<string,unknown>=>typeof value==='object'&&value!==null
+2 -2
View File
@@ -1,6 +1,6 @@
import { newOperationID } from './operationKey'
export type IngestState = 'pending' | 'uploading' | 'uploaded' | 'failed'
export type ProcessingState = 'pending' | 'processing' | 'finalizing' | 'completed' | 'failed' | 'stalled'
export type ProcessingState = 'planned' | 'pending' | 'processing' | 'finalizing' | 'completed' | 'failed' | 'stalled'
export interface TestPublication {
id: string
@@ -50,7 +50,7 @@ export interface StartTestPublicationsResult {
const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null
const isCount = (value: unknown): value is number => typeof value === 'number' && Number.isInteger(value) && value >= 0
const ingestStates = new Set<IngestState>(['pending', 'uploading', 'uploaded', 'failed'])
const processingStates = new Set<ProcessingState>(['pending', 'processing', 'finalizing', 'completed', 'failed', 'stalled'])
const processingStates = new Set<ProcessingState>(['planned', 'pending', 'processing', 'finalizing', 'completed', 'failed', 'stalled'])
function parseTestPublication(value: unknown): TestPublication {
if (!isRecord(value) || typeof value.id !== 'string' || typeof value.title !== 'string' ||
+3 -3
View File
@@ -5,7 +5,7 @@ import { activateUISettings, createUISettingsCandidate, fetchActiveUISettings, p
const active = {
id: 'settings-default', state: 'active', document_refresh_seconds: 15,
resource_refresh_seconds: 30, stalled_after_seconds: 1800,
finalizing_after_seconds: 7200, updated_by: 'system:migration',
finalizing_after_seconds: 7200, ingestion_concurrency: 2, updated_by: 'system:migration',
created_at: '2026-09-10T08:00:00Z', activated_at: '2026-09-10T08:00:00Z',
retired_at: null, error_code: '',
}
@@ -29,12 +29,12 @@ describe('UI settings API', () => {
vi.stubGlobal('fetch', fetchMock)
await fetchActiveUISettings()
await createUISettingsCandidate({ document_refresh_seconds: 30, resource_refresh_seconds: 60, stalled_after_seconds: 3600, finalizing_after_seconds: 14400 })
await createUISettingsCandidate({ document_refresh_seconds: 30, resource_refresh_seconds: 60, stalled_after_seconds: 3600, finalizing_after_seconds: 14400, ingestion_concurrency: 3 })
await activateUISettings('uis-candidate')
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/ui-settings')
expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/ui-settings/candidates')
expect(fetchMock.mock.calls[1][1]).toMatchObject({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ document_refresh_seconds: 30, resource_refresh_seconds: 60, stalled_after_seconds: 3600, finalizing_after_seconds: 14400 }) })
expect(fetchMock.mock.calls[1][1]).toMatchObject({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ document_refresh_seconds: 30, resource_refresh_seconds: 60, stalled_after_seconds: 3600, finalizing_after_seconds: 14400, ingestion_concurrency: 3 }) })
expect(fetchMock.mock.calls[2][0]).toBe('/api/v1/ui-settings/uis-candidate/activate')
expect(fetchMock.mock.calls[2][1]).toMatchObject({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' })
vi.unstubAllGlobals()
+4
View File
@@ -6,6 +6,7 @@ export interface UISettings {
resource_refresh_seconds: 30 | 60
stalled_after_seconds: 1800 | 3600
finalizing_after_seconds: 7200 | 14400
ingestion_concurrency: number
updated_by: string
created_at: string
activated_at: string | null
@@ -18,6 +19,7 @@ export interface UISettingsCandidateInput {
resource_refresh_seconds: UISettings['resource_refresh_seconds']
stalled_after_seconds: UISettings['stalled_after_seconds']
finalizing_after_seconds: UISettings['finalizing_after_seconds']
ingestion_concurrency: number
}
export function settingsRefreshDelays(settings: Pick<UISettings, 'document_refresh_seconds' | 'resource_refresh_seconds'>) {
@@ -40,6 +42,7 @@ export function parseUISettingsResponse(value: unknown): UISettings {
typeof item.resource_refresh_seconds !== 'number' || !resourceRefresh.has(item.resource_refresh_seconds) ||
typeof item.stalled_after_seconds !== 'number' || !stalledAfter.has(item.stalled_after_seconds) ||
typeof item.finalizing_after_seconds !== 'number' || !finalizingAfter.has(item.finalizing_after_seconds) ||
typeof item.ingestion_concurrency !== 'number' || !Number.isInteger(item.ingestion_concurrency) || item.ingestion_concurrency < 1 || item.ingestion_concurrency > 16 ||
typeof item.updated_by !== 'string' || typeof item.created_at !== 'string' ||
(item.activated_at !== null && typeof item.activated_at !== 'string') ||
(item.retired_at !== null && typeof item.retired_at !== 'string') || typeof item.error_code !== 'string') {
@@ -52,6 +55,7 @@ export function parseUISettingsResponse(value: unknown): UISettings {
resource_refresh_seconds: item.resource_refresh_seconds as UISettings['resource_refresh_seconds'],
stalled_after_seconds: item.stalled_after_seconds as UISettings['stalled_after_seconds'],
finalizing_after_seconds: item.finalizing_after_seconds as UISettings['finalizing_after_seconds'],
ingestion_concurrency: item.ingestion_concurrency,
updated_by: item.updated_by,
created_at: item.created_at,
activated_at: item.activated_at as string | null,