feat(qaops): 接入真实模型补缺任务与总表看板
build / build (push) Successful in 1m12s

按已确认需求提供独立安全模型配置、真实探测、正式字典字段评估与原问题译中,持久批次支持只补空白、暂停恢复、有限重试、幂等和逐字段依据。覆盖固定规则、本地语言、组织关联与主表有效看板共用治理侧读模型,保留源生产和冻结历史。

验证:完整 make verify 退出0,702项Go与329项前端通过;默认118项外部/隔离集成明确跳过,另跑完整镜像及组织隔离PG竞态。12并发、输入漂移、过期租约、暂停/恢复及有限重试通过。用户授权的百炼 deepseek-v4.1-flash 完成真实后台与浏览器评估/翻译;552行、16列、11块看板及完整PNG、独立配置页测试/保存、重开恢复和零JS异常通过。仅非业务样本外发,自动处理关闭,原payload不变。

上线前治理库已做导出快照原生备份并真实恢复,60表行数与17个QA表内容哈希一致;不修改DobotAI生产或隧道。本提交时尚未部署,线上验收须独立完成。
This commit is contained in:
姚章浩
2026-10-19 14:29:49 +08:00
parent 330fd12b3f
commit 533db535f1
83 changed files with 5769 additions and 138 deletions
+111
View File
@@ -0,0 +1,111 @@
import { it, expect } from 'vitest'
import { renderToStaticMarkup } from 'react-dom/server'
import { QAAIWorkbench, QAAIEvidenceView } from './QAAI'
import type { AIStatus, AIEvidence } from './qaAITypes'
const status: AIStatus = {
settings: {
revision: 1,
base_url: 'https://model.example.invalid/v1',
model: 'fixture',
key_configured: true,
verification: 'verified',
checked_at: null,
automatic_evaluation: true,
automatic_translation: false,
storage_ready: true,
},
worker_ready: true,
queues: [{ kind: 'evaluation', queued: 2, running: 1, retry: 0, failed: 1, paused: 0, succeeded: 2, skipped: 0 }],
batches: [],
recent_tasks: [],
recent_tasks_limited: false,
}
it('shows open-ended automatic queue counts without fabricating a percentage', () => {
const html = renderToStaticMarkup(
<QAAIWorkbench
initial={status}
query={{ start: '2026-10-05T00:00:00Z', end: '2026-10-12T00:00:00Z', keyword: 'executed-query', cursor: '' }}
/>
)
for (const value of ['补缺评估', '补缺中文翻译', '当前已执行筛选', '后台任务', '排队 2', '执行 1', '失败 1'])
expect(html).toContain(value)
expect(html).not.toContain('100%')
})
it('exposes persistent pause, resume and failed-only retry without claiming completion is success', () => {
const batches: AIStatus['batches'] = [
{
id: 'active-batch',
kind: 'evaluation',
state: 'active',
total: 2,
succeeded: 0,
failed: 1,
skipped: 0,
running: 0,
queued: 1,
retry: 0,
paused: 0,
created_at: '2026-10-19T00:00:00Z',
},
{
id: 'paused-batch',
kind: 'translation',
state: 'paused',
total: 1,
succeeded: 0,
failed: 0,
skipped: 0,
running: 0,
queued: 0,
retry: 0,
paused: 1,
created_at: '2026-10-19T00:00:00Z',
},
]
const html = renderToStaticMarkup(<QAAIWorkbench initial={{ ...status, batches }} query={null} />)
for (const value of ['暂停批次', '恢复批次', '重试失败项', '已结束不代表全部成功', '已发出的请求完成后暂停后续请求'])
expect(html).toContain(value)
})
it('renders original evidence quotes, actual model/version and applied-versus-skipped provenance', () => {
const evidence: AIEvidence = {
id: 'w',
record_id: 'r',
kind: 'evaluation',
state: 'succeeded',
stage: 'completed',
attempt: 1,
error_code: '',
skip_reason: '',
started_at: '2026-10-19T00:00:00Z',
updated_at: '2026-10-19T00:00:01Z',
input_hash: 'a'.repeat(64),
config_revision: 1,
prompt_version: 'prompt-fixture-v1',
dictionary_version: 'dict-fixture-v1',
actual_model: 'actual-fixture-model',
result: {
fields: {
product_category: {
value: 'MG400',
basis: 'semantic_only',
reason: '原问题明确包含型号',
quotes: [{ source: 'question', text: 'MG400 怎么连接?', reference_index: 0 }],
},
},
},
applied_fields: { product_category: 'MG400' },
skipped_fields: {},
}
const html = renderToStaticMarkup(<QAAIEvidenceView evidence={[evidence]} />)
for (const value of [
'字段结论与依据',
'原问题明确包含型号',
'MG400 怎么连接?',
'仅语义判断',
'actual-fixture-model',
'prompt-fixture-v1',
'dict-fixture-v1',
'已回填',
])
expect(html).toContain(value)
})
+514
View File
@@ -0,0 +1,514 @@
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: AIScope | 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 prepare = async () => {
if (!scope) return
setBusy(true)
setError(null)
setMessage(null)
try {
setPreview(await previewAI(scope))
setNonce(newOperationID())
} catch (reason) {
setError(errorText(reason))
} finally {
setBusy(false)
}
}
const confirm = async () => {
if (!preview) return
setBusy(true)
setError(null)
try {
await startAI(preview.id, nonce)
setPreview(null)
setMessage('批次已持久保存;关闭页面后继续执行。')
onQueued?.()
} catch (reason) {
setError(errorText(reason))
} 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>{`${aiKindLabels[preview.kind]}:范围 ${preview.scope_total} 条,实际待补 ${preview.eligible} 条,跳过 ${preview.skipped} 条。`}</strong>
<small>
{preview.kind === 'evaluation'
? '只向已配置模型发送待补记录的问题、答案及获准引用,不发送人员/部门信息。'
: '只发送待补记录的原始问题,不翻译或发送答案。'}
仅补空白,不覆盖既有标签或人工结论。
</small>
<button type="button" disabled={busy} onClick={() => setPreview(null)}>
取消
</button>
<button type="button" disabled={busy || preview.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,
onStatus,
onRecordChanged,
}: {
initial?: AIStatus
query: QAQuery | null
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)
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)
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 scope = (kind: AIKind): AIScope | null =>
query ? { kind, start: query.start, end: query.end, keyword: query.keyword } : null
const scopeKey = query ? `${query.start}:${query.end}:${query.keyword}` : 'none'
return (
<section className="qa-ai-workbench" aria-label="问答后台任务">
<div className="qa-ai-actions">
<span>当前已执行筛选</span>
<QAAIRequest
key={'evaluation:' + scopeKey}
scope={scope('evaluation')}
label="补缺评估"
disabled={!ready}
onQueued={refresh}
/>
<QAAIRequest
key={'translation:' + scopeKey}
scope={scope('translation')}
label="补缺中文翻译"
disabled={!ready}
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.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>实际返回模型</dt>
<dd>{work.actual_model || '尚未返回'}</dd>
<dt>配置修订</dt>
<dd>{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 + ':evaluation'}
scope={{ kind: 'evaluation', ids: [recordID] }}
label="本条补缺评估"
onQueued={refresh}
/>
<QAAIRequest
key={recordID + ':translation'}
scope={{ kind: 'translation', ids: [recordID] }}
label="本条补缺中文翻译"
onQueued={refresh}
/>
</div>
{error ? (
<p role="alert" className="error-banner">
{error}
</p>
) : null}
{loading ? <p role="status">字段结论与依据读取中…</p> : <QAAIEvidenceView evidence={evidence} />}
</>
)
}
+2 -2
View File
@@ -19,7 +19,7 @@ const base: QAMirrorStatus = {
describe('local Q&A synchronization strip', () => {
it('shows pending first import rather than a successfully empty dataset', () => {
const html = renderToStaticMarkup(<QAMirrorSyncView status={base} error="" submitting={false} onSync={vi.fn()} />)
expect(html).toContain('本地数据库')
expect(html).not.toContain('本地数据库')
expect(html).toContain('首次同步尚未完成')
expect(html).toContain('立即同步')
expect(html).not.toContain('每 5 分钟后台同步 · 查询不请求远端')
@@ -36,7 +36,7 @@ describe('local Q&A synchronization strip', () => {
error_code: 'mirror_source_unavailable',
}
const html = renderToStaticMarkup(<QAMirrorSyncView status={status} error="" submitting={false} onSync={vi.fn()} />)
expect(html).toContain('639')
expect(html).not.toContain('已同步 639 条')
expect(html).toContain('保留上次成功数据')
expect(html).not.toContain('不承诺实时源快照')
})
+1 -4
View File
@@ -13,11 +13,8 @@ export function QAMirrorSyncView(p: ViewProps) {
const s = p.status
const active = mirrorSyncActive(s)
return (
<section className="qa-mirror-sync" aria-label="问答本地数据库与同步状态">
<section className="qa-mirror-sync" aria-label="问答同步状态">
<div className="qa-mirror-sync-line">
<strong>本地数据库</strong>
{s?.ready ? <span>已同步 {s.records} 条</span> : null}
<button type="button" onClick={p.onSync} disabled={p.submitting || !s?.worker_ready || active}>
{p.submitting ? '正在入队…' : active ? '后台同步中…' : '立即同步'}
</button>
+40
View File
@@ -0,0 +1,40 @@
import { it, expect } from 'vitest'
import { renderToStaticMarkup } from 'react-dom/server'
import { QAModelSettings, qaAIKeyEntryAllowed } from './QAModelSettings'
it('provides independent write-only model settings and does not equate save with bulk execution', () => {
const html = renderToStaticMarkup(
<QAModelSettings
initial={{
revision: 1,
base_url: 'https://model.example.invalid/v1',
model: 'fixture',
key_configured: true,
verification: 'verified',
checked_at: '2026-10-19T00:00:00Z',
automatic_evaluation: false,
automatic_translation: false,
storage_ready: true,
}}
/>
)
for (const text of [
'问答评估模型',
'API 基础地址',
'模型名称',
'API Key',
'type="password"',
'测试连接',
'保存配置',
'保留现有密钥',
'更换密钥',
'清除密钥',
'保存不会启动全量评估',
])
expect(html).toContain(text)
expect(html).not.toContain('value="fixture-only-api-key"')
})
it('permits new-key entry only on HTTPS or browser-local loopback origins', () => {
expect(qaAIKeyEntryAllowed({ protocol: 'https:', hostname: 'kg.example.invalid' })).toBe(true)
expect(qaAIKeyEntryAllowed({ protocol: 'http:', hostname: 'localhost' })).toBe(true)
expect(qaAIKeyEntryAllowed({ protocol: 'http:', hostname: '192.168.1.2' })).toBe(false)
})
+184
View File
@@ -0,0 +1,184 @@
import { useEffect, useState } from 'react'
import type { AISettings } from './qaAITypes'
import type { AISettingsInput } from './qaAI'
import { fetchAISettings, saveAISettings, testAISettings } from './qaAI'
export function qaAIKeyEntryAllowed(location: { protocol: string; hostname: string }) {
return location.protocol === 'https:' || ['localhost', '127.0.0.1', '[::1]', '::1'].includes(location.hostname)
}
const verificationLabels: Record<AISettings['verification'], string> = {
not_configured: '未配置可用密钥',
verified: '已通过真实连接测试',
unverified: '未完成核验,未启用调用',
rejected: '服务已拒绝,调用已阻断',
}
export function QAModelSettings({ initial }: { initial?: AISettings }) {
const [settings, setSettings] = useState(initial ?? null),
[base, setBase] = useState(initial?.base_url ?? ''),
[model, setModel] = useState(initial?.model ?? '')
const [keyAction, setKeyAction] = useState<AISettingsInput['key_action']>(
initial?.key_configured ? 'keep' : 'replace'
),
[key, setKey] = useState('')
const [busy, setBusy] = useState(false),
[error, setError] = useState<string | null>(null),
[message, setMessage] = useState<string | null>(null)
const secure = typeof window !== 'undefined' && qaAIKeyEntryAllowed(window.location)
useEffect(() => {
if (initial) return
const controller = new AbortController()
void fetchAISettings(controller.signal)
.then((value) => {
setSettings(value)
setBase(value.base_url)
setModel(value.model)
setKeyAction(value.key_configured ? 'keep' : 'replace')
})
.catch((reason) => {
if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : '模型配置读取失败')
})
return () => controller.abort()
}, [initial])
const dirty = () => {
setMessage(null)
setError(null)
}
const run = async (test: boolean) => {
if (!settings) return
setBusy(true)
setMessage(null)
setError(null)
const input: AISettingsInput = {
base_revision: settings.revision,
base_url: base,
model,
key_action: keyAction,
...(keyAction === 'replace' ? { api_key: key } : {}),
}
try {
const result = await (test ? testAISettings(input) : saveAISettings(input))
if (!test) {
setSettings(result)
setKey('')
setKeyAction(result.key_configured ? 'keep' : 'replace')
}
setMessage(
(test ? '连接测试:' : '配置已保存:') +
verificationLabels[result.verification] +
(test ? ';未保存、未启动任务' : ';保存不会启动全量评估')
)
} catch (reason) {
setError(reason instanceof Error ? reason.message : '模型配置操作失败')
} finally {
setBusy(false)
}
}
const ready =
Boolean(settings) &&
!busy &&
(keyAction !== 'replace' || (secure && Boolean(key) && Boolean(settings?.storage_ready)))
return (
<section className="qa-ai-model-settings" aria-label="问答评估模型">
<h3>问答评估模型</h3>
<p className="qa-ops-muted">
四字段分析和中文问题翻译共用此独立配置。保存不会启动全量评估,也不会自动开启新增处理。
</p>
{settings ? (
<>
<p>
{verificationLabels[settings.verification]};密钥:{settings.key_configured ? '已配置(不回显)' : '未配置'}
;自动分析/翻译:{settings.automatic_evaluation ? '开' : '关'} /{' '}
{settings.automatic_translation ? '开' : '关'}
</p>
<div className="safe-setting-grid">
<label>
API 基础地址
<input
value={base}
onChange={(event) => {
setBase(event.target.value)
dirty()
}}
placeholder="https://模型服务地址/v1"
autoComplete="off"
disabled={busy}
/>
<small>OpenAI 兼容基础地址,不含 /chat/completions;更换地址须重新录入密钥。</small>
</label>
<label>
模型名称
<input
value={model}
onChange={(event) => {
setModel(event.target.value)
dirty()
}}
placeholder="服务商提供的模型标识"
autoComplete="off"
disabled={busy}
/>
</label>
<label>
密钥操作
<select
value={keyAction}
onChange={(event) => {
setKeyAction(event.target.value as AISettingsInput['key_action'])
setKey('')
dirty()
}}
disabled={busy}
>
<option value="keep">保留现有密钥</option>
<option value="replace">更换密钥</option>
<option value="clear">清除密钥并停用AI</option>
</select>
</label>
<label>
API Key
<input
type="password"
name="qa_ai_key"
value={key}
onChange={(event) => {
setKey(event.target.value)
dirty()
}}
autoComplete="new-password"
spellCheck={false}
placeholder={settings.key_configured ? '已配置;保留时不必填写' : '仅用于此治理平台'}
disabled={busy || keyAction !== 'replace' || !secure || !settings.storage_ready}
/>
</label>
</div>
{!secure ? (
<p className="qa-ops-warning">
当前不是安全密钥录入连接。请使用有效HTTPS或本机 localhost
地址录入新密钥;不会通过失配证书或普通局域网HTTP发送新密钥。
</p>
) : null}
{!settings.storage_ready ? (
<p className="qa-ops-warning">
独立安全存储未就绪,请配置服务器的 QA_AI_MASTER_KEY_FILE;不会读取 Hermes 密钥。
</p>
) : null}
<div className="qa-ai-actions">
<button type="button" disabled={!ready || keyAction === 'clear'} onClick={() => void run(true)}>
{busy ? '正在真实核验…' : '测试连接'}
</button>
<button type="button" disabled={!ready} onClick={() => void run(false)}>
保存配置
</button>
</div>
</>
) : !error ? (
<p role="status">读取独立模型配置…</p>
) : null}
{message ? <p role="status">{message}</p> : null}
{error ? (
<p className="error-banner" role="alert">
{error}
</p>
) : null}
</section>
)
}
+65
View File
@@ -50,6 +50,71 @@ const props = {
}
describe('QA operations workbench', () => {
it('shows each persisted AI task in the existing operation cell and explains positive master coverage', () => {
const withTasks = {
...item,
background_tasks: [
{
id: 'w',
record_id: item.id,
kind: 'evaluation' as const,
state: 'running' as const,
stage: 'request',
attempt: 1,
error_code: '',
skip_reason: '',
started_at: '2026-10-19T00:00:00Z',
updated_at: '2026-10-19T00:00:01Z',
},
],
}
const detail = {
...item,
record_origin: 'dobotai_2_0' as const,
coverage: { state: 'checked' as const, verdict: 'covered' as const, rule_version: 'master-answer-substring-v2' },
}
const html = renderToStaticMarkup(
<QAOperationsView {...props} page={{ ...page, items: [withTasks] }} detail={detail} />
)
expect(html).toContain('字段分析:执行中')
expect(html).toContain('已覆盖:成功读取且非空答案未包含')
expect(html).toContain('字段结论与依据')
})
it('hides only the two requested advisory warnings, not real errors', () => {
const html = renderToStaticMarkup(
<QAOperationsView
{...props}
status={{
state: 'connected',
code: '',
warnings: ['database_temp_enabled', 'database_transport_unencrypted', 'fixture_other_warning'],
read_only: true,
source_version: '2.0',
channel: 'dingtalk',
}}
error="fixture real read failure"
/>
)
expect(html).not.toContain('数据库仍允许临时对象')
expect(html).not.toContain('数据库连接未启用 TLS')
expect(html).toContain('数据源有待审核的安全告警')
expect(html).toContain('fixture real read failure')
})
it('keeps a name-only person summary with the original available separately', () => {
const detail = { ...item, trigger_person: JSON.stringify({ name: '示例姓名', unionId: 'fixture-union' }) }
const html = renderToStaticMarkup(<QAOperationsView {...props} detail={detail} />)
expect(html).toContain('<dd>示例姓名</dd>')
expect(html).toContain('原始人员信息')
expect(html).toContain('fixture-union')
})
it('provides a row-level detail target and categorical color tags without adding business columns', () => {
const html = renderToStaticMarkup(<QAOperationsView {...props} />)
expect(html).toContain('data-qa-row="fixture"')
expect(html).toContain('双击行查看详情')
expect(html).toContain('qa-field-tag')
})
it('uses the four requested destinations in their fixed order', () => {
const html = renderToStaticMarkup(<QAOperationsTabs view="records" onChange={vi.fn()} />)
const labels = ['问题流水', '问题统计看板', '区域配置', '周报生成']
+153 -61
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { FormEvent } from 'react'
import { useOptionalAuth } from './auth'
import { fetchQARecord, fetchAllQARecords, fetchQAStatus, qaCellValue, qaColumns } from './qaOps'
@@ -8,11 +8,14 @@ import { QARegions } from './QARegions'
import { QADashboard } from './QADashboard'
import { QAWeekly } from './QAWeekly'
import { QAQualityEditor } from './QAQuality'
import { qaFieldColors, qaTagColumns } from './qaFieldColors'
import { qualityLabels } from './qaQuality'
import { usageLabels } from './qaUsage'
import { QAWeekPicker } from './QAWeekPicker'
import { QAAnswerMarkdown } from './QAAnswerMarkdown'
import { QAMirrorSync } from './QAMirrorSync'
import { QAAIWorkbench, QAAIRecordEvidence, QAAITaskBadges } from './QAAI'
import type { AIStatus, AIWorkState } from './qaAITypes'
import { currentQAWeek, qaDateTimeToISO, qaWeekQueryRange } from './qaWeeks'
export type QAOpsView = 'records' | 'dashboard' | 'regions' | 'weekly'
@@ -35,6 +38,7 @@ export function QAOperationsTabs({ view, onChange }: { view: QAOpsView; onChange
)
}
interface ViewProps {
taskUpdates?: AIWorkState[]
onQualitySaved?: (record: QARecord) => void
onReloadDetail?: () => void
page: QARecordPage | null
@@ -62,9 +66,76 @@ const statusLabels: Record<string, string> = {
}
const sourceCoverageLabels: Record<string, string> = { covered: '已覆盖', uncovered: '未覆盖' }
function tasksFor(item: QARecord, updates: AIWorkState[] | undefined) {
const byKind = new Map((item.background_tasks ?? []).map((task) => [task.kind, task]))
for (const task of updates ?? []) {
const previous = byKind.get(task.kind)
if (!previous || previous.id === task.id || Date.parse(task.updated_at) > Date.parse(previous.updated_at))
byKind.set(task.kind, task)
}
return [...byKind.values()].sort((a, b) => a.kind.localeCompare(b.kind))
}
const QARow = memo(
function QARow({
item,
tasks,
onSelect,
}: {
item: QARecord
tasks: AIWorkState[]
signature: string
onSelect: (id: string) => void
}) {
return (
<tr
data-qa-row={item.id}
onDoubleClick={(event) => {
if (!(event.target as HTMLElement).closest('button,a,input,select,textarea,summary')) onSelect(item.id)
}}
>
{qaColumns.map(({ key }) => (
<td
key={key}
className={
key === 'answer' || key === 'question' || key === 'question_chinese' || key === 'department'
? 'qa-ops-text-cell'
: ''
}
>
<span
className={qaTagColumns.has(key) ? 'qa-field-tag' : key === 'trigger_person' ? 'qa-person-name' : ''}
style={qaTagColumns.has(key) ? qaFieldColors(key, qaCellValue(item, key) ?? '—') : undefined}
>
{qaCellValue(item, key) ?? '—'}
</span>
</td>
))}
<td>
<button type="button" onClick={() => onSelect(item.id)} aria-label={`查看问答 ${item.id} 的详情`}>
详情
</button>
{item.quality ? <small className="qa-quality-state">{qualityLabels[item.quality.state]}</small> : null}
<QAAITaskBadges tasks={tasks} />
</td>
</tr>
)
},
(before, after) =>
before.item === after.item && before.signature === after.signature && before.onSelect === after.onSelect
)
export function QAOperationsView(props: ViewProps) {
const page = props.page
const columns = qaColumns
const updates = useMemo(() => {
const map = new Map<string, AIWorkState[]>()
for (const task of props.taskUpdates ?? []) {
const list = map.get(task.record_id) ?? []
if (!list.some((previous) => previous.kind === task.kind)) list.push(task)
map.set(task.record_id, list)
}
return map
}, [props.taskUpdates])
const detail = props.detail
const showDrawer = Boolean(detail || props.detailLoading || props.detailError)
return (
@@ -77,13 +148,16 @@ export function QAOperationsView(props: ViewProps) {
? `共 ${page.total} 条 · 已展示 ${page.items.length} 条`
: '尚未读取问答'}
</span>
<small className="qa-ops-muted">双击行查看详情</small>
</div>
{props.status?.warnings.map((warning) => (
<p className="qa-ops-warning" key={warning}>
{warningLabels[warning] ?? '数据源有待审核的安全告警'}
</p>
))}
{props.status?.warnings
.filter((warning) => !['database_temp_enabled', 'database_transport_unencrypted'].includes(warning))
.map((warning) => (
<p className="qa-ops-warning" key={warning}>
{warningLabels[warning] ?? '数据源有待审核的安全告警'}
</p>
))}
{props.error ? (
<div className="error-banner" role="alert">
{props.error}{' '}
@@ -104,43 +178,18 @@ export function QAOperationsView(props: ViewProps) {
</tr>
</thead>
<tbody>
{page.items.map((item) => (
<tr key={item.id}>
{columns.map(({ key }) => (
<td
key={key}
className={
key === 'answer' || key === 'question' || key === 'question_chinese' || key === 'department'
? 'qa-ops-text-cell'
: ''
}
>
<span
className={
key === 'coverage' &&
(item.quality?.effective.coverage ?? item.coverage.verdict) === 'uncovered'
? 'qa-ops-uncovered'
: ''
}
>
{qaCellValue(item, key) ?? '—'}
</span>
</td>
))}
<td>
<button
type="button"
onClick={() => props.onSelect(item.id)}
aria-label={`查看问答 ${item.id} 的详情`}
>
详情
</button>
{item.quality ? (
<small className="qa-quality-state">{qualityLabels[item.quality.state]}</small>
) : null}
</td>
</tr>
))}
{page.items.map((item) => {
const tasks = tasksFor(item, updates.get(item.id))
return (
<QARow
key={item.id}
item={item}
tasks={tasks}
signature={JSON.stringify(tasks)}
onSelect={props.onSelect}
/>
)
})}
</tbody>
</table>
</div>
@@ -252,8 +301,12 @@ export function QAOperationsView(props: ViewProps) {
<dt>问答状态</dt>
<dd>{statusLabels[detail.status] ?? detail.status}</dd>
<dt>流程触发人员信息</dt>
<dd>{detail.trigger_person || '未记录'}</dd>
<dd>{qaCellValue(detail, 'trigger_person') || '未记录'}</dd>
</dl>
<details>
<summary>原始人员信息</summary>
<pre>{detail.master_fields?.trigger_person ?? detail.trigger_person ?? '未记录'}</pre>
</details>
<h4>原始问题</h4>
<div className="qa-ops-full-text">{detail.question || '无文本问题'}</div>
<h4>AI答案</h4>
@@ -262,7 +315,11 @@ export function QAOperationsView(props: ViewProps) {
<p>
{detail.coverage.verdict === 'uncovered'
? '未覆盖:答案包含“暂无已发布”,引用不能抵消这一结果。'
: '待评估:未命中“暂无已发布”不代表已覆盖。'}
: detail.coverage.verdict === 'covered'
? '已覆盖:成功读取且非空答案未包含“暂无已发布”。'
: detail.coverage.rule_version === 'master-answer-substring-v2'
? '待判定:答案为空或读取未完成,未据未命中标记判定已覆盖。'
: '旧版规则只检测未覆盖标记,尚无已覆盖结论。'}
</p>
<p className="qa-ops-muted">规则:{detail.coverage.rule_version}</p>
<h4>源端覆盖(仅对照)</h4>
@@ -271,6 +328,14 @@ export function QAOperationsView(props: ViewProps) {
{detail.source_coverage.evaluator_version || '无版本'}
</p>
<p className="qa-ops-muted">{detail.source_coverage.reason_code || '未记录判定原因'}</p>
<QAAIRecordEvidence
key={detail.id + ':ai'}
recordID={detail.id}
revision={updates
.get(detail.id)
?.map((task) => task.updated_at)
.join(':')}
/>
{detail.quality ? (
<QAQualityEditor
key={detail.id}
@@ -326,6 +391,11 @@ export function QAOperations() {
const [loading, setLoading] = useState(false)
const [revision, setRevision] = useState(0)
const [qualityRevision, setQualityRevision] = useState(0)
const [aiStatus, setAIStatus] = useState<AIStatus | null>(null)
const generation = useRef(0)
const freshAI = useRef(new Map<string, QARecord>())
const viewRef = useRef(view)
viewRef.current = view
const [mirrorChanged, setMirrorChanged] = useState(false)
const [detail, setDetail] = useState<QARecord | null>(null)
const [detailLoading, setDetailLoading] = useState(false)
@@ -354,6 +424,8 @@ export function QAOperations() {
return
}
const controller = new AbortController()
generation.current += 1
freshAI.current.clear()
detailRequest.current?.abort()
setLoading(true)
setError(null)
@@ -371,7 +443,8 @@ export function QAOperations() {
if (!controller.signal.aborted) setProgress({ loaded, total })
})
.then((result) => {
if (!controller.signal.aborted) setPage(result)
if (!controller.signal.aborted)
setPage({ ...result, items: result.items.map((item) => freshAI.current.get(item.id) ?? item) })
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : '问答读取失败')
@@ -401,7 +474,7 @@ export function QAOperations() {
setError(reason instanceof Error ? reason.message : '时间格式无效')
}
}
const select = async (id: string) => {
const select = useCallback(async (id: string) => {
detailRequest.current?.abort()
returnFocus.current = document.activeElement as HTMLElement | null
const controller = new AbortController()
@@ -417,7 +490,22 @@ export function QAOperations() {
} finally {
if (!controller.signal.aborted) setDetailLoading(false)
}
}
}, [])
const refreshAIRecord = useCallback((id: string) => {
if (viewRef.current === 'dashboard') {
setQualityRevision((value) => value + 1)
return
}
const version = generation.current
void fetchQARecord(id, undefined, 'master')
.then((fresh) => {
if (version !== generation.current) return
freshAI.current.set(id, fresh)
setPage((old) => (old ? { ...old, items: old.items.map((item) => (item.id === id ? fresh : item)) } : old))
setDetail((old) => (old?.id === id ? fresh : old))
})
.catch(() => {})
}, [])
const close = () => {
if (mirrorChanged) {
setMirrorChanged(false)
@@ -445,17 +533,6 @@ export function QAOperations() {
<QAOperationsTabs view={view} onChange={setView} />
{queryView ? (
<>
<QAMirrorSync
onChanged={() => {
if (detail || detailLoading) {
setMirrorChanged(true)
return
}
setQuery((q) => (q ? { ...q } : q))
setRevision((v) => v + 1)
setQualityRevision((v) => v + 1)
}}
/>
{mirrorChanged ? <p className="qa-ops-warning">数据已更新,关闭详情后刷新。</p> : null}
<form className="qa-ops-query" onSubmit={submit}>
<QAWeekPicker
@@ -500,7 +577,7 @@ export function QAOperations() {
<input
type="search"
maxLength={200}
placeholder="检索原始问题"
placeholder="检索原始/中文问题"
value={draft.keyword}
onChange={(e) => setDraft({ ...draft, keyword: e.target.value })}
/>
@@ -508,7 +585,21 @@ export function QAOperations() {
<button type="submit" disabled={loading}>
查询
</button>
<QAMirrorSync
onChanged={() => {
if (detail || detailLoading) {
setMirrorChanged(true)
return
}
setQuery((q) => (q ? { ...q } : q))
setRevision((v) => v + 1)
setQualityRevision((v) => v + 1)
}}
/>
</form>
<div hidden={view !== 'records'}>
<QAAIWorkbench query={query} onStatus={setAIStatus} onRecordChanged={refreshAIRecord} />
</div>
</>
) : null}
{view === 'regions' ? (
@@ -529,6 +620,7 @@ export function QAOperations() {
<QAOperationsView
page={page}
status={status}
taskUpdates={aiStatus?.recent_tasks}
error={error}
loading={loading}
detail={detail}
@@ -545,7 +637,7 @@ export function QAOperations() {
)
setQualityRevision((v) => v + 1)
}}
onSelect={(id) => void select(id)}
onSelect={select}
onCloseDetail={close}
progress={progress}
onRetry={() => setRevision((v) => v + 1)}
+2
View File
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useState } from 'react'
import { BackupScheduleSection } from './BackupScheduleSection'
import { QAModelSettings } from './QAModelSettings'
import { MembersSection } from './MembersSection'
import { DingtalkSessionControl } from './DingtalkSessionControl'
import { RoutingBindingsSection } from './RoutingBindingsSection'
@@ -551,6 +552,7 @@ export function SystemSettingsView({
</p>
</div>
</div>
{isAdmin ? <QAModelSettings /> : null}
<div className="environment-cards">
<article>
<b>测试 WeKnora</b>
+129
View File
@@ -0,0 +1,129 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import {
parseAISettings,
parseAIBatch,
aiBatchProgress,
parseAIStatus,
parseAIWorkState,
parseAIPreview,
parseAIEvidence,
} from './qaAITypes'
const settings = {
revision: 1,
base_url: 'https://model.example.invalid/v1',
model: 'fixture',
key_configured: true,
verification: 'verified',
checked_at: '2026-10-19T00:00:00Z',
automatic_evaluation: false,
automatic_translation: false,
storage_ready: true,
}
const batch = {
id: 'fixture',
kind: 'evaluation',
state: 'active',
total: 4,
succeeded: 2,
failed: 1,
skipped: 1,
running: 0,
queued: 0,
retry: 0,
paused: 0,
created_at: '2026-10-19T00:00:00Z',
}
describe('AI safe settings and honest batch accounting', () => {
it('accepts only a write-only key status and rejects secret-bearing settings responses', () => {
expect(parseAISettings(settings).key_configured).toBe(true)
expect(() => parseAISettings({ ...settings, api_key: 'fixture-only' })).toThrow('响应无效')
})
it('counts all terminal outcomes as finished without equating 100% with success', () => {
const parsed = parseAIBatch(batch)
expect(aiBatchProgress(parsed)).toEqual({ finished: 4, percent: 100 })
expect(parsed.failed).toBe(1)
expect(() => parseAIBatch({ ...batch, total: 5 })).toThrow('响应无效')
expect(
aiBatchProgress(parseAIBatch({ ...batch, total: 0, succeeded: 0, failed: 0, skipped: 0 })).percent
).toBeNull()
})
})
it('strictly accepts real task/evidence metadata and refuses partial preview counts', () => {
const work = {
id: 'work',
record_id: 'record',
kind: 'evaluation',
state: 'running',
stage: 'request',
attempt: 1,
error_code: '',
skip_reason: '',
started_at: '2026-10-19T00:00:00Z',
updated_at: '2026-10-19T00:00:01Z',
}
const status = {
settings,
worker_ready: true,
queues: [{ kind: 'evaluation', queued: 0, running: 1, retry: 0, failed: 0, paused: 0, succeeded: 0, skipped: 0 }],
batches: [],
recent_tasks: [work],
recent_tasks_limited: false,
}
expect(parseAIStatus(status).recent_tasks[0].stage).toBe('request')
expect(() => parseAIWorkState({ ...work, state: 'invented' })).toThrow('响应无效')
const preview = {
id: 'preview',
kind: 'evaluation',
scope_total: 4,
eligible: 3,
skipped: 1,
config_revision: 1,
expires_at: '2026-10-19T00:10:00Z',
}
expect(parseAIPreview(preview).eligible).toBe(3)
expect(() => parseAIPreview({ ...preview, eligible: 2 })).toThrow('响应无效')
const evidence = {
...work,
state: 'succeeded',
input_hash: 'a'.repeat(64),
config_revision: 1,
prompt_version: 'fixture',
dictionary_version: 'fixture',
actual_model: 'fixture',
result: {
fields: {
product_category: {
value: 'MG400',
basis: 'semantic_only',
reason: '原问题含型号',
quotes: [{ source: 'question', text: 'MG400', reference_index: 0 }],
},
},
},
applied_fields: { product_category: 'MG400' },
skipped_fields: {},
}
expect(parseAIEvidence(evidence).result.fields?.product_category.reason).toBe('原问题含型号')
})
afterEach(() => vi.unstubAllGlobals())
it('saves through the real admin API contract with explicit intent and no key on keep', async () => {
const { saveAISettings } = await import('./qaAI')
const fetcher = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: settings }), { status: 200 }))
vi.stubGlobal('fetch', fetcher)
const result = await saveAISettings({
base_revision: 1,
base_url: settings.base_url,
model: settings.model,
key_action: 'keep',
})
expect(result.key_configured).toBe(true)
const [path, request] = fetcher.mock.calls[0]
expect(path).toBe('/api/v1/qa-ops/ai/settings')
expect(request.headers['X-Governance-Action']).toBe('qa-ai')
const body = JSON.parse(request.body)
expect(body.key_action).toBe('keep')
expect(body).not.toHaveProperty('api_key')
expect(body).not.toHaveProperty('actor')
})
+57
View File
@@ -0,0 +1,57 @@
import { getPayload } from './qaOps'
import { parseAISettings, parseAIBatch, parseAIStatus, parseAIPreview, parseAIEvidence } from './qaAITypes'
import type { AISettings, AIKind } from './qaAITypes'
export interface AISettingsInput {
base_revision: number
base_url: string
model: string
key_action: 'keep' | 'replace' | 'clear'
api_key?: string
}
export interface AIScope {
kind: AIKind
ids?: string[]
start?: string
end?: string
keyword?: string
}
const prefix = '/api/v1/qa-ops/ai'
const post = (path: string, input: unknown, nonce?: string) =>
getPayload(prefix + path, undefined, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Governance-Action': 'qa-ai',
...(nonce ? { 'Idempotency-Key': nonce } : {}),
},
body: JSON.stringify(input),
})
export async function fetchAISettings(signal?: AbortSignal) {
return parseAISettings(await getPayload(prefix + '/settings', signal))
}
export async function saveAISettings(input: AISettingsInput): Promise<AISettings> {
return parseAISettings(await post('/settings', input))
}
export async function testAISettings(input: AISettingsInput) {
return parseAISettings(await post('/settings/test', input))
}
export async function fetchAIStatus(signal?: AbortSignal) {
return parseAIStatus(await getPayload(prefix + '/status', signal))
}
export async function previewAI(scope: AIScope) {
return parseAIPreview(await post('/previews', scope))
}
export async function startAI(preview_id: string, nonce: string) {
return parseAIBatch(await post('/batches', { preview_id, nonce }))
}
export async function manageAIBatch(id: string, action: 'pause' | 'resume' | 'retry', nonce: string) {
return parseAIBatch(await post('/batches/' + encodeURIComponent(id) + '/actions', { action, nonce }, nonce))
}
export async function setAIAutomation(kind: AIKind, enabled: boolean) {
return parseAISettings(await post('/automation', { kind, enabled }))
}
export async function fetchAIEvidence(id: string, signal?: AbortSignal) {
const value = await getPayload(prefix + '/records/' + encodeURIComponent(id), signal)
if (!Array.isArray(value)) throw new Error('AI依据响应无效')
return value.map(parseAIEvidence)
}
+248
View File
@@ -0,0 +1,248 @@
export interface AISettings {
revision: number
base_url: string
model: string
key_configured: boolean
verification: 'not_configured' | 'verified' | 'unverified' | 'rejected'
checked_at: string | null
automatic_evaluation: boolean
automatic_translation: boolean
storage_ready: boolean
}
export type AIKind = 'evaluation' | 'translation'
export interface AIBatch {
id: string
kind: AIKind
state: 'active' | 'paused'
total: number
succeeded: number
failed: number
skipped: number
running: number
queued: number
retry: number
paused: number
created_at: string
}
const bad = (): never => {
throw new Error('问答AI响应无效,未展示失真的状态或凭据')
}
export const aiObject = (v: unknown): Record<string, unknown> =>
v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : bad()
const text = (v: unknown): string => (typeof v === 'string' ? v : bad())
const count = (v: unknown): number => (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? v : bad())
const bool = (v: unknown): boolean => (typeof v === 'boolean' ? v : bad())
const stamp = (v: unknown): string => {
const s = text(v)
return Number.isFinite(Date.parse(s)) ? s : bad()
}
const kind = (v: unknown): AIKind => (v === 'evaluation' || v === 'translation' ? v : bad())
export function parseAISettings(value: unknown): AISettings {
const v = aiObject(value)
if (['api_key', 'key', 'key_ciphertext', 'secret'].some((key) => key in v)) return bad()
const verification = text(v.verification)
if (!['not_configured', 'verified', 'unverified', 'rejected'].includes(verification)) return bad()
const out = {
revision: count(v.revision),
base_url: text(v.base_url),
model: text(v.model),
key_configured: bool(v.key_configured),
verification: verification as AISettings['verification'],
checked_at: v.checked_at === null ? null : stamp(v.checked_at),
automatic_evaluation: bool(v.automatic_evaluation),
automatic_translation: bool(v.automatic_translation),
storage_ready: bool(v.storage_ready),
}
if (out.verification === 'verified' && (!out.key_configured || !out.base_url || !out.model)) return bad()
return out
}
export function parseAIBatch(value: unknown): AIBatch {
const v = aiObject(value)
if (v.state !== 'active' && v.state !== 'paused') return bad()
const batch = {
id: text(v.id),
kind: kind(v.kind),
state: v.state as AIBatch['state'],
total: count(v.total),
succeeded: count(v.succeeded),
failed: count(v.failed),
skipped: count(v.skipped),
running: count(v.running),
queued: count(v.queued),
retry: count(v.retry),
paused: count(v.paused),
created_at: stamp(v.created_at),
}
if (
!batch.id ||
batch.total !==
batch.succeeded + batch.failed + batch.skipped + batch.running + batch.queued + batch.retry + batch.paused
)
return bad()
return batch
}
export function aiBatchProgress(batch: AIBatch) {
const finished = batch.succeeded + batch.failed + batch.skipped
return { finished, percent: batch.total > 0 ? Math.round((100 * finished) / batch.total) : null }
}
export type AIWorkStateName = 'queued' | 'running' | 'retry' | 'succeeded' | 'failed' | 'skipped' | 'paused'
export interface AIWorkState {
id: string
record_id: string
kind: AIKind
state: AIWorkStateName
stage: string
attempt: number
error_code: string
skip_reason: string
started_at: string | null
updated_at: string
}
export interface AIQueue {
kind: AIKind
queued: number
running: number
retry: number
failed: number
paused: number
succeeded: number
skipped: number
}
export interface AIStatus {
settings: AISettings
worker_ready: boolean
queues: AIQueue[]
batches: AIBatch[]
recent_tasks: AIWorkState[]
recent_tasks_limited: boolean
}
export interface AIPreview {
id: string
kind: AIKind
scope_total: number
eligible: number
skipped: number
config_revision: number
expires_at: string
}
export interface AIQuote {
source: string
text: string
reference_index: number
}
export interface AIFieldEvidence {
value: string
basis: string
reason: string
quotes: AIQuote[]
}
export interface AIEvidence extends AIWorkState {
input_hash: string
config_revision: number
prompt_version: string
dictionary_version: string
actual_model: string
result: { fields?: Record<string, AIFieldEvidence>; question_chinese?: string }
applied_fields: Record<string, string>
skipped_fields: Record<string, string>
}
export function parseAIWorkState(value: unknown): AIWorkState {
const v = aiObject(value),
state = text(v.state)
if (!['queued', 'running', 'retry', 'succeeded', 'failed', 'skipped', 'paused'].includes(state)) return bad()
const work = {
id: text(v.id),
record_id: text(v.record_id),
kind: kind(v.kind),
state: state as AIWorkStateName,
stage: text(v.stage),
attempt: count(v.attempt),
error_code: text(v.error_code),
skip_reason: text(v.skip_reason),
started_at: v.started_at === null ? null : stamp(v.started_at),
updated_at: stamp(v.updated_at),
}
if (!work.id || !work.record_id || (work.state === 'running' && !work.started_at)) return bad()
return work
}
export function parseAIStatus(value: unknown): AIStatus {
const v = aiObject(value)
if (!Array.isArray(v.queues) || !Array.isArray(v.batches) || !Array.isArray(v.recent_tasks)) return bad()
const queues = v.queues.map((raw) => {
const q = aiObject(raw)
return {
kind: kind(q.kind),
queued: count(q.queued),
running: count(q.running),
retry: count(q.retry),
failed: count(q.failed),
paused: count(q.paused),
succeeded: count(q.succeeded),
skipped: count(q.skipped),
}
})
if (new Set(queues.map((q) => q.kind)).size !== queues.length) return bad()
return {
settings: parseAISettings(v.settings),
worker_ready: bool(v.worker_ready),
queues,
batches: v.batches.map(parseAIBatch),
recent_tasks: v.recent_tasks.map(parseAIWorkState),
recent_tasks_limited: bool(v.recent_tasks_limited),
}
}
export function parseAIPreview(value: unknown): AIPreview {
const v = aiObject(value),
preview = {
id: text(v.id),
kind: kind(v.kind),
scope_total: count(v.scope_total),
eligible: count(v.eligible),
skipped: count(v.skipped),
config_revision: count(v.config_revision),
expires_at: stamp(v.expires_at),
}
if (!preview.id || preview.eligible + preview.skipped !== preview.scope_total) return bad()
return preview
}
const stringMap = (value: unknown): Record<string, string> =>
Object.fromEntries(Object.entries(aiObject(value)).map(([key, v]) => [key, text(v)]))
export function parseAIEvidence(value: unknown): AIEvidence {
const v = aiObject(value),
r = aiObject(v.result),
result: AIEvidence['result'] = {}
if (r.fields !== undefined) {
result.fields = Object.fromEntries(
Object.entries(aiObject(r.fields)).map(([field, raw]) => {
if (!['is_correct', 'product_category', 'problem_type', 'root_cause'].includes(field)) return bad()
const f = aiObject(raw)
if (
!Array.isArray(f.quotes) ||
!['semantic_only', 'reference_evidence', 'insufficient_evidence'].includes(text(f.basis))
)
return bad()
const quotes = f.quotes.map((raw) => {
const q = aiObject(raw)
if (!['question', 'answer', 'reference'].includes(text(q.source))) return bad()
return { source: text(q.source), text: text(q.text), reference_index: count(q.reference_index) }
})
return [field, { value: text(f.value), basis: text(f.basis), reason: text(f.reason), quotes }]
})
)
}
if (r.question_chinese !== undefined) result.question_chinese = text(r.question_chinese)
const input_hash = text(v.input_hash)
if (!/^[a-f0-9]{64}$/.test(input_hash)) return bad()
return {
...parseAIWorkState(v),
input_hash,
config_revision: count(v.config_revision),
prompt_version: text(v.prompt_version),
dictionary_version: text(v.dictionary_version),
actual_model: text(v.actual_model),
result,
applied_fields: stringMap(v.applied_fields),
skipped_fields: stringMap(v.skipped_fields),
}
}
+52
View File
@@ -0,0 +1,52 @@
const colors = {
blue: ['#1d4ed8', '#dbeafe'],
cyan: ['#155e75', '#cffafe'],
violet: ['#6d28d9', '#ede9fe'],
indigo: ['#3730a3', '#e0e7ff'],
orange: ['#9a3412', '#ffedd5'],
teal: ['#115e59', '#ccfbf1'],
gray: ['#475569', '#f1f5f9'],
green: ['#166534', '#dcfce7'],
red: ['#991b1b', '#fee2e2'],
amber: ['#92400e', '#fef3c7'],
} as const
const categories: Record<string, keyof typeof colors> = {}
const group = (color: keyof typeof colors, labels: string[]) =>
labels.forEach((label) => {
categories[label] = color
})
group('blue', ['CR/CRA/H/AP', 'CRV', 'CR配件', '参数'])
group('cyan', ['Nova及系列', 'Nova配件', 'MG400', 'MG400配件', 'M1 Pro', '使用配置'])
group('violet', ['人形机器人', '四六足机器人', '教育所有产品', 'X-Trainer', '咨询', '检索不到'])
group('indigo', ['DobotStudio Pro', '仿真软件', '维护工具', '新示教器', 'VX500', '二次开发', '培训与学习'])
group('orange', [
'码垛解决方案',
'码垛插件',
'焊接解决方案',
'焊接插件',
'移动复合机器人',
'故障',
'售后',
'知识缺失',
'知识过期',
])
group('teal', ['生态插件', '生态合作', '安全皮肤', '资料获取', '案例'])
group('green', ['认证'])
group('gray', ['未知', '其他', '问题质量差', '非知识范围', '—'])
group('red', ['答案生成错误'])
group('amber', ['结果不清', '待确认', '部分覆盖'])
export const qaTagColumns = new Set(['coverage', 'is_correct', 'product_category', 'problem_type', 'root_cause'])
export function qaFieldColors(field: string, label: string): { color: string; backgroundColor: string } {
const tone =
field === 'coverage' || field === 'is_correct'
? label === '是'
? 'green'
: label === '否'
? 'red'
: label === '待确认' || label === '部分覆盖'
? 'amber'
: 'gray'
: categories[label] || 'gray'
const [color, backgroundColor] = colors[tone]
return { color, backgroundColor }
}
+27
View File
@@ -1,6 +1,7 @@
import { afterEach, expect, it, vi } from 'vitest'
import { fetchQARecords, parseQARecord, qaCellValue } from './qaOps'
import { fixtureRecord } from './qaOps.test'
import { qualityFixture, fields } from './qaQuality.fixture'
afterEach(() => vi.unstubAllGlobals())
it('keeps imported historical labels and genuine missing values instead of replacing them with new rule labels', () => {
const raw = {
@@ -24,6 +25,32 @@ it('keeps imported historical labels and genuine missing values instead of repla
for (const bad of [null, [], { coverage: 123 }, { unapproved: 'x' }])
expect(() => parseQARecord({ ...raw, master_fields: bad })).toThrow('响应无效')
})
it('accepts explicitly versioned master effective fields without inventing a human review or weakening legacy checks', () => {
const quality = {
...qualityFixture,
state: 'unreviewed',
revision: 0,
latest_review: null,
effective: fields,
effective_source: 'master-effective-fields-v1',
}
const row = {
...fixtureRecord,
record_origin: 'historical_excel',
master_fields: { coverage: '是', is_correct: '是', product_category: 'MG400' },
quality,
}
expect(parseQARecord(row).quality?.effective.product_category).toBe('MG400')
expect(parseQARecord(row).quality?.state).toBe('unreviewed')
expect(() => parseQARecord({ ...row, record_origin: undefined })).toThrow()
expect(() => parseQARecord({ ...row, quality: { ...quality, effective_source: undefined } })).toThrow()
const tampered = {
...qualityFixture,
effective_source: 'master-effective-fields-v1',
effective: { ...fields, correctness: 'incorrect' },
}
expect(() => parseQARecord({ ...row, quality: tampered })).toThrow()
})
it('selects the durable master explicitly and leaves original 2.0 callers on their existing dataset', async () => {
const page = { items: [], columns: [], total: 0, has_more: false, next_cursor: '', as_of: '2026-10-19T00:00:00Z' }
const mocked = vi
+197
View File
@@ -436,3 +436,200 @@
.qa-quality-rates p {
margin: 4px 0 0;
}
/* Keep the wide ledger at the top; category colors do not tint entire rows. */
.qa-ops {
gap: 8px;
padding: 12px 16px;
}
.qa-ops-query {
flex-wrap: nowrap;
gap: 8px;
padding: 8px 10px;
}
.qa-ops-query label {
gap: 3px;
font-size: 11px;
}
.qa-week-picker {
flex-basis: auto;
flex-wrap: nowrap;
gap: 6px;
}
.qa-week-picker > span {
display: none;
}
.qa-ops-keyword {
min-width: 110px;
}
.qa-ops-query input[type='datetime-local'] {
width: 177px;
padding: 6px;
}
.qa-ops-query .qa-mirror-sync {
margin: 0;
padding: 0;
border: 0;
flex: 0 0 auto;
background: none;
}
.qa-ops-query .qa-mirror-sync-line {
gap: 4px;
}
.qa-ops-query .qa-mirror-sync [role='status']:empty {
display: none;
}
.qa-ops-result-bar {
display: flex;
justify-content: space-between;
gap: 12px;
}
.qa-field-tag {
display: inline-block;
padding: 1px 6px;
border: 1px solid currentColor;
border-radius: 4px;
font-size: 12px;
line-height: 18px;
white-space: nowrap;
}
.qa-person-name {
display: inline-block;
max-width: 140px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}
.qa-ops-table tbody tr[data-qa-row] {
cursor: default;
}
.qa-ops-table tbody tr[data-qa-row]:hover {
background: var(--bg-subtle, #f8fafc);
}
@media (max-width: 1100px) {
.qa-ops-query {
flex-wrap: wrap;
}
}
@media (max-width: 500px) {
.qa-ops {
padding: 8px;
}
.qa-ops-query input[type='datetime-local'] {
width: 100%;
}
}
.qa-ai-model-settings {
padding: 14px 0;
border-block: 1px solid var(--border, #e2e8f0);
}
.qa-ai-model-settings h3 {
margin: 0 0 6px;
}
.qa-ai-workbench {
border: 1px solid var(--border, #e2e8f0);
border-radius: 5px;
padding: 6px 10px;
}
.qa-ai-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
font-size: 12px;
}
.qa-ai-actions button,
.qa-ai-queue button,
.qa-ai-confirm button {
padding: 5px 9px;
font-size: 12px;
}
.qa-ai-request {
display: inline-flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
.qa-ai-confirm {
display: flex;
flex-wrap: wrap;
gap: 8px;
padding: 10px;
border: 1px solid #93c5fd;
background: #eff6ff;
color: #1e3a8a;
border-radius: 4px;
}
.qa-ai-confirm strong,
.qa-ai-confirm small {
flex: 1 0 100%;
}
.qa-ai-progress {
margin-top: 5px;
font-size: 12px;
}
.qa-ai-progress > summary {
cursor: pointer;
}
.qa-ai-queue {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
padding: 7px 0;
}
.qa-ai-batch {
display: flex;
flex-direction: column;
gap: 5px;
margin-top: 8px;
padding: 8px;
border-top: 1px solid var(--border, #e2e8f0);
}
.qa-ai-task {
display: block;
line-height: 18px;
color: #475569;
}
.qa-ai-task-running,
.qa-ai-task-queued {
color: #1d4ed8;
}
.qa-ai-task-succeeded {
color: #166534;
}
.qa-ai-task-failed {
color: #991b1b;
}
.qa-ai-task-retry,
.qa-ai-task-paused {
color: #92400e;
}
.qa-ai-evidence {
margin-top: 12px;
}
.qa-ai-evidence > details {
border-top: 1px solid var(--border, #e2e8f0);
padding: 8px 0;
}
.qa-ai-field-evidence {
margin: 8px 0;
padding: 8px;
border-left: 2px solid #93c5fd;
background: #f8fafc;
}
.qa-ai-field-evidence p {
margin: 5px 0;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.qa-ai-field-evidence blockquote {
margin: 8px 0;
padding-left: 10px;
border-left: 2px solid #cbd5e1;
}
.qa-ai-hash {
overflow-wrap: anywhere;
}
+68 -8
View File
@@ -1,3 +1,5 @@
import { parseAIWorkState } from './qaAITypes'
import type { AIWorkState } from './qaAITypes'
import { parseQAQuality } from './qaQuality'
import { regionNames, parseRegionDefinitions } from './qaOrg'
import type { QAQuality } from './qaQuality'
@@ -82,6 +84,7 @@ export function mergeQAPages(current: QARecordPage, next: QARecordPage): QARecor
}
}
export interface QARecord {
background_tasks?: AIWorkState[]
record_origin?: 'dobotai_2_0' | 'historical_excel'
master_fields?: Partial<Record<QAColumn, string>>
quality?: QAQuality
@@ -100,7 +103,12 @@ export interface QARecord {
media: unknown
source_coverage: { verdict: string; reason_code: string; evaluator_version: string }
feedback: { asker_value: string; up: number; down: number }
coverage: { state: 'pending' | 'checked'; verdict?: 'uncovered'; rule_version: string; matched_text?: string }
coverage: {
state: 'pending' | 'checked'
verdict?: 'uncovered' | 'covered'
rule_version: string
matched_text?: string
}
question_chinese?: string
is_correct?: boolean | null
product_category?: string
@@ -158,12 +166,26 @@ export function parseQARecord(value: unknown): QARecord {
const source = object(row.source_coverage)
const coverage = object(row.coverage)
if (coverage.state !== 'pending' && coverage.state !== 'checked') return invalid()
if (coverage.verdict !== undefined && coverage.verdict !== 'uncovered') return invalid()
if (coverage.state === 'checked' && coverage.verdict !== 'uncovered') return invalid()
const masterV2 =
['dobotai_2_0', 'historical_excel'].includes(String(row.record_origin)) &&
coverage.rule_version === 'master-answer-substring-v2'
if (
coverage.verdict !== undefined &&
coverage.verdict !== 'uncovered' &&
!(masterV2 && coverage.verdict === 'covered')
)
return invalid()
if (coverage.state === 'checked' && coverage.verdict !== 'uncovered' && !(masterV2 && coverage.verdict === 'covered'))
return invalid()
if (coverage.state === 'pending' && coverage.verdict !== undefined) return invalid()
const askerValue = text(feedback.asker_value)
if (!['', 'up', 'down'].includes(askerValue)) return invalid()
const item: QARecord = {
...(row.quality === undefined ? {} : { quality: parseQAQuality(row.quality) }),
...(row.quality === undefined
? {}
: {
quality: parseQAQuality(row.quality, ['dobotai_2_0', 'historical_excel'].includes(String(row.record_origin))),
}),
id: text(row.id),
status: text(row.status),
question: text(row.question),
@@ -206,6 +228,11 @@ export function parseQARecord(value: unknown): QARecord {
}
item.master_fields = fields
}
if (row.background_tasks !== undefined) {
if (!Array.isArray(row.background_tasks)) return invalid()
item.background_tasks = row.background_tasks.map(parseAIWorkState)
if (item.background_tasks.some((task) => task.record_id !== item.id)) return invalid()
}
if (row.organization !== undefined) {
const o = object(row.organization)
if (
@@ -343,15 +370,47 @@ export async function fetchQAStatus(signal?: AbortSignal): Promise<QAStatus> {
}
}
export function triggerPersonName(raw: string): string | null {
const value = raw.trim()
if (!value) return null
if (!/^[{[]/.test(value)) return value
try {
const person: unknown = JSON.parse(value)
if (!person || typeof person !== 'object' || Array.isArray(person)) return '人员信息待解析'
const fields = person as Record<string, unknown>
for (const key of ['name', 'nickName']) {
if (typeof fields[key] === 'string' && fields[key].trim()) return fields[key].trim()
}
return '未提供姓名'
} catch {
return '人员信息待解析'
}
}
export function qaCellValue(item: QARecord, column: QAColumn): string | null {
if (column === 'trigger_person') return triggerPersonName(item.master_fields?.trigger_person ?? item.trigger_person)
const reviewedQuality =
item.quality?.state === 'reviewed' &&
['coverage', 'is_correct', 'product_category', 'problem_type', 'root_cause'].includes(column)
if (!reviewedQuality && item.master_fields && Object.hasOwn(item.master_fields, column))
return item.master_fields[column] || null
if (!reviewedQuality && item.master_fields && Object.hasOwn(item.master_fields, column)) {
const stored = item.master_fields[column]
if (stored?.trim()) return stored
if (column === 'department' || column === 'region') return item[column] || null
const f = item.quality?.effective
const projected =
column === 'coverage'
? f?.coverage
: column === 'is_correct'
? f?.correctness
: column === 'product_category' || column === 'problem_type' || column === 'root_cause'
? f?.[column]
: undefined
if (!projected) return null
}
if (column === 'question_chinese')
return item.question_chinese || (/\p{Script=Han}/u.test(item.question) ? item.question : '待翻译')
return item.question_chinese || (['zh', '中文'].includes(item.language ?? '') ? item.question : '待翻译')
if (column === 'language') return item.language || '未识别'
const f = item.quality?.effective
if (f) {
@@ -371,7 +430,8 @@ export function qaCellValue(item: QARecord, column: QAColumn): string | null {
if (column === 'product_category' || column === 'problem_type' || column === 'root_cause') return f[column] || null
}
if (column === 'coverage') return item.coverage.verdict === 'uncovered' ? '否' : null
if (column === 'coverage')
return item.coverage.verdict === 'uncovered' ? '否' : item.coverage.verdict === 'covered' ? '是' : null
if (column === 'is_correct') return typeof item.is_correct === 'boolean' ? (item.is_correct ? '是' : '否') : null
if (column === 'feedback') {
if (item.feedback.asker_value === 'up') return '是'
+58
View File
@@ -0,0 +1,58 @@
import { describe, expect, it } from 'vitest'
import { qaCellValue, parseQARecord } from './qaOps'
import type { QARecord } from './qaOps'
const record = {
id: 'display-fixture',
status: 'succeeded',
question: 'MG400 怎么连接?',
answer: 'fixture',
asked_at: '2026-10-19T00:00:00Z',
time_source: 'request_message.created_at',
asker: 'fixture',
trigger_person: JSON.stringify({ name: '示例姓名', nickName: '示例昵称', unionId: 'fixture-private-union' }),
department: '',
region: '',
references: [],
media: [],
source_coverage: { verdict: '', reason_code: '', evaluator_version: '' },
feedback: { asker_value: '', up: 0, down: 0 },
coverage: { state: 'pending', rule_version: 'fixture' },
} satisfies QARecord
describe('compact trigger-person display', () => {
it('extracts the name without modifying or exposing the original identity object', () => {
const raw = record.trigger_person
expect(qaCellValue(record, 'trigger_person')).toBe('示例姓名')
expect(record.trigger_person).toBe(raw)
expect(qaCellValue({ ...record, master_fields: { trigger_person: raw } }, 'trigger_person')).toBe('示例姓名')
})
})
describe('master rule and empty-field projection', () => {
it('accepts positive coverage only under the master v2 rule', () => {
const master = {
...record,
record_origin: 'dobotai_2_0',
coverage: { state: 'checked', verdict: 'covered', rule_version: 'master-answer-substring-v2' },
}
const parsed = parseQARecord(master)
expect(qaCellValue(parsed, 'coverage')).toBe('是')
expect(() =>
parseQARecord({
...master,
record_origin: undefined,
coverage: { ...master.coverage, rule_version: 'governance-answer-substring-v1' },
})
).toThrow('响应无效')
})
it('never treats Japanese kanji as an already translated Chinese question', () => {
expect(qaCellValue({ ...record, question: 'MG400の接続方法', language: '日文' }, 'question_chinese')).toBe('待翻译')
})
})
it('does not let empty historical organization fields hide verified directory enrichment', () => {
const enriched = { ...record, master_fields: { department: '', region: '' }, department: '示例部门', region: 'APAC' }
expect(qaCellValue(enriched, 'department')).toBe('示例部门')
expect(qaCellValue(enriched, 'region')).toBe('APAC')
})
+25 -3
View File
@@ -25,6 +25,7 @@ export interface QualityReview {
created_at: string
}
export interface QAQuality {
effective_source?: 'master-effective-fields-v1'
input_hash: string
input_epoch: number
revision: number
@@ -191,7 +192,7 @@ function review(value: unknown): QualityReview {
created_at: stamp(v.created_at),
}
}
export function parseQAQuality(value: unknown): QAQuality {
export function parseQAQuality(value: unknown, allowMasterProjection = false): QAQuality {
const v = obj(value),
state = text(v.state)
if (!['unreviewed', 'reviewed', 'stale'].includes(state)) return bad()
@@ -216,8 +217,29 @@ export function parseQAQuality(value: unknown): QAQuality {
if (state !== actual) return bad()
const expected =
state === 'reviewed' ? latest_review!.fields : { ...emptyQualityFields, coverage: automatic.result.verdict || '' }
for (const key of Object.keys(expected) as (keyof QualityFields)[]) if (expected[key] !== effective[key]) return bad()
return { input_hash, input_epoch, revision, state: state as QAQuality['state'], automatic, latest_review, effective }
const master = v.effective_source === 'master-effective-fields-v1'
if (v.effective_source !== undefined && (!master || !allowMasterProjection)) return bad()
for (const key of Object.keys(expected) as (keyof QualityFields)[]) {
// The versioned master layer may fill missing fields, but never change an explicit human decision.
if (master) {
if (
state === 'reviewed' &&
(expected[key] !== '' || (key === 'root_cause' && expected.correctness === 'correct')) &&
expected[key] !== effective[key]
)
return bad()
} else if (expected[key] !== effective[key]) return bad()
}
return {
input_hash,
input_epoch,
revision,
state: state as QAQuality['state'],
automatic,
latest_review,
effective,
...(master ? { effective_source: 'master-effective-fields-v1' as const } : {}),
}
}
function qualityRate(value: unknown): QualityRate {
const v = obj(value),