Files
knowledge-governance/web/src/QAAI.tsx
T
姚章浩 00c4c13283
build / build (push) Successful in 1m19s
fix(qa): 首批即显并统一五字段后端筛选
列表正文改为按需读取;保留完整导出、版本隔离和有效标签筛选。
验证:前端全量、Go全量及隔离PG全mirror竞态通过;覆盖首批回调、续载失败与筛选分页。
2026-10-25 12:45:31 +08:00

546 lines
20 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 { useEffect, useRef, useState } from 'react'
import type { AIKind, AIStatus, AIEvidence, AIWorkState, AIPreview, AIBatch } from './qaAITypes'
import { aiBatchProgress } from './qaAITypes'
import type { QAQuery } from './qaOps'
import type { AIScope } from './qaAI'
import { fetchAIStatus, fetchAIEvidence, previewAI, startAI, setAIAutomation, manageAIBatch } from './qaAI'
import { newOperationID } from './operationKey'
import { qaFieldColors } from './qaFieldColors'
export const aiKindLabels: Record<AIKind, string> = { evaluation: '字段分析', translation: '中文翻译' }
export const aiStateLabels: Record<string, string> = {
queued: '排队',
running: '执行中',
retry: '等待重试',
succeeded: '成功',
failed: '失败',
skipped: '跳过',
paused: '已暂停',
}
const stageLabels: Record<string, string> = {
queued: '排队',
preparing: '准备输入',
request: '请求模型',
validation: '校验输出',
saving: '保存结果',
completed: '完成',
waiting_retry: '等待重试',
paused: '已暂停',
failed: '失败',
lease_expired: '等待租约恢复',
}
const fieldLabels: Record<string, string> = {
is_correct: '是否正确',
product_category: '产品分类',
problem_type: '问题类型',
root_cause: '根因分析',
question_chinese: '中文问题',
}
const basisLabels: Record<string, string> = {
semantic_only: '仅语义判断(非事实核验)',
reference_evidence: '引用证据',
insufficient_evidence: '证据不足',
}
const reasonLabels: Record<string, string> = {
nonempty_or_protected: '已有非空值或人工保护',
legal_empty_root: '合法留空,已保存依据',
input_or_review_changed: '输入或人工版本变化',
configuration_changed_or_unverified: '配置已变更或未核验',
nothing_missing_or_not_ready: '无待补字段或输入未就绪',
input_review_or_configuration_changed: '输入、人工复核或配置已变化',
automation_disabled: '自动处理已关闭',
}
const errorText = (reason: unknown) => (reason instanceof Error ? reason.message : 'AI后台操作失败,请重试')
export function QAAIRequest({
scope,
label,
disabled,
onQueued,
}: {
scope: Omit<AIScope, 'kind'> | null
label: string
disabled?: boolean
onQueued?: () => void
}) {
const [preview, setPreview] = useState<AIPreview[] | null>(null),
[nonce, setNonce] = useState(''),
[busy, setBusy] = useState(false),
[error, setError] = useState<string | null>(null),
[message, setMessage] = useState<string | null>(null)
const queued = useRef(new Set<AIKind>())
const prepare = async () => {
if (!scope) return
setBusy(true)
setError(null)
setMessage(null)
try {
setPreview(
await Promise.all((['evaluation', 'translation'] as const).map((kind) => previewAI({ ...scope, kind })))
)
queued.current.clear()
setNonce(newOperationID())
} catch (reason) {
setError(errorText(reason))
} finally {
setBusy(false)
}
}
const confirm = async () => {
if (!preview) return
setBusy(true)
setError(null)
try {
for (const part of preview) {
if (part.eligible === 0 || queued.current.has(part.kind)) continue
await startAI(part.id, nonce + ':' + part.kind)
queued.current.add(part.kind)
}
setPreview(null)
setMessage('AI分析任务已持久保存;字段分析与中文翻译按实际缺口执行,关闭页面后继续。')
onQueued?.()
} catch (reason) {
setError((queued.current.size ? '部分任务已创建,重试只补未确认部分,不会重复入队。' : '') + errorText(reason))
if (queued.current.size) onQueued?.()
} finally {
setBusy(false)
}
}
return (
<span className="qa-ai-request">
<button type="button" onClick={() => void prepare()} disabled={disabled || busy || !scope}>
{busy ? '正在处理…' : label}
</button>
{preview ? (
<span className="qa-ai-confirm" role="dialog" aria-label={label + '范围确认'}>
<strong>AI分析:仅补当前范围的空白字段和缺失中文翻译</strong>
{preview.map((part) => (
<small key={part.kind}>
{aiKindLabels[part.kind]}:范围 {part.scope_total} 条,待补 {part.eligible} 条,跳过 {part.skipped} 条。
</small>
))}
<small>
两类任务独立计数,同一记录可能同时需要两项。仅发送问题、分析所需答案及已有引用片段,不发送人员/部门;不覆盖非空标签或人工结论。
</small>
<button type="button" disabled={busy} onClick={() => setPreview(null)}>
取消
</button>
<button
type="button"
disabled={busy || preview.every((part) => part.eligible === 0)}
onClick={() => void confirm()}
>
确认创建后台批次
</button>
</span>
) : null}
{message ? <small role="status">{message}</small> : null}
{error ? (
<small role="alert" className="error-message">
{error}
</small>
) : null}
</span>
)
}
function QAAIBatchControls({ batch, onChanged }: { batch: AIBatch; onChanged: () => void }) {
const [busy, setBusy] = useState(false),
[error, setError] = useState<string | null>(null)
const nonces = useRef(new Map<string, string>())
const act = async (action: 'pause' | 'resume' | 'retry') => {
setBusy(true)
setError(null)
let nonce = nonces.current.get(action)
if (!nonce) {
nonce = newOperationID()
nonces.current.set(action, nonce)
}
try {
await manageAIBatch(batch.id, action, nonce)
nonces.current.delete(action)
onChanged()
} catch (reason) {
setError(errorText(reason))
} finally {
setBusy(false)
}
}
return (
<div className="qa-ai-actions">
{batch.state === 'paused' ? (
<button type="button" disabled={busy} onClick={() => void act('resume')}>
恢复批次
</button>
) : batch.queued + batch.running + batch.retry > 0 ? (
<button type="button" disabled={busy} onClick={() => void act('pause')}>
暂停批次
</button>
) : null}
{batch.failed > 0 ? (
<button type="button" disabled={busy} onClick={() => void act('retry')}>
重试失败项
</button>
) : null}
<small>已发出的请求完成后暂停后续请求;共享任务如仍被其他活动批次需要,会继续执行。</small>
{error ? (
<small role="alert" className="error-message">
{error}
</small>
) : null}
</div>
)
}
export function QAAIWorkbench({
initial,
query,
filteredIDs,
filterRevision,
onStatus,
onRecordChanged,
}: {
initial?: AIStatus
query: QAQuery | null
filteredIDs?: string[]
filterRevision?: number
onStatus?: (status: AIStatus) => void
onRecordChanged?: (id: string) => void
}) {
const [status, setStatus] = useState<AIStatus | null>(initial ?? null),
[error, setError] = useState<string | null>(null),
[revision, setRevision] = useState(0),
[busy, setBusy] = useState(false),
[enable, setEnable] = useState<AIKind | null>(null)
const callbacks = useRef({ onStatus, onRecordChanged })
callbacks.current = { onStatus, onRecordChanged }
const previous = useRef<Map<string, string> | null>(null)
const statusSignature = useRef('')
useEffect(() => {
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout> | undefined
const load = async () => {
let active = false
try {
const next = await fetchAIStatus(controller.signal)
if (controller.signal.aborted) return
setStatus(next)
setError(null)
const signature = JSON.stringify(next)
if (signature !== statusSignature.current) {
statusSignature.current = signature
callbacks.current.onStatus?.(next)
}
if (previous.current) {
for (const task of next.recent_tasks) {
if (
task.state === 'succeeded' &&
previous.current.get(task.id) !== 'succeeded' &&
previous.current.has(task.id)
)
callbacks.current.onRecordChanged?.(task.record_id)
}
}
previous.current = new Map(next.recent_tasks.map((task) => [task.id, task.state]))
active =
next.settings.automatic_evaluation ||
next.settings.automatic_translation ||
next.queues.some((q) => q.queued + q.running + q.retry > 0)
} catch (reason) {
if (!controller.signal.aborted) setError(errorText(reason))
} finally {
if (!controller.signal.aborted) timer = setTimeout(() => void load(), active ? 3000 : 15000)
}
}
void load()
return () => {
controller.abort()
if (timer) clearTimeout(timer)
}
}, [revision])
const refresh = () => setRevision((value) => value + 1)
const toggle = async (kind: AIKind, enabled: boolean) => {
setBusy(true)
setError(null)
try {
await setAIAutomation(kind, enabled)
setEnable(null)
refresh()
} catch (reason) {
setError(errorText(reason))
} finally {
setBusy(false)
}
}
const ready = Boolean(status?.settings.verification === 'verified' && status.settings.storage_ready)
const filtered = Boolean(query?.filters && Object.keys(query.filters).length)
const scope = filtered
? filteredIDs?.length
? { ids: filteredIDs }
: null
: query
? { start: query.start, end: query.end, keyword: query.keyword }
: null
const scopeKey = query
? `${query.start}:${query.end}:${query.keyword}:${JSON.stringify(query.filters ?? {})}:${filteredIDs?.length ?? 'loading'}:${filterRevision ?? ''}`
: 'none'
return (
<section className="qa-ai-workbench" aria-label="问答后台任务">
<div className="qa-ai-actions">
<span>当前已执行筛选</span>
<QAAIRequest key={scopeKey} scope={scope} label="AI分析" disabled={!ready || !scope} onQueued={refresh} />
{status ? (
<small>
{status.worker_ready ? '执行器在线' : '执行器未在线,任务会持久保留'}
{!ready ? ';请先在系统设置 → 服务配置完成模型核验' : ''}
</small>
) : (
<small>读取后台状态…</small>
)}
</div>
<details className="qa-ai-progress">
<summary>
后台任务
{status
? ' · ' +
status.queues
.map((q) => `${aiKindLabels[q.kind]}:排队 ${q.queued} / 执行 ${q.running} / 失败 ${q.failed}`)
.join(';')
: ''}
</summary>
<p className="qa-ops-muted">
分析和翻译分别计数。自动队列没有固定分母,不显示百分比;手动批次的“已结束”包含成功、最终失败和跳过。
</p>
{status?.queues.map((q) => {
const enabled =
q.kind === 'evaluation' ? status.settings.automatic_evaluation : status.settings.automatic_translation
return (
<div key={q.kind} className="qa-ai-queue">
<strong>{aiKindLabels[q.kind]}</strong>
<span>{`排队 ${q.queued} · 执行 ${q.running} · 等待重试 ${q.retry} · 失败 ${q.failed} · 暂停 ${q.paused}`}</span>
<button
type="button"
disabled={busy || (!enabled && !ready)}
onClick={() => (enabled ? void toggle(q.kind, false) : setEnable(q.kind))}
>
{enabled ? '关闭自动处理' : '启用自动处理'}
</button>
</div>
)
})}
{enable ? (
<div role="dialog" className="qa-ai-confirm" aria-label="启用自动处理确认">
<strong>{`启用${aiKindLabels[enable]}自动处理?`}</strong>
<p>
首次启用只处理之后正常收录的新问答,不回填历史;重新启用会恢复暂停任务及之前启用后的积压。已有标签和人工结论不会被覆盖,原问答只发送给已配置的模型。
</p>
<button type="button" disabled={busy} onClick={() => setEnable(null)}>
取消
</button>
<button type="button" disabled={busy} onClick={() => void toggle(enable, true)}>
确认启用
</button>
</div>
) : null}
{status?.batches.map((batch) => {
const progress = aiBatchProgress(batch)
return (
<article key={batch.id} className="qa-ai-batch">
<strong>
{aiKindLabels[batch.kind]} · {batch.id}
</strong>
<span>{`已结束 ${progress.finished}/${batch.total}${progress.percent === null ? '' : `(${progress.percent}%)`};成功 ${batch.succeeded} / 失败 ${batch.failed} / 跳过 ${batch.skipped} / 执行 ${batch.running} / 排队 ${batch.queued} / 等待重试 ${batch.retry} / 暂停 ${batch.paused}`}</span>
{batch.failed > 0 ? (
<small className="error-message">已结束不代表全部成功,请查看失败原因后重试。</small>
) : null}
<QAAIBatchControls batch={batch} onChanged={refresh} />
</article>
)
})}
</details>
{error ? (
<p role="alert" className="error-banner">
{error}(保留上次读数,未伪装为零)
<button type="button" onClick={refresh}>
重试状态
</button>
</p>
) : null}
</section>
)
}
export function QAAITaskBadges({ tasks }: { tasks: AIWorkState[] }) {
return (
<>
{tasks.map((task) => (
<small key={task.kind} className={'qa-ai-task qa-ai-task-' + task.state}>
{aiKindLabels[task.kind]}:{aiStateLabels[task.state] ?? task.state}
</small>
))}
</>
)
}
function TaskPhase({ task }: { task: AIWorkState }) {
const [now, setNow] = useState(Date.now())
useEffect(() => {
if (task.state !== 'running') return
const timer = setInterval(() => setNow(Date.now()), 1000)
return () => clearInterval(timer)
}, [task.state])
const elapsed =
task.state === 'running' && task.started_at
? Math.max(0, Math.floor((now - Date.parse(task.started_at)) / 1000))
: null
return (
<p>
{`${aiKindLabels[task.kind]}:${stageLabels[task.stage] ?? task.stage}(${aiStateLabels[task.state] ?? task.state}),尝试 ${task.attempt}`}{' '}
{elapsed === null ? '' : `· 已等待 ${elapsed} 秒`}
{task.error_code ? `;错误:${task.error_code}` : ''}
{task.skip_reason ? `;${reasonLabels[task.skip_reason] ?? task.skip_reason}` : ''}
</p>
)
}
export function QAAIEvidenceView({ evidence }: { evidence: AIEvidence[] }) {
return (
<section className="qa-ai-evidence" aria-label="字段结论与依据">
<h4>字段结论与依据</h4>
{evidence.length === 0 ? (
<p className="qa-ops-muted">
未发现此记录的AI评估依据。原历史标签、源标签与人工结论保留原来源,不补造理由或引用。
</p>
) : null}
{evidence.map((work, index) => (
<details key={work.id} open={index === 0}>
<summary>
{aiKindLabels[work.kind]} · {aiStateLabels[work.state] ?? work.state} ·{' '}
{new Date(work.updated_at).toLocaleString('zh-CN', { hour12: false })}
</summary>
<TaskPhase task={work} />
{work.result.fields
? Object.entries(work.result.fields).map(([field, result]) => (
<article key={field} className="qa-ai-field-evidence">
<strong>
{fieldLabels[field] ?? field}:
<span className="qa-field-tag" style={qaFieldColors(field, result.value)}>
{result.value || '留空'}
</span>
</strong>
<p>{result.reason}</p>
<small>
{basisLabels[result.basis] ?? result.basis};
{Object.hasOwn(work.applied_fields, field)
? '已回填'
: (reasonLabels[work.skipped_fields[field]] ?? '未回填(保留原结论)')}
</small>
{result.quotes.map((quote, i) => (
<blockquote key={i}>
<small>
{quote.source === 'question'
? '原始问题'
: quote.source === 'answer'
? '原答案'
: `引用片段 ${quote.reference_index + 1}`}
</small>
<p>{quote.text}</p>
</blockquote>
))}
</article>
))
: null}
{work.result.local_derivations
? Object.entries(work.result.local_derivations).map(([field, proof]) => (
<article key={field} className="qa-ai-field-evidence">
<strong>
{field === 'language'
? '语言'
: field === 'question_chinese'
? '中文问题'
: (fieldLabels[field] ?? field)}
:{proof.value}
</strong>
<p>{proof.reason}</p>
<small>
本地规则/历史复用(非模型);
{Object.hasOwn(work.applied_fields, field) ? '已回填' : '未回填,保留当前值'}
</small>
</article>
))
: null}
{work.result.question_chinese ? (
<article>
<strong>中文问题</strong>
<p>{work.result.question_chinese}</p>
<small>
{Object.hasOwn(work.applied_fields, 'question_chinese') ? '已回填' : '未回填,保留当前原文/译文'}
</small>
</article>
) : null}
<details>
<summary>模型、规则版本与输入指纹</summary>
<dl>
<dt>{work.actual_model === 'local-rule-history-v1' ? '结论来源(非模型)' : '实际返回模型'}</dt>
<dd>
{work.actual_model === 'local-rule-history-v1'
? '本地规则/历史复用(非模型)'
: work.actual_model || '尚未返回'}
</dd>
<dt>配置修订</dt>
<dd>{work.config_revision === 0 ? '外部受控回填,未使用服务模型配置' : work.config_revision}</dd>
<dt>提示词版本</dt>
<dd>{work.prompt_version}</dd>
<dt>正式字典版本</dt>
<dd>{work.dictionary_version}</dd>
<dt>输入指纹</dt>
<dd className="qa-ai-hash">{work.input_hash}</dd>
</dl>
</details>
</details>
))}
</section>
)
}
export function QAAIRecordEvidence({
recordID,
revision,
onQueued,
}: {
recordID: string
revision?: string
onQueued?: () => void
}) {
const [evidence, setEvidence] = useState<AIEvidence[]>([]),
[error, setError] = useState<string | null>(null),
[counter, setCounter] = useState(0),
[loading, setLoading] = useState(true)
useEffect(() => {
const controller = new AbortController()
setError(null)
setLoading(true)
void fetchAIEvidence(recordID, controller.signal)
.then((value) => {
if (!controller.signal.aborted) setEvidence(value)
setLoading(false)
})
.catch((reason) => {
if (!controller.signal.aborted) {
setError(errorText(reason))
setLoading(false)
}
})
return () => controller.abort()
}, [recordID, revision, counter])
const refresh = () => {
setCounter((value) => value + 1)
onQueued?.()
}
return (
<>
<div className="qa-ai-actions">
<QAAIRequest key={recordID} scope={{ ids: [recordID] }} label="AI分析" onQueued={refresh} />
</div>
{error ? (
<p role="alert" className="error-banner">
{error}
</p>
) : null}
{loading ? <p role="status">字段结论与依据读取中…</p> : <QAAIEvidenceView evidence={evidence} />}
</>
)
}