Files
knowledge-governance/web/src/WeKnoraMonitor.tsx
T
姚章浩 1b09f7d35b
build / build (push) Successful in 1m17s
feat(monitor): 卡片概况与统一文件处理表
2026-10-27 12:14:19 +08:00

750 lines
28 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useContext, useEffect, useRef, useState } from 'react'
import { fetchMonitorOverview, fetchRunMetrics } from './monitor'
import type { MonitorOverview, RunMetrics, ServiceHealth } from './monitor'
import {
fetchMonitorTasks,
defaultMonitorFilters,
canRetryTask,
actionLabels,
stageLabels,
taskStatusLabels,
} from './monitorTasks'
import type { MonitorFilters, MonitorTask, MonitorTaskPage } from './monitorTasks'
import { requeueJobFailure, retryPublicationsBatch } from './testPublications'
import { fetchActiveUISettings, settingsRefreshDelays } from './uiSettings'
import { useOptionalAuth } from './auth'
import { WorkspaceContextTabsSetter } from './workspaceContext'
import './monitorWorkbench.css'
const emptyPage: MonitorTaskPage = { items: [], total: 0, limit: 20, offset: 0, sources: [], targets: [], retryable: 0 }
const time = (value: string) => (value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '—')
const percent = (value: number | null | undefined) => (value == null ? '—' : `${value}%`)
const seconds = (value: number | null | undefined) => (value == null ? '—' : `${Number(value.toFixed(1))} 秒`)
const gb = (n: number) => Number((n / 1073741824).toFixed(1))
export function healthLabel(service: ServiceHealth) {
if (!service.applicable) return '不适用'
if (!service.configured || service.readiness === 'not_configured') return '未配置'
return (
(
{ ready: '可接单', degraded: '降级', blocked: '阻断', down: '不可达', unknown: '未确认' } as Record<
string,
string
>
)[service.readiness] || '未确认'
)
}
interface ViewProps {
overview: MonitorOverview | null
metrics: RunMetrics | null
page: MonitorTaskPage
filters: MonitorFilters
selected: MonitorTask[]
loading: boolean
busy: boolean
error: string
message: string
canOperate: boolean
onFilters: (value: MonitorFilters) => void
onPage: (offset: number) => void
onSelection: (rows: MonitorTask[]) => void
onSelectAll: () => void
onRetry: (rows: MonitorTask[]) => void
onDetail: (row: MonitorTask) => void
onRefresh: () => void
}
export function WeKnoraMonitorView(p: ViewProps) {
const { overview, metrics, page, filters, selected, busy, loading } = p
const patchFilter = (key: keyof MonitorFilters, value: string) => p.onFilters({ ...filters, [key]: value })
const toggle = (item: MonitorTask) =>
p.onSelection(
selected.some((r) => r.id === item.id) ? selected.filter((r) => r.id !== item.id) : [...selected, item]
)
const eligible = page.items.filter(canRetryTask)
const selectedIDs = new Set(selected.map((r) => r.id))
const allPage = eligible.length > 0 && eligible.every((r) => selectedIDs.has(r.id))
const kbName = (id: string) => overview?.knowledge_bases.find((k) => k.id === id)?.name || id
return (
<main className="page-shell monitor-workbench">
<header className="monitor-heading">
<div>
<h1>解析监控</h1>
<p>运行概况与文件处理进度</p>
</div>
<span>{overview ? `快照 ${time(overview.observed_at)}` : '等待运行快照'}</span>
<button disabled={busy || loading} onClick={p.onRefresh}>
{loading ? '刷新中…' : '刷新'}
</button>
</header>
{p.error ? (
<div className="monitor-alert" role="alert">
{p.error}
</div>
) : null}
{overview?.simulated || metrics?.worker_source === 'simulation' ? (
<div className="monitor-alert">运行指标含模拟数据;下方文件状态来自治理数据库。</div>
) : null}
<section className="monitor-metric-grid" aria-label="系统运行指标">
<article>
<h2>
任务成功率 <small>全部任务口径</small>
</h2>
<div className="monitor-numbers">
<div>
<strong>{percent(metrics?.short_window.success_rate)}</strong>
<span>最近 1 小时</span>
</div>
<div>
<strong>{percent(metrics?.long_window.success_rate)}</strong>
<span>最近 24 小时</span>
</div>
</div>
</article>
<article>
<h2>
处理耗时 <small>最近 1 小时</small>
</h2>
<div className="monitor-numbers">
<div>
<strong>{seconds(metrics?.short_window.duration_p50_seconds)}</strong>
<span>p50 · 中位耗时</span>
</div>
<div>
<strong>{seconds(metrics?.short_window.duration_p95_seconds)}</strong>
<span>p95 · 处理耗时</span>
</div>
</div>
</article>
<article>
<h2>
任务队列 <small>全部任务口径</small>
</h2>
<div className="monitor-numbers">
<div>
<strong>{metrics?.active_workers ?? '—'}</strong>
<span>活跃 Worker</span>
</div>
<div>
<strong>{metrics?.queue.pending ?? '—'}</strong>
<span>等待</span>
</div>
<div>
<strong>{metrics?.queue.running ?? '—'}</strong>
<span>运行</span>
</div>
<div>
<strong className="monitor-bad">{metrics?.queue.failed ?? '—'}</strong>
<span>失败</span>
</div>
</div>
</article>
<article>
<h2>
主机资源 <small>当前</small>
</h2>
<div className="monitor-numbers">
<div>
<strong>{overview ? `${overview.host.cpu_percent.toFixed(0)}%` : '—'}</strong>
<span>CPU 使用率</span>
</div>
<div>
<strong className="monitor-memory">
{overview ? `${gb(overview.host.memory_used_bytes)} / ${gb(overview.host.memory_total_bytes)}` : '—'}
</strong>
<span>内存 · GB</span>
</div>
</div>
</article>
</section>
<section className="monitor-service-panel">
<div className="monitor-section-heading">
<h2>服务与依赖</h2>
<span>展开查看状态原因</span>
</div>
<div className="monitor-service-grid">
{overview?.health.length ? (
overview.health.map((s) => (
<details key={s.key} className="monitor-service">
<summary>
<span>{s.name}</span>
<b
className={
healthLabel(s) === '可接单'
? 'monitor-good'
: ['阻断', '不可达'].includes(healthLabel(s))
? 'monitor-bad'
: ''
}
>
● {healthLabel(s)}
</b>
</summary>
<p>{s.reason || '未提供状态说明'}</p>
<small>
检测:{time(s.observed_at)} · {s.latency_ms} ms
</small>
</details>
))
) : (
<p className="monitor-muted">尚未取得服务状态</p>
)}
</div>
</section>
<section className="monitor-files">
<div className="monitor-section-heading">
<h2>文件处理</h2>
<span>生产发布授权在「发布管理」</span>
</div>
<div className="monitor-filters">
<input
aria-label="搜索文件名称或目录"
placeholder="搜索文件名称或目录"
value={filters.q}
disabled={busy}
onChange={(e) => patchFilter('q', e.target.value)}
/>
<select
aria-label="来源"
value={filters.source}
disabled={busy}
onChange={(e) => patchFilter('source', e.target.value)}
>
<option value="">全部来源</option>
{page.sources.map((s) => (
<option key={s.id} value={s.id}>
{s.name}
</option>
))}
</select>
<select
aria-label="目标范围"
value={filters.scope}
disabled={busy}
onChange={(e) => patchFilter('scope', e.target.value)}
>
<option value="">对内 / 对外</option>
<option value="internal">对内知识库</option>
<option value="external">对外知识库</option>
</select>
<select
aria-label="目标知识库"
value={filters.target}
disabled={busy}
onChange={(e) => patchFilter('target', e.target.value)}
>
<option value="">全部目标知识库</option>
{page.targets.map((t) => (
<option key={t.id} value={t.id}>
{kbName(t.id)}
</option>
))}
</select>
<select
aria-label="处理动作"
value={filters.action}
disabled={busy}
onChange={(e) => patchFilter('action', e.target.value)}
>
<option value="">全部处理动作</option>
{Object.entries(actionLabels).map(([key, label]) => (
<option key={key} value={key}>
{label}
</option>
))}
</select>
<select
aria-label="处理状态"
value={filters.status}
disabled={busy}
onChange={(e) => patchFilter('status', e.target.value)}
>
<option value="active">未结束</option>
<option value="">全部处理状态</option>
{Object.entries(taskStatusLabels).map(([key, label]) => (
<option key={key} value={key}>
{label}
</option>
))}
</select>
<select
aria-label="当前阶段"
value={filters.stage}
disabled={busy}
onChange={(e) => patchFilter('stage', e.target.value)}
>
<option value="">全部阶段</option>
{Object.entries(stageLabels).map(([key, label]) => (
<option key={key} value={key}>
{label}
</option>
))}
</select>
<details className="monitor-time-filter">
<summary>时间范围{filters.since || filters.until ? ' · 已筛选' : ''}</summary>
<label>
更新时间起
<input
type="datetime-local"
aria-label="更新时间起"
disabled={busy}
value={
filters.since
? new Date(new Date(filters.since).getTime() - new Date(filters.since).getTimezoneOffset() * 60000)
.toISOString()
.slice(0, 16)
: ''
}
onChange={(e) => patchFilter('since', e.target.value ? new Date(e.target.value).toISOString() : '')}
/>
</label>
<label>
更新时间止
<input
type="datetime-local"
aria-label="更新时间止"
disabled={busy}
value={
filters.until
? new Date(new Date(filters.until).getTime() - new Date(filters.until).getTimezoneOffset() * 60000)
.toISOString()
.slice(0, 16)
: ''
}
onChange={(e) => patchFilter('until', e.target.value ? new Date(e.target.value).toISOString() : '')}
/>
</label>
</details>
<button
className="monitor-link"
disabled={busy}
onClick={() => p.onFilters({ ...defaultMonitorFilters, status: '' })}
>
清除筛选
</button>
</div>
{p.canOperate ? (
<div className="monitor-batch">
<b>已选 {selected.length} 项</b>
<span>只重试可恢复项,沿用原处理动作</span>
<button className="monitor-link" disabled={busy || loading || !page.retryable} onClick={p.onSelectAll}>
选择筛选内全部可重试项({page.retryable})
</button>
<button
className="primary"
disabled={busy || loading || !selected.length}
onClick={() => p.onRetry(selected)}
>
{busy ? '处理中…' : `重试所选(${selected.length})`}
</button>
</div>
) : null}
{p.message ? (
<div className="monitor-result" role="status">
{p.message}
</div>
) : null}
<div className="monitor-table-scroll" aria-busy={loading}>
<table className="monitor-unified-table">
<colgroup>
<col style={{ width: '3%' }} />
<col style={{ width: '20%' }} />
<col style={{ width: '10%' }} />
<col style={{ width: '11%' }} />
<col style={{ width: '6%' }} />
<col style={{ width: '8%' }} />
<col style={{ width: '9%' }} />
<col style={{ width: '16%' }} />
<col style={{ width: '10%' }} />
<col style={{ width: '7%' }} />
</colgroup>
<thead>
<tr>
<th>
{p.canOperate ? (
<input
type="checkbox"
aria-label="选择本页可重试项"
checked={allPage}
disabled={busy || loading || !eligible.length}
onChange={() =>
p.onSelection(
allPage
? selected.filter((r) => !eligible.some((e) => e.id === r.id))
: [...selected, ...eligible.filter((e) => !selectedIDs.has(e.id))]
)
}
/>
) : null}
</th>
<th>文件名称 / 目录</th>
<th>来源</th>
<th>目标知识库</th>
<th>处理动作</th>
<th>当前阶段</th>
<th>处理状态</th>
<th>状态说明</th>
<th>更新时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{page.items.map((item) => (
<tr key={item.id} className={selectedIDs.has(item.id) ? 'monitor-selected' : ''}>
<td>
{canRetryTask(item) && p.canOperate ? (
<input
type="checkbox"
aria-label={`选择${item.title}`}
checked={selectedIDs.has(item.id)}
disabled={busy || loading}
onChange={() => toggle(item)}
/>
) : null}
</td>
<td>
<b className="monitor-file-name">{item.title || '未命名文件'}</b>
<small title={item.path}>{item.path || '未提供目录'}</small>
</td>
<td>{item.source_name}</td>
<td>
<span className="monitor-scope">{item.target_scope === 'internal' ? '对内' : '对外'}</span>
<small title={kbName(item.target_kb)}>{kbName(item.target_kb)}</small>
</td>
<td>{actionLabels[item.action]}</td>
<td>{stageLabels[item.stage]}</td>
<td>
<span className={`monitor-state ${item.status}`}>{taskStatusLabels[item.status]}</span>
</td>
<td className="monitor-detail-cell" title={item.detail}>
{item.detail}
</td>
<td>{time(item.updated_at)}</td>
<td>
<button className="monitor-link" onClick={() => p.onDetail(item)}>
详情
</button>
{canRetryTask(item) && p.canOperate ? (
<button className="monitor-link" disabled={busy || loading} onClick={() => p.onRetry([item])}>
重试
</button>
) : null}
</td>
</tr>
))}
{!page.items.length ? (
<tr>
<td colSpan={10} className="monitor-empty">
{loading ? '正在读取文件状态…' : '当前筛选没有文件,可清除筛选查看全部。'}
</td>
</tr>
) : null}
</tbody>
</table>
</div>
<footer className="monitor-pagination">
<span>
共 {page.total} 项 · 每页 {page.limit} 项
</span>
<div>
<button
disabled={busy || loading || page.offset === 0}
onClick={() => p.onPage(Math.max(0, page.offset - page.limit))}
>
上一页
</button>
<span>
{Math.floor(page.offset / page.limit) + 1} / {Math.max(1, Math.ceil(page.total / page.limit))}
</span>
<button
disabled={busy || loading || page.offset + page.limit >= page.total}
onClick={() => p.onPage(page.offset + page.limit)}
>
下一页
</button>
</div>
</footer>
</section>
</main>
)
}
function TaskDetail({ item, onClose }: { item: MonitorTask; onClose: () => void }) {
const ref = useRef<HTMLDialogElement>(null)
useEffect(() => {
ref.current?.showModal()
}, [])
return (
<dialog className="monitor-drawer" ref={ref} onCancel={onClose}>
<header>
<h2>文件处理详情</h2>
<button onClick={onClose} autoFocus>
关闭
</button>
</header>
<h3>{item.title}</h3>
<dl>
{[
['来源', item.source_name],
['目录', item.path],
['目标知识库', item.target_kb],
['处理动作', actionLabels[item.action]],
['当前阶段', stageLabels[item.stage]],
['处理状态', taskStatusLabels[item.status]],
['状态说明', item.detail],
['更新时间', time(item.updated_at)],
['累计重试', String(item.retry_count)],
['版本标识', item.version_id],
].map(([label, value]) => (
<div key={label}>
<dt>{label}</dt>
<dd>{value || '—'}</dd>
</div>
))}
</dl>
{item.history?.length ? (
<section className="monitor-history">
<h3>版本与重试记录</h3>
<p className="monitor-muted">最近 50 条已登记记录,不推断未记录的处理步骤。</p>
{item.history.map((event, i) => (
<article key={i}>
<b>{event.kind}</b>
<small>{time(event.at)}</small>
<p>{event.detail}</p>
</article>
))}
</section>
) : null}
<p className="monitor-muted">新增、更新完成表示测试库处理完成;移除完成表示测试库内容移除,不代表生产发布。</p>
{item.status === 'attention' ? (
<p className="monitor-alert">
请先确认配置、权限或依赖已恢复。
{canRetryTask(item) ? '重试将沿用原处理动作。' : '当前记录不满足安全重试条件,需先修复前置条件。'}
</p>
) : null}
</dialog>
)
}
export function WeKnoraMonitor() {
const auth = useOptionalAuth()
const canOperate = auth?.identity?.role === 'admin' || auth?.identity?.role === 'engineer'
const [overview, setOverview] = useState<MonitorOverview | null>(null),
[metrics, setMetrics] = useState<RunMetrics | null>(null)
const [page, setPage] = useState(emptyPage),
[filters, setFilters] = useState(defaultMonitorFilters),
[offset, setOffset] = useState(0)
const [selected, setSelected] = useState<MonitorTask[]>([]),
[detail, setDetail] = useState<MonitorTask | null>(null)
const [loading, setLoading] = useState(true),
[busy, setBusy] = useState(false),
[message, setMessage] = useState('')
const [errors, setErrors] = useState({ files: '', overview: '', metrics: '', settings: '' })
const [docRev, setDocRev] = useState(0),
[resRev, setResRev] = useState(0),
[delays, setDelays] = useState({ documentMs: 15000, resourceMs: 30000 })
const setTabs = useContext(WorkspaceContextTabsSetter)
useEffect(() => {
setTabs([])
return () => setTabs([])
}, [setTabs])
useEffect(() => {
const c = new AbortController()
void fetchActiveUISettings(c.signal)
.then((s) => {
if (!c.signal.aborted) setDelays(settingsRefreshDelays(s))
})
.catch((e) => {
if (!c.signal.aborted) setErrors((x) => ({ ...x, settings: String(e) }))
})
return () => c.abort()
}, [])
useEffect(() => {
const t = window.setTimeout(() => setDocRev((x) => x + 1), delays.documentMs)
return () => clearTimeout(t)
}, [docRev, delays.documentMs])
useEffect(() => {
const t = window.setTimeout(() => setResRev((x) => x + 1), delays.resourceMs)
return () => clearTimeout(t)
}, [resRev, delays.resourceMs])
useEffect(() => {
const c = new AbortController()
setLoading(true)
const timer = window.setTimeout(() => {
void fetchMonitorTasks(filters, offset, 20, c.signal)
.then((p) => {
if (c.signal.aborted) return
setPage(p)
setErrors((e) => ({ ...e, files: '' }))
setSelected((old) =>
old.flatMap((r) => {
const fresh = p.items.find((i) => i.id === r.id)
return fresh ? (canRetryTask(fresh) ? [fresh] : []) : [r]
})
)
})
.catch((e) => {
if (!c.signal.aborted) {
setPage({ ...emptyPage, offset })
setErrors((x) => ({ ...x, files: e instanceof Error ? e.message : '读取文件状态失败' }))
}
})
.finally(() => {
if (!c.signal.aborted) setLoading(false)
})
}, 200)
return () => {
clearTimeout(timer)
c.abort()
}
}, [filters, offset, docRev])
useEffect(() => {
const c = new AbortController()
void fetchMonitorOverview(c.signal)
.then((r) => {
if (!c.signal.aborted) {
setOverview(r)
setErrors((e) => ({ ...e, overview: '' }))
}
})
.catch((e) => {
if (!c.signal.aborted) {
setOverview(null)
setErrors((x) => ({ ...x, overview: e instanceof Error ? e.message : '读取服务状态失败' }))
}
})
void fetchRunMetrics(c.signal)
.then((r) => {
if (!c.signal.aborted) {
setMetrics(r)
setErrors((e) => ({ ...e, metrics: '' }))
}
})
.catch((e) => {
if (!c.signal.aborted) {
setMetrics(null)
setErrors((x) => ({ ...x, metrics: e instanceof Error ? e.message : '读取运行指标失败' }))
}
})
return () => c.abort()
}, [resRev])
const refresh = () => {
setDocRev((x) => x + 1)
setResRev((x) => x + 1)
}
const selectAll = async () => {
if (busy) return
setBusy(true)
setMessage('')
try {
const found = new Map<string, MonitorTask>()
for (let at = 0; ; at += 100) {
const p = await fetchMonitorTasks(filters, at, 100)
if (p.total > 10000) throw new Error('筛选结果超过 10000 项,请缩小范围后再选择')
p.items.filter(canRetryTask).forEach((r) => found.set(r.id, r))
if (at + p.items.length >= p.total || !p.items.length) break
}
setSelected([...found.values()])
setMessage(`已选择 ${found.size} 项;提交前会重新核验状态。`)
} catch (e) {
setMessage(e instanceof Error ? e.message : '跨页选择失败')
} finally {
setBusy(false)
}
}
const retry = async (rows: MonitorTask[]) => {
if (busy || !rows.length) return
const removals = rows.filter((r) => r.action === 'remove').length
if (
!window.confirm(
`重试 ${rows.length} 项:新增/更新 ${rows.length - removals} 项,测试库移除 ${removals} 项。\n不会删除来源文件或操作生产知识库。是否继续?`
)
)
return
setBusy(true)
setMessage('')
let accepted = 0,
skipped = 0,
failed = 0
const notes: string[] = []
for (const row of rows) {
try {
const fresh = (await fetchMonitorTasks({ id: row.id }, 0, 1)).items[0]
if (!fresh || !canRetryTask(fresh) || fresh.action !== row.action) {
skipped++
notes.push(`${row.title}:状态已变化,跳过`)
continue
}
if (fresh.retry_kind === 'fetch') {
const r = await requeueJobFailure(fresh.failure_id, '解析监控重试')
if (r.already_queued) {
skipped++
continue
}
} else if (fresh.retry_kind === 'upload') {
const r = await retryPublicationsBatch([fresh.id], '解析监控重试')
if (!r.started) {
skipped++
notes.push(`${row.title}:${r.outcomes[0]?.detail || '处理中或不可重试'}`)
continue
}
} else {
const r = await fetch(`/api/v1/test-publications/${encodeURIComponent(fresh.id)}/removal-retry`, {
method: 'POST',
headers: { Accept: 'application/json', 'X-Governance-Action': 'monitor-removal-retry' },
})
if (!r.ok) throw new Error(`测试库移除重试失败(HTTP ${r.status})`)
}
accepted++
try {
await fetchMonitorTasks({ id: fresh.id }, 0, 1)
} catch {
notes.push(`${row.title}:已受理,状态读回失败,请刷新确认`)
}
} catch (e) {
failed++
notes.push(`${row.title}:${e instanceof Error ? e.message : '请求失败'}`)
}
}
setMessage(
`已受理 ${accepted} 项,已跳过 ${skipped} 项,失败 ${failed} 项。受理不代表处理完成。${notes.length ? ' ' + notes.join(';') : ''}`
)
setSelected([])
setBusy(false)
refresh()
}
return (
<>
<WeKnoraMonitorView
overview={overview}
metrics={metrics}
page={page}
filters={filters}
selected={selected}
loading={loading}
busy={busy}
error={Object.values(errors).filter(Boolean).join(';')}
message={message}
canOperate={canOperate}
onFilters={(v) => {
setFilters(v)
setOffset(0)
setSelected([])
setMessage('')
setLoading(true)
}}
onPage={setOffset}
onSelection={setSelected}
onSelectAll={() => void selectAll()}
onRetry={(r) => void retry(r)}
onDetail={(row) => {
void fetchMonitorTasks({ id: row.id }, 0, 1)
.then((p) => {
if (p.items[0]) setDetail(p.items[0])
else setMessage('该条记录已被新版本替换,请刷新列表')
})
.catch((e) => setMessage(e instanceof Error ? e.message : '读取详情失败'))
}}
onRefresh={refresh}
/>
{detail ? <TaskDetail item={detail} onClose={() => setDetail(null)} /> : null}
</>
)
}