f6cb90cd70
- main.tsx 挂 AuthProvider 门控:未登录→登录页;must_change_password→强制改密页 - 登录页/改密页/顶栏身份(头像+姓名+角色徽章+退出)按 A·Data-console token 样式 - 全局 fetch 拦截器:任意业务请求 401 自动回登录页(会话过期/被撤销不留死表单) - 系统设置新增「成员与角色」分区(仅 admin 可见):名单、角色调整、启停、重置临时密码、新增成员 - 消灭全部手填操作人:审核/封批/确认计划集/范围规则/来源调度/UI 设置/开始处理/批量重试/ 目录差异确认共 9 处输入框删除,请求体不再携带 actor 字段(服务端从会话注入) - 测试断言方向翻转:显式验证请求体不含 operator_ref/created_by 等字段 - 附带修复:登录失败计数 SQL 参数类型无法推断导致 500(pgx 扩展协议),显式 cast 解决 前端门禁:tsc 0 错、125 用例全绿、build 通过
392 lines
34 KiB
TypeScript
392 lines
34 KiB
TypeScript
import { useContext, useEffect, useMemo, useState } from 'react'
|
||
|
||
import { fetchMonitorFiles, fetchMonitorOverview, fetchRunMetrics } from './monitor'
|
||
import type { RunMetrics } from './monitor'
|
||
import type { KnowledgeProgress, MonitorFilePage, MonitorOverview, MonitorStatus } from './monitor'
|
||
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'
|
||
|
||
const emptyQueue: TestPublicationPage = { items: [], total: 0, limit: 50, offset: 0 }
|
||
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 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 === 'Hash / 文件校验' || stage === 'OSS') return '文件或暂存校验问题,重新入队会重新拉取来源文件。'
|
||
if (stage === '测试知识移除') return '移除失败,请先在测试知识库确认该文档当前状态。'
|
||
if (stage === '治理策略') return '按治理策略阻止,请先在来源目录修正对内/对外标注。'
|
||
if (code.includes('429')) return '远端容量已满,恢复后可一键重新入队。'
|
||
return '确认错误码后可直接重试;尝试次数耗尽将进入死信队列。'
|
||
}
|
||
|
||
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
|
||
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 }
|
||
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('oss')) return 'OSS'
|
||
if (code.includes('upload')) return 'WeKnora 上传'
|
||
if (code.includes('parse')) return '文档解析'
|
||
if (code.includes('stalled') || code.includes('index')) return '索引 / 增强'
|
||
if (code.includes('removal')) return '测试知识移除'
|
||
if (code.includes('blocked')) return '治理策略'
|
||
return item.processing_state === 'failed' ? '处理链路' : '—'
|
||
}
|
||
|
||
interface ViewProps {
|
||
overview: MonitorOverview | null
|
||
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 | ''
|
||
queueScope?: 'internal' | 'external' | ''
|
||
loading: boolean
|
||
error: string | null
|
||
retryingIDs?: string[]
|
||
starting?: boolean
|
||
startMessage?: string
|
||
batchMessage?: string
|
||
failures?: JobFailure[]
|
||
metrics?: RunMetrics | null
|
||
onSelectKB: (kb: KnowledgeProgress) => void
|
||
onStatus: (status: MonitorStatus | '') => void
|
||
onQueueStatus: (value: ProcessingState | '') => void
|
||
onQueueScope: (value: 'internal' | 'external' | '') => void
|
||
lane?: string
|
||
onLaneChange?: (lane: string) => void
|
||
onRetry?: (id: string) => void
|
||
onBatchRetry?: (ids: string[]) => void
|
||
onStart?: (ids: string[], reason: 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',
|
||
onLaneChange = () => undefined,
|
||
loading,
|
||
error,
|
||
retryingIDs = [],
|
||
starting = false,
|
||
startMessage = '',
|
||
batchMessage = '',
|
||
failures = [],
|
||
metrics = null,
|
||
onSelectKB,
|
||
onStatus,
|
||
onQueueStatus = () => undefined,
|
||
onQueueScope = () => undefined,
|
||
onRetry = () => undefined,
|
||
onBatchRetry = () => undefined,
|
||
onStart = () => undefined,
|
||
onRefresh,
|
||
}: ViewProps) {
|
||
const [startReason, setStartReason] = useState('已核对来源快照与测试知识库差异')
|
||
const [selectedRetryIDs, setSelectedRetryIDs] = useState<string[]>([])
|
||
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],
|
||
['processing', selectedKB.processing], ['failed', selectedKB.failed], ['cancelled', selectedKB.cancelled],
|
||
] : []
|
||
const orderedQueue = useMemo(() => [...queue.items].sort((left, right) => {
|
||
const priority = (item: TestPublication) => item.processing_state === 'failed' || item.processing_state === 'stalled' ? 0 : 1
|
||
return priority(left) - priority(right)
|
||
}), [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 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 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>
|
||
<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="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>
|
||
<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>
|
||
</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>
|
||
{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>)}
|
||
<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 === '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('当前没有等待处理的死信记录。')}
|
||
</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}
|
||
</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="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>
|
||
<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-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}
|
||
{files?.items.length ? <div className="monitor-file-wrap"><table className="monitor-file-table"><thead><tr><th>文件名</th><th>来源目录</th><th>对内/对外</th><th>当前阶段</th><th>已停留</th><th>说明</th></tr></thead><tbody>{files.items.map((file) => <tr key={`${file.name}-${file.status}`}><td>{file.name}</td><td>{file.directory}</td><td><span className={`scope-badge ${file.visibility}`}>{scope(file.visibility)}</span></td><td><span className={`monitor-status ${file.status}`}>{file.status}</span></td><td>{duration(file.elapsed_seconds)}</td><td>{file.stage_detail}{file.error_code ? <small>{file.error_code}</small> : null}</td></tr>)}</tbody></table></div> : !loading ? <div className="empty-state">当前筛选没有文件。</div> : null}
|
||
</> : null}</div>
|
||
</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('当前页没有已完成任务;用全部任务视图翻页查看。')}
|
||
</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}
|
||
</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>
|
||
</div>
|
||
</main>
|
||
}
|
||
|
||
export function WeKnoraMonitor() {
|
||
const [overview, setOverview] = useState<MonitorOverview | null>(null)
|
||
const [selected, setSelected] = useState<KnowledgeProgress | null>(null)
|
||
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 [loading, setLoading] = useState(true)
|
||
const [error, setError] = useState<string | null>(null)
|
||
const [documentRevision, setDocumentRevision] = useState(0)
|
||
const [resourceRevision, setResourceRevision] = useState(0)
|
||
const [documentRefreshMs, setDocumentRefreshMs] = useState(15000)
|
||
const [resourceRefreshMs, setResourceRefreshMs] = useState(30000)
|
||
const [retryingIDs, setRetryingIDs] = useState<string[]>([])
|
||
const [starting, setStarting] = useState(false)
|
||
const [startMessage, setStartMessage] = useState('')
|
||
const [batchMessage, setBatchMessage] = useState('')
|
||
const [failures, setFailures] = useState<JobFailure[]>([])
|
||
const [metrics, setMetrics] = useState<RunMetrics | null>(null)
|
||
const setContextTabs = useContext(WorkspaceContextTabsSetter)
|
||
|
||
useEffect(() => {
|
||
const controller = new AbortController()
|
||
void fetchActiveUISettings(controller.signal).then((active) => {
|
||
const delays = settingsRefreshDelays(active)
|
||
if (!controller.signal.aborted) { setDocumentRefreshMs(delays.documentMs); setResourceRefreshMs(delays.resourceMs) }
|
||
}).catch((cause) => { if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载刷新设置失败') })
|
||
return () => controller.abort()
|
||
}, [])
|
||
|
||
useEffect(() => {
|
||
const controller = new AbortController(); setLoading(true)
|
||
void fetchMonitorOverview(controller.signal).then((result) => {
|
||
if (controller.signal.aborted) return
|
||
setOverview(result)
|
||
setSelected((current) => current && result.knowledge_bases.find((kb) => kb.id === current.id) || result.knowledge_bases[0] || null)
|
||
setError(null)
|
||
}).catch((cause) => { if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载资源监控失败') }).finally(() => { if (!controller.signal.aborted) setLoading(false) })
|
||
return () => controller.abort()
|
||
}, [resourceRevision])
|
||
|
||
useEffect(() => {
|
||
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) }
|
||
}).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])
|
||
|
||
useEffect(() => {
|
||
if (!selected) return
|
||
const controller = new AbortController()
|
||
setLoading(true)
|
||
void fetchMonitorFiles(selected.id, status, 20, 0, controller.signal).then((result) => {
|
||
if (!controller.signal.aborted) setFiles(result)
|
||
}).catch((cause) => {
|
||
if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载文档阶段失败')
|
||
}).finally(() => {
|
||
if (!controller.signal.aborted) setLoading(false)
|
||
})
|
||
return () => controller.abort()
|
||
}, [selected, status, documentRevision])
|
||
|
||
useEffect(() => {
|
||
const timer = window.setTimeout(() => setDocumentRevision((value) => value + 1), documentRefreshMs)
|
||
return () => window.clearTimeout(timer)
|
||
}, [documentRevision, documentRefreshMs])
|
||
useEffect(() => {
|
||
const timer = window.setTimeout(() => setResourceRevision((value) => value + 1), resourceRefreshMs)
|
||
return () => window.clearTimeout(timer)
|
||
}, [resourceRevision, resourceRefreshMs])
|
||
useEffect(() => {
|
||
setContextTabs(selected ? [{ key: selected.id, label: selected.name, onActivate: () => setStatus('') }] : [])
|
||
return () => setContextTabs([])
|
||
}, [selected, setContextTabs])
|
||
useEffect(() => {
|
||
const controller = new AbortController()
|
||
void fetchJobFailures(controller.signal).then((items) => { if (!controller.signal.aborted) setFailures(items) }).catch(() => undefined)
|
||
return () => controller.abort()
|
||
}, [documentRevision, resourceRevision])
|
||
useEffect(() => {
|
||
const controller = new AbortController()
|
||
void fetchRunMetrics(controller.signal).then((result) => { if (!controller.signal.aborted) setMetrics(result) }).catch(() => undefined)
|
||
return () => controller.abort()
|
||
}, [documentRevision, resourceRevision])
|
||
|
||
const retryOne = async (id: string) => {
|
||
setRetryingIDs((current) => [...current, id])
|
||
try {
|
||
await retryPublication(id)
|
||
setError(null)
|
||
setDocumentRevision((value) => value + 1)
|
||
} catch (cause) {
|
||
setError(cause instanceof Error ? cause.message : '重试失败')
|
||
} finally {
|
||
setRetryingIDs((current) => current.filter((value) => value !== id))
|
||
}
|
||
}
|
||
|
||
const retryBatch = async (ids: string[]) => {
|
||
setRetryingIDs(ids)
|
||
setBatchMessage('')
|
||
try {
|
||
const result = await retryPublicationsBatch(ids, '解析队列批量重试')
|
||
setError(null)
|
||
const skipped = result.already_running + result.not_retryable
|
||
setBatchMessage(`已重新入队 ${result.started} 项${skipped ? `,跳过 ${skipped} 项(处理中或不可重试)` : ''}`)
|
||
setDocumentRevision((value) => value + 1)
|
||
} catch (cause) {
|
||
setError(cause instanceof Error ? cause.message : '批量重试失败')
|
||
} finally {
|
||
setRetryingIDs([])
|
||
}
|
||
}
|
||
|
||
const startPlans = async (ids: string[], reason: string) => {
|
||
setStarting(true)
|
||
setStartMessage('')
|
||
try {
|
||
const result = await startTestPublications(ids, reason)
|
||
setStartMessage(`已确认 ${result.selected} 项;新建解析任务 ${result.started} 项;已开始 ${result.already_started} 项;不可处理 ${result.unavailable} 项。`)
|
||
setError(null)
|
||
setDocumentRevision((value) => value + 1)
|
||
} catch (cause) {
|
||
setStartMessage(cause instanceof Error ? cause.message : '开始处理失败')
|
||
} finally {
|
||
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) }} />
|
||
} |