Elffuss BraidHub

kikocis/utopia public

dev · 46.9 KiBRawPermalink
1import { useEffect, useState } from "react";
2import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
3import { useNavigate, useSearch } from "@tanstack/react-router";
4import { ArrowUpRight } from "lucide-react";
5import {
6 api,
7 type AxiomViolation,
8 type ReviewQueue,
9 type OntologyDefect,
10 type ConflictItem,
11 type FactReviewItem,
12 type MergeLog,
13 type PendingFactItem,
14 type ReviewHistoryEvent,
15 type ReviewItem,
16 type ReviewSide,
17 type ViolationResolution,
18} from "../api";
19import { PendingFactRow, useCanDecide } from "./PendingFacts";
20import { S } from "../i18n";
21import { useKb, useKbId } from "../kb";
22import { Chip, type ChipTone, Pager, RAIL_CLS, cn } from "../ui";
23
24const DUP_PAGE = 6;
25const FACT_PAGE = 10;
26const MERGE_PAGE = 10;
27const CONFLICT_PAGE = 8;
28
29const ym = (iso: string | null) => (iso ? iso.slice(0, 7) : null);
30
31/** `code` 或 `code|detail`。查不到就原样显示——存量行里还是旧的英文散文 */
32function escalationText(reason: string): string {
33 const [code, detail] = reason.split("|");
34 const worded = S.review.escalated[code];
35 if (!worded) return reason;
36 return detail ? S.errDetail(worded, detail) : worded;
37}
38
39function dateRange(from: string | null, to: string | null): string | null {
40 if (!from && !to) return null;
41 return `${ym(from) ?? "…"} → ${ym(to) ?? S.review.ongoing}`;
42}
43
44function SideCard({ side }: { side: ReviewSide }) {
45 return (
46 <div className="flex-1 min-w-0">
47 <div className="flex items-center gap-2 mb-1">
48 <span
49 className="h-2.5 w-2.5 rounded-full shrink-0"
50 style={{ backgroundColor: side.color }}
51 />
52 <span className="text-sm font-medium text-white truncate">
53 {side.name}
54 </span>
55 {side.disambiguator && (
56 <span className="text-xs text-neutral-500 truncate">
57 · {side.disambiguator}
58 </span>
59 )}
60 </div>
61 <div className="text-xs text-neutral-500 mb-2">
62 {side.type_label ?? S.graph.untyped} ·{" "}
63 {S.review.factsCount(side.degree)}
64 </div>
65 {side.top_facts.length > 0 ? (
66 <ul className="space-y-1">
67 {side.top_facts.map((f, i) => (
68 <li key={i} className="text-xs text-neutral-400 truncate">
69 {f}
70 </li>
71 ))}
72 </ul>
73 ) : (
74 <p className="text-xs text-neutral-600">{S.review.noFacts}</p>
75 )}
76 </div>
77 );
78}
79
80function DuplicateCard({
81 item,
82 busy,
83 onDecide,
84}: {
85 item: ReviewItem;
86 busy: boolean;
87 onDecide: (action: "merge" | "keep") => void;
88}) {
89 return (
90 <div className="glass rounded-xl p-4">
91 <div className="flex gap-4">
92 <SideCard side={item.left} />
93 <div className="self-center text-neutral-600 text-sm shrink-0">≟</div>
94 <SideCard side={item.right} />
95 </div>
96 <div className="mt-3 pt-3 flex items-center gap-3 border-t border-[var(--u-line)]">
97 <span
98 className={`u-chip ${item.stage === "human" ? "u-chip-warn" : "u-chip-neutral"}`}
99 >
100 {item.stage === "human"
101 ? S.review.stageHuman
102 : S.review.stageAdjudicating}
103 </span>
104 <span className="text-xs text-neutral-500">
105 {S.review.similarity(Math.round(item.score * 100))}
106 </span>
107 {item.reason && (
108 <span className="text-xs text-neutral-600 truncate min-w-0">
109 {escalationText(item.reason)}
110 </span>
111 )}
112 <div className="ml-auto flex gap-2 shrink-0">
113 <button
114 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
115 disabled={busy}
116 onClick={() => onDecide("keep")}
117 >
118 {S.review.keep}
119 </button>
120 <button
121 className="u-btn u-btn-primary px-3 py-1.5 text-xs"
122 disabled={busy}
123 onClick={() => onDecide("merge")}
124 >
125 {S.review.merge}
126 </button>
127 </div>
128 </div>
129 </div>
130 );
131}
132
133function FactRow({
134 fact,
135 busy,
136 onConfirm,
137 onReject,
138}: {
139 fact: FactReviewItem;
140 busy: boolean;
141 onConfirm: () => void;
142 onReject: () => void;
143}) {
144 const range = dateRange(fact.valid_from, fact.valid_to);
145 return (
146 <div className="glass rounded-xl p-4">
147 <div className="flex items-center gap-2 flex-wrap">
148 <span className="text-sm font-medium text-white">
149 {fact.subject_name}
150 </span>
151 <span className="text-xs text-neutral-500">
152 —{" "}
153 <span
154 className={
155 fact.predicate_label === null
156 ? "italic text-neutral-600"
157 : undefined
158 }
159 >
160 {fact.predicate_label ?? S.graph.unknownPredicate}
161 </span>{" "}
162 →
163 </span>
164 <span className="text-sm font-medium text-white">
165 {fact.object_name ?? "?"}
166 </span>
167 {range && <span className="text-xs text-neutral-500">({range})</span>}
168 <span className="u-chip u-chip-warn ml-auto">
169 {S.review.confidence(Math.round(fact.confidence * 100))}
170 </span>
171 </div>
172 {fact.quote && (
173 <p className="mt-2 text-xs text-neutral-500 italic line-clamp-2">
174 “{fact.quote}”
175 </p>
176 )}
177 <div className="mt-3 flex gap-2 justify-end">
178 <button
179 className="u-btn u-btn-ghost px-3 py-1.5 text-xs text-[var(--u-danger)]"
180 disabled={busy}
181 onClick={onReject}
182 >
183 {S.review.reject}
184 </button>
185 <button
186 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
187 disabled={busy}
188 onClick={onConfirm}
189 >
190 {S.review.confirm}
191 </button>
192 </div>
193 </div>
194 );
195}
196
197/** 时态冲突行:旧事实 vs 新事实,三个动作(Close old / Keep both / Reject new)。 */
198function ConflictRow({
199 conflict,
200 busy,
201 onResolve,
202}: {
203 conflict: ConflictItem;
204 busy: boolean;
205 onResolve: (
206 action: "close" | "keep" | "reject_new",
207 closeAt?: string,
208 ) => void;
209}) {
210 const [closeAt, setCloseAt] = useState("");
211 const c = conflict;
212 const needsDate = !c.new_valid_from;
213 // close_at 输入按天精度转 RFC3339
214 const closeAtIso = /^\d{4}-\d{2}-\d{2}$/.test(closeAt.trim())
215 ? `${closeAt.trim()}T00:00:00Z`
216 : undefined;
217
218 return (
219 <div className="glass rounded-xl p-4">
220 <div className="flex items-center gap-2 flex-wrap">
221 <span className="text-sm font-medium text-white">{c.old_subject}</span>
222 <span className="text-xs text-neutral-500">
223 — {c.predicate_label} →
224 </span>
225 <span className="text-sm font-medium text-white">
226 {c.old_object ?? "?"}
227 </span>
228 {c.old_valid_from && (
229 <span className="u-num text-xs text-neutral-500">
230 ({S.review.conflictSince(c.old_valid_from.slice(0, 10))})
231 </span>
232 )}
233 <span className="text-xs text-neutral-600">{S.review.conflictVs}</span>
234 <span className="text-sm font-medium text-white">{c.new_subject}</span>
235 <span className="text-xs text-neutral-500">
236 — {c.predicate_label} →
237 </span>
238 <span className="text-sm font-medium text-white">
239 {c.new_object ?? "?"}
240 </span>
241 {c.new_valid_from && (
242 <span className="u-num text-xs text-neutral-500">
243 ({S.review.conflictSince(c.new_valid_from.slice(0, 10))})
244 </span>
245 )}
246 <span className="u-chip u-chip-warn ml-auto">
247 {S.review.conflictReason[c.reason] ?? c.reason}
248 </span>
249 </div>
250 <div className="mt-3 flex items-center gap-2 justify-end">
251 <button
252 className="u-btn u-btn-ghost px-3 py-1.5 text-xs text-[var(--u-danger)]"
253 disabled={busy}
254 onClick={() => onResolve("reject_new")}
255 >
256 {S.review.rejectNew}
257 </button>
258 <button
259 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
260 disabled={busy}
261 onClick={() => onResolve("keep")}
262 >
263 {S.review.keepBoth}
264 </button>
265 {needsDate && (
266 <input
267 className="input-dark u-num w-28 px-2 py-1.5 text-xs text-center"
268 placeholder={S.review.closeAtPlaceholder}
269 value={closeAt}
270 onChange={(e) => setCloseAt(e.target.value)}
271 />
272 )}
273 <button
274 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
275 disabled={busy || (needsDate && !closeAtIso)}
276 onClick={() => onResolve("close", closeAtIso)}
277 >
278 {c.new_valid_from
279 ? S.review.closeOldAt(c.new_valid_from.slice(0, 10))
280 : S.review.closeOld}
281 </button>
282 </div>
283 </div>
284 );
285}
286
287/** "文档新版没再提"的事实行:Reject(抽取错误)或 Close at date(这事结束了)。 */
288function UnconfirmedRow({
289 fact,
290 busy,
291 onReject,
292 onClose,
293}: {
294 fact: FactReviewItem;
295 busy: boolean;
296 onReject: () => void;
297 onClose: (validTo: string) => void;
298}) {
299 const [closeAt, setCloseAt] = useState("");
300 const closeAtIso = /^\d{4}-\d{2}-\d{2}$/.test(closeAt.trim())
301 ? `${closeAt.trim()}T00:00:00Z`
302 : undefined;
303 const range = dateRange(fact.valid_from, fact.valid_to);
304
305 return (
306 <div className="glass rounded-xl p-4">
307 <div className="flex items-center gap-2 flex-wrap">
308 <span className="text-sm font-medium text-white">
309 {fact.subject_name}
310 </span>
311 <span className="text-xs text-neutral-500">
312 —{" "}
313 <span
314 className={
315 fact.predicate_label === null
316 ? "italic text-neutral-600"
317 : undefined
318 }
319 >
320 {fact.predicate_label ?? S.graph.unknownPredicate}
321 </span>{" "}
322 →
323 </span>
324 <span className="text-sm font-medium text-white">
325 {fact.object_name ?? "?"}
326 </span>
327 {range && (
328 <span className="u-num text-xs text-neutral-500">({range})</span>
329 )}
330 </div>
331 {fact.quote && (
332 <p className="mt-2 text-xs text-neutral-500 italic line-clamp-2">
333 “{fact.quote}”
334 </p>
335 )}
336 <div className="mt-3 flex items-center gap-2 justify-end">
337 <button
338 className="u-btn u-btn-ghost px-3 py-1.5 text-xs text-[var(--u-danger)]"
339 disabled={busy}
340 onClick={onReject}
341 >
342 {S.review.reject}
343 </button>
344 <input
345 className="input-dark u-num w-28 px-2 py-1.5 text-xs text-center"
346 placeholder={S.review.closeAtPlaceholder}
347 value={closeAt}
348 onChange={(e) => setCloseAt(e.target.value)}
349 />
350 <button
351 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
352 disabled={busy || !closeAtIso}
353 onClick={() => closeAtIso && onClose(closeAtIso)}
354 >
355 {closeAt.trim()
356 ? S.review.closeFactAt(closeAt.trim())
357 : S.review.closeFact}
358 </button>
359 </div>
360 </div>
361 );
362}
363
364function MergeRow({
365 merge,
366 busy,
367 onRevert,
368}: {
369 merge: MergeLog;
370 busy: boolean;
371 onRevert: () => void;
372}) {
373 return (
374 <div className="glass rounded-xl px-4 py-3 flex items-center gap-3">
375 <div className="min-w-0 flex-1">
376 <div className="text-sm text-neutral-300 truncate">
377 <span className="text-neutral-500">{merge.source_name}</span>
378 <span className="text-neutral-600"> → </span>
379 <span className="text-white">{merge.target_name}</span>
380 </div>
381 <div className="text-xs text-neutral-500 truncate">
382 {merge.merged_by_name
383 ? S.review.mergedBy(merge.merged_by_name)
384 : S.review.mergedByAi}
385 {" · "}
386 {merge.created_at.slice(0, 10)}
387 {merge.reason ? ` · ${escalationText(merge.reason)}` : ""}
388 </div>
389 </div>
390 {merge.reverted_at ? (
391 <span className="u-chip u-chip-neutral shrink-0">
392 {S.review.reverted}
393 </span>
394 ) : (
395 <button
396 className="u-btn u-btn-ghost px-3 py-1.5 text-xs shrink-0"
397 disabled={busy}
398 onClick={onRevert}
399 >
400 {S.review.revert}
401 </button>
402 )}
403 </div>
404 );
405}
406
407/* ---------- 决策台账行 ---------- */
408
409const DECISION_TONE: Record<string, ChipTone> = {
410 "review.merge": "violet",
411 "merge.manual": "violet",
412 "review.keep": "neutral",
413 "fact.confirm": "success",
414 "fact.reject": "danger",
415 "conflict.reject_new": "danger",
416 "fact.close": "info",
417 "conflict.close_old": "info",
418 "conflict.keep_both": "neutral",
419 "merge.revert": "warn",
420};
421
422function DecisionRow({ e }: { e: ReviewHistoryEvent }) {
423 // detail 是决策时的自包含快照——不 join 活数据,事实删了台账也完整
424 // eslint-disable-next-line @typescript-eslint/no-explicit-any
425 const d = e.detail as any;
426 let text: string;
427 if (e.action.startsWith("review.")) text = `${d.left} ≟ ${d.right}`;
428 else if (e.action.startsWith("fact."))
429 text = `${d.subject} — ${d.predicate ?? "?"} → ${d.object ?? "?"}`;
430 else if (e.action.startsWith("conflict."))
431 text = `${d.old_subject} — ${d.predicate} → ${d.old_object ?? "?"} · vs · ${
432 d.new_object ?? d.new_subject
433 }`;
434 else text = `${d.source} → ${d.target}`;
435
436 return (
437 <div className="glass rounded-xl px-4 py-3 flex items-center gap-3">
438 <Chip tone={DECISION_TONE[e.action] ?? "neutral"}>
439 {S.review.decisionActions[e.action] ?? e.action}
440 </Chip>
441 <span className="text-sm text-neutral-300 truncate min-w-0">{text}</span>
442 {typeof d.confidence === "number" && (
443 <span className="u-num text-xs text-neutral-600 shrink-0">
444 {Math.round(d.confidence * 100)}%
445 </span>
446 )}
447 {typeof d.valid_to === "string" && (
448 <span className="u-num text-xs text-neutral-600 shrink-0">
449 → {d.valid_to.slice(0, 10)}
450 </span>
451 )}
452 <span className="ml-auto shrink-0 text-xs text-neutral-500">
453 {e.actor_name ?? S.review.aiActor}
454 {" · "}
455 <span className="u-num">{e.created_at.slice(0, 10)}</span>
456 </span>
457 </div>
458 );
459}
460
461/** 一条待表态的数据映射口径(0011)。
462 *
463 * 展示的重点是**「这个数怎么算」**——SQL / 表达式 / 表名按这个优先级取一个,
464 * 因为人要判断的正是它对不对。概念名与源是身份,unit 是答里必须带的量纲。 */
465/** 本体自己的一处自相矛盾。**两个按钮而不是三个**——这一档压根没看数据,
466 * 所以没有「数据错了」这条出路,只能是「我去改了本体」或「先放着」。 */
467function DefectRow({
468 defect: d,
469 busy,
470 onDecide,
471}: {
472 defect: OntologyDefect;
473 busy: boolean;
474 onDecide: (resolution: "fixed" | "accepted") => void;
475}) {
476 const what = {
477 symmetric_and_asymmetric: S.review.defectSymAsym,
478 transitive_and_functional: S.review.defectTransFunc,
479 subclass_cycle: S.review.defectCycle,
480 disjoint_with_ancestor: S.review.defectDisjointAncestor,
481 inherits_disjoint: S.review.defectInheritsDisjoint,
482 inverse_of_itself: S.review.defectInverseSelf,
483 inverse_not_mutual: S.review.defectInverseNotMutual,
484 sub_property_cycle: S.review.defectSubPropertyCycle,
485 rules_disagree: S.review.defectRulesDisagree,
486 }[d.kind];
487 const rules = d.kind === "rules_disagree" ? (d.detail.rules ?? []) : [];
488 // 后两类的后果值得写出来:不可满足的类不会报错,它只是永远空着
489 const unsatisfiable =
490 d.kind === "disjoint_with_ancestor" || d.kind === "inherits_disjoint";
491 return (
492 <div className="glass rounded-xl p-3">
493 <div className="flex items-baseline gap-2 flex-wrap">
494 <span className="text-sm text-[var(--u-danger)]">{what}</span>
495 {d.subject_label && (
496 <span className="text-xs text-neutral-300">{d.subject_label}</span>
497 )}
498 {d.other_label && (
499 <span className="text-xs text-neutral-500">↔ {d.other_label}</span>
500 )}
501 </div>
502 {d.path_labels.length > 0 && (
503 <div className="mt-1 text-xs text-neutral-400">
504 {d.path_labels.join(" → ")} → {d.path_labels[0]}
505 </div>
506 )}
507 {unsatisfiable && (
508 <p className="mt-1 text-xs text-neutral-500">
509 {S.review.defectNeverInstantiable}
510 </p>
511 )}
512 {rules.length > 0 && (
513 <div className="mt-1 space-y-1 text-xs text-neutral-400">
514 <div>{S.review.rulesDisagreeCount(d.detail.count ?? 0)}</div>
515 {rules.map((r, i) => (
516 <div key={i}>
517 <div className="text-neutral-500">
518 {S.review.rulesDisagreeRule(r.rule_a, r.via_a, r.rule_b, r.via_b, r.axiom)}
519 </div>
520 {r.examples.map(([x, y], j) => (
521 <div key={j} className="pl-3 text-neutral-400">
522 {x} <span className="text-neutral-600">·</span> {y}
523 </div>
524 ))}
525 </div>
526 ))}
527 </div>
528 )}
529 <div className="mt-2 flex gap-1.5">
530 <button
531 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
532 disabled={busy}
533 onClick={() => onDecide("accepted")}
534 >
535 {S.review.defectAccepted}
536 </button>
537 <button
538 className="u-btn u-btn-primary px-3 py-1.5 text-xs"
539 disabled={busy}
540 onClick={() => onDecide("fixed")}
541 >
542 {S.review.defectFixed}
543 </button>
544 </div>
545 </div>
546 );
547}
548
549/** 一处公理违规。**三个按钮而不是两个**——第三个是这一档独有的出路:
550 * 矛盾可能出在定义上(用户导的本体把某个属性声明成反对称,而他的语料里
551 * 那关系其实双向),这时该改的是本体,不是二十条事实。 */
552function ViolationRow({
553 violation: v,
554 busy,
555 onDecide,
556 onDuplicates,
557 onOntology,
558}: {
559 violation: AxiomViolation;
560 busy: boolean;
561 onDecide: (resolution: ViolationResolution, closeAt?: string) => void;
562 onDuplicates: () => void;
563 onOntology: () => void;
564}) {
565 const what = {
566 self_loop: S.review.violationSelfLoop,
567 asymmetry: S.review.violationAsymmetry,
568 cycle: S.review.violationCycle,
569 functional: S.review.violationFunctional,
570 signature: S.review.violationSignature,
571 derived_contradiction: S.review.violationDerived,
572 }[v.kind];
573 if (v.kind === "derived_contradiction") {
574 return <ContradictionRow {...{ v, what, busy, onDecide, onDuplicates, onOntology }} />;
575 }
576 // 自反那一类两条事实是同一条——显示一遍就够,显示两遍像个 bug
577 const single = v.left_fact === v.right_fact;
578 return (
579 <div className="glass rounded-xl p-3">
580 <div className="flex items-baseline gap-2 flex-wrap">
581 <span className="text-sm text-[var(--u-warn)]">{what}</span>
582 {v.predicate && (
583 <span className="text-[11px] text-neutral-500">
584 {S.review.violationVia(v.predicate)}
585 </span>
586 )}
587 {v.path_len > 0 && (
588 <span className="text-[11px] text-neutral-500">
589 {S.review.violationPath(v.path_len)}
590 </span>
591 )}
592 </div>
593 <div className="mt-1.5 space-y-1">
594 <div className="text-xs text-neutral-300">{v.left_text}</div>
595 {!single && (
596 <div className="text-xs text-neutral-300">{v.right_text}</div>
597 )}
598 </div>
599 <div className="mt-2 flex gap-1.5 flex-wrap">
600 <button
601 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
602 disabled={busy}
603 onClick={() => onDecide("accepted")}
604 >
605 {S.review.acceptBoth}
606 </button>
607 <button
608 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
609 disabled={busy}
610 onClick={() => onDecide("axiom_relaxed")}
611 >
612 {S.review.relaxAxiom}
613 </button>
614 <button
615 className="u-btn u-btn-primary px-3 py-1.5 text-xs"
616 disabled={busy}
617 onClick={() => onDecide("fact_retracted")}
618 >
619 {S.review.retractFact}
620 </button>
621 </div>
622 </div>
623 );
624}
625
626/**
627 * 派生撞上断言(0017):卡片是一次审核,线索指向上游的错——旧断言该闭合、
628 * 两个同名实体其实是一个、抽取本来就没把握。修法就在卡片上,端点替人执行。
629 */
630function ContradictionRow({
631 v,
632 what,
633 busy,
634 onDecide,
635 onDuplicates,
636 onOntology,
637}: {
638 v: AxiomViolation;
639 what: string;
640 busy: boolean;
641 onDecide: (resolution: ViolationResolution, closeAt?: string) => void;
642 onDuplicates: () => void;
643 onOntology: () => void;
644}) {
645 const [closeAt, setCloseAt] = useState("");
646 const d = v.detail;
647 const hint =
648 v.hint === "stale"
649 ? S.review.hintStale
650 : v.hint === "duplicate"
651 ? S.review.hintDuplicate
652 : v.hint === "unsure"
653 ? S.review.hintUnsure
654 : S.review.hintReadBoth;
655 return (
656 <div className="glass rounded-xl p-3 border border-[color-mix(in_srgb,var(--u-contest)_35%,transparent)]">
657 <div className="flex items-baseline gap-2 flex-wrap">
658 <span className="text-sm text-[var(--u-contest)]">{what}</span>
659 {v.predicate && (
660 <span className="text-[11px] text-neutral-500">
661 {S.review.violationVia(v.predicate)}
662 </span>
663 )}
664 </div>
665 <div className="mt-1.5 space-y-1">
666 <div className="text-xs text-neutral-300">
667 {S.review.derivedLine(d.subject ?? "?", d.predicate ?? "?", d.object ?? "?")}
668 {d.rule && d.via_label && (
669 <span className="ml-1.5 text-neutral-500">
670 {S.review.derivedBy(d.rule, d.via_label)}
671 </span>
672 )}
673 </div>
674 <div className="text-xs text-neutral-300">
675 {S.review.assertedLine(v.left_text)}
676 </div>
677 </div>
678 <p className="mt-1.5 text-xs text-neutral-500">{hint}</p>
679 <div className="mt-2 flex gap-1.5 flex-wrap items-center">
680 <input
681 type="date"
682 className="input-dark px-2 py-1 text-xs u-num"
683 value={closeAt}
684 title={S.review.closeAssertion}
685 onChange={(e) => setCloseAt(e.target.value)}
686 />
687 <button
688 className="u-btn u-btn-primary px-3 py-1.5 text-xs"
689 disabled={busy || !closeAt}
690 onClick={() =>
691 onDecide("fact_closed", new Date(closeAt).toISOString())
692 }
693 >
694 {S.review.closeAssertion}
695 </button>
696 <button
697 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
698 disabled={busy}
699 onClick={() => onDecide("fact_retracted")}
700 >
701 {S.review.retractAssertion}
702 </button>
703 <button
704 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
705 disabled={busy}
706 onClick={onDuplicates}
707 >
708 {S.review.seeDuplicates}
709 </button>
710 <button
711 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
712 disabled={busy}
713 onClick={onOntology}
714 >
715 {S.review.openOntology}
716 </button>
717 <button
718 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
719 disabled={busy}
720 onClick={() => onDecide("accepted")}
721 >
722 {S.review.letBothStand}
723 </button>
724 </div>
725 </div>
726 );
727}
728
729/* ---------- 页面:左栏分类 + 单类内容区 ---------- */
730
731type Sel =
732 // 记忆抽出、等人点头的事实(0015)。排第一:它是人自己说的话,
733 // 而且在这一档里的东西**还没进图**——别处每一档审的都是已经在图上的
734 | "pending"
735 | "duplicates"
736 | "conflicts"
737 | "unconfirmed"
738 | "lowconf"
739 // 公理违规(0002 R0)。**与 conflicts 分开**:那一档问「哪条对」,
740 // 这一档还可能答「公理写错了」——出路不同
741 | "violations"
742 // 本体自己的自相矛盾。**与 violations 分开**:那一档看事实,这一档只看定义
743 | "defects"
744 | "decisions"
745 | "merges";
746
747/** 走服务端分页的那几档(决策台账另有自己的接口) */
748const QUEUE_FETCHED: ReviewQueue[] = [
749 "pending",
750 "duplicates",
751 "conflicts",
752 "unconfirmed",
753 "lowconf",
754 "violations",
755 "defects",
756 "merges",
757];
758
759const QUEUE_ORDER: Sel[] = [
760 "pending",
761 "duplicates",
762 "conflicts",
763 "unconfirmed",
764 "lowconf",
765 "violations",
766 "defects",
767];
768const PAGE_SIZE: Record<Sel, number> = {
769 pending: FACT_PAGE,
770 duplicates: DUP_PAGE,
771 conflicts: CONFLICT_PAGE,
772 unconfirmed: FACT_PAGE,
773 lowconf: FACT_PAGE,
774 violations: FACT_PAGE,
775 defects: FACT_PAGE,
776 merges: MERGE_PAGE,
777 decisions: 20,
778};
779
780function RailHeader({ label }: { label: string }) {
781 return (
782 <div className="px-4 pt-4 pb-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-neutral-500">
783 {label}
784 </div>
785 );
786}
787
788function RailItem({
789 active,
790 label,
791 count,
792 onClick,
793 external,
794}: {
795 active: boolean;
796 label: string;
797 count: number | null;
798 onClick: () => void;
799 /** 这一档不在本页办——加个去向记号,免得点下去以为页面没反应 */
800 external?: boolean;
801}) {
802 return (
803 <button
804 onClick={onClick}
805 className={cn(
806 "w-full flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-[13px] transition-colors",
807 active
808 ? "u-nav-active"
809 : "text-neutral-400 hover:bg-white/[0.05] hover:text-neutral-200",
810 )}
811 >
812 <span className="truncate">{label}</span>
813 {external && <ArrowUpRight size={11} className="shrink-0 opacity-50" />}
814 {count !== null && (
815 <span
816 className={cn(
817 "ml-auto shrink-0 u-num text-[10.5px]",
818 count > 0 ? "text-neutral-400" : "text-neutral-700",
819 )}
820 >
821 {count}
822 </span>
823 )}
824 </button>
825 );
826}
827
828export function Review() {
829 const kbId = useKbId();
830 const { kb } = useKb();
831 const queryClient = useQueryClient();
832 const navigate = useNavigate();
833 // 面板的争议 chip 带着 queue / item 跳过来:先落到那一档,再把那张卡点亮
834 const search = useSearch({ from: "/app/kb/$kbId/review" });
835 const [sel, setSel] = useState<Sel | null>(
836 QUEUE_ORDER.includes(search.queue as Sel) ? (search.queue as Sel) : null,
837 );
838 const [page, setPage] = useState(0);
839
840 // 队列变化经 SSE 事件流推送(useKbEvents 挂在 Shell),无需轮询。
841 //
842 // **按分档 + 页码取**:从前一次把八个队列全端回来、每档 100 条、客户端分页,
843 // 于是左栏的徽标是截断后的数字,第十一页之后的东西界面上不存在。现在计数
844 // 每次都回(服务端 COUNT,不受一页多少条影响),内容只回当前这一档的一页。
845 const queueSel: ReviewQueue = QUEUE_FETCHED.includes(
846 (sel ?? "duplicates") as ReviewQueue,
847 )
848 ? ((sel ?? "duplicates") as ReviewQueue)
849 : "duplicates";
850 const review = useQuery({
851 queryKey: ["review", kb?.id, queueSel, page],
852 queryFn: () =>
853 api.review(
854 kb!.id,
855 queueSel,
856 PAGE_SIZE[queueSel as Sel],
857 page * PAGE_SIZE[queueSel as Sel],
858 ),
859 enabled: !!kb,
860 // 翻页时别把上一页闪成空白——计数与骨架都还在,只有条目在换
861 placeholderData: (prev) => prev,
862 });
863 // 决策台账:服务端分页,仅选中时拉取
864 const history = useQuery({
865 queryKey: ["reviewHistory", kb?.id, page],
866 queryFn: () => api.reviewHistory(kb!.id, page),
867 enabled: !!kb && sel === "decisions",
868 });
869
870 const invalidate = () => {
871 queryClient.invalidateQueries({ queryKey: ["review", kb?.id] });
872 queryClient.invalidateQueries({ queryKey: ["reviewHistory", kb?.id] });
873 queryClient.invalidateQueries({ queryKey: ["graph"] });
874 };
875
876 const decide = useMutation({
877 mutationFn: ({ id, action }: { id: string; action: "merge" | "keep" }) =>
878 api.decideReview(kb!.id, id, action),
879 onSettled: invalidate,
880 });
881 const factAction = useMutation({
882 mutationFn: ({
883 id,
884 action,
885 }: {
886 id: string;
887 action: "confirm" | "reject";
888 }) =>
889 action === "confirm"
890 ? api.confirmFact(kb!.id, id)
891 : api.rejectFact(kb!.id, id),
892 onSettled: invalidate,
893 });
894 // 等人点头的事实(0015):确认进账本,驳回记进 rejected_facts
895 // 点头是写图的动作:Viewer 看得见提议、看不见按钮(与服务端 Editor 门槛同口径)
896 const canDecidePending = useCanDecide(kb?.id);
897 const pendingAction = useMutation({
898 mutationFn: ({
899 id,
900 action,
901 }: {
902 id: string;
903 action: "confirm" | "reject";
904 }) => api.decidePending(kb!.id, id, action),
905 onSettled: () => {
906 invalidate();
907 queryClient.invalidateQueries({ queryKey: ["pending", kb?.id] });
908 },
909 });
910 const defectAction = useMutation({
911 mutationFn: ({
912 id,
913 resolution,
914 }: {
915 id: string;
916 resolution: "fixed" | "accepted";
917 }) => api.decideDefect(kb!.id, id, resolution),
918 onSettled: invalidate,
919 });
920 const violationAction = useMutation({
921 mutationFn: ({
922 id,
923 resolution,
924 closeAt,
925 }: {
926 id: string;
927 resolution: ViolationResolution;
928 closeAt?: string;
929 }) => api.decideViolation(kb!.id, id, resolution, closeAt),
930 onSettled: invalidate,
931 });
932 // 检查是同步的纯计算,所以直接 mutate 不排队。跑完把报告留在按钮旁边——
933 // **零和零不一样**:没有公理时要说「无从判起」,不能说「未发现矛盾」
934 const runCheck = useMutation({
935 mutationFn: () => api.runConsistencyCheck(kb!.id),
936 onSettled: invalidate,
937 });
938 const revert = useMutation({
939 mutationFn: (mergeId: string) => api.revertMerge(kb!.id, mergeId),
940 onSettled: invalidate,
941 });
942 const conflictAction = useMutation({
943 mutationFn: ({
944 id,
945 action,
946 closeAt,
947 }: {
948 id: string;
949 action: "close" | "keep" | "reject_new";
950 closeAt?: string;
951 }) => api.resolveConflict(kb!.id, id, { action, close_at: closeAt }),
952 onSettled: invalidate,
953 });
954
955 const closeFactAction = useMutation({
956 mutationFn: ({ id, validTo }: { id: string; validTo: string }) =>
957 api.closeFact(kb!.id, id, validTo),
958 onSettled: invalidate,
959 });
960
961 // **徽标读服务端的 COUNT,不读列表长度。** 这是从前那个「库里 164、界面写
962 // 100」的根源:数组长度反映的是一页多少条,不是库里有多少条。
963 const c = review.data?.counts;
964 // mappings 不是本页的一档(审批在「数据映射」页),但计数照收:
965 // 收件箱该说「有几条等你」
966 const counts: Record<Sel | "mappings", number> = {
967 pending: c?.pending ?? 0,
968 duplicates: c?.duplicates ?? 0,
969 conflicts: c?.conflicts ?? 0,
970 unconfirmed: c?.unconfirmed ?? 0,
971 lowconf: c?.lowconf ?? 0,
972 mappings: c?.mappings ?? 0,
973 violations: c?.violations ?? 0,
974 defects: c?.defects ?? 0,
975 merges: c?.merges ?? 0,
976 decisions: history.data?.total ?? 0,
977 };
978 // 当前这一档的一页。**服务端已经切好了**,这里只按档收窄类型——
979 // 收窄错了会在渲染时露馅,而不是悄悄显示空列表
980 const rows = review.data?.queue === queueSel ? (review.data.items ?? []) : [];
981 const asPending = () => rows as PendingFactItem[];
982 const asDuplicates = () => rows as ReviewItem[];
983 const asFacts = () => rows as FactReviewItem[];
984 const asConflicts = () => rows as ConflictItem[];
985 const asViolations = () => rows as AxiomViolation[];
986 const asDefects = () => rows as OntologyDefect[];
987 const asMerges = () => rows as MergeLog[];
988 const queueEmpty = QUEUE_ORDER.every((k) => counts[k] === 0);
989
990 // 首批数据到达:定位到第一个非空队列(全空落在 duplicates 显示"干净"文案)
991 useEffect(() => {
992 if (sel === null && c)
993 setSel(QUEUE_ORDER.find((k) => counts[k] > 0) ?? "duplicates");
994 // eslint-disable-next-line react-hooks/exhaustive-deps
995 }, [c]);
996
997 const select = (s: Sel) => {
998 setSel(s);
999 setPage(0);
1000 };
1001
1002 const active = sel ?? "duplicates";
1003 const isQueueSel = QUEUE_ORDER.includes(active);
1004
1005 const SECTION: Record<Sel, { title: string; hint: string | null }> = {
1006 pending: { title: S.review.pending, hint: S.review.pendingHint },
1007 duplicates: { title: S.review.duplicates, hint: S.review.duplicatesHint },
1008 conflicts: { title: S.review.conflicts, hint: S.review.conflictsHint },
1009 unconfirmed: {
1010 title: S.review.unconfirmed,
1011 hint: S.review.unconfirmedHint,
1012 },
1013 lowconf: {
1014 title: S.review.lowConfidence,
1015 hint: S.review.lowConfidenceHint,
1016 },
1017 violations: {
1018 title: S.review.violations,
1019 hint: S.review.violationsHint,
1020 },
1021 defects: { title: S.review.defects, hint: S.review.defectsHint },
1022 decisions: { title: S.review.decisionsTitle, hint: S.review.decisionsHint },
1023 merges: { title: S.review.mergeHistory, hint: null },
1024 };
1025
1026 return (
1027 <div className="h-full flex">
1028 {/* 左栏:队列分类 + 历史,各带实时计数(SSE 推动刷新) */}
1029 {/* `overflow-y-auto`:矮窗口下这一栏的内容比它高,而底部那条是「去别处办」
1030 的出口——没有滚动它会被裁掉且够不着。`mt-auto` 只在有富余空间时把它
1031 压到底,两者要一起给 */}
1032 <aside className={`${RAIL_CLS} flex flex-col overflow-y-auto u-scroll`}>
1033 <RailHeader label={S.review.tabQueue} />
1034 <div className="px-2 space-y-0.5">
1035 <RailItem
1036 active={active === "pending"}
1037 label={S.review.railPending}
1038 count={counts.pending}
1039 onClick={() => select("pending")}
1040 />
1041 <RailItem
1042 active={active === "duplicates"}
1043 label={S.review.railDuplicates}
1044 count={counts.duplicates}
1045 onClick={() => select("duplicates")}
1046 />
1047 <RailItem
1048 active={active === "conflicts"}
1049 label={S.review.railConflicts}
1050 count={counts.conflicts}
1051 onClick={() => select("conflicts")}
1052 />
1053 <RailItem
1054 active={active === "unconfirmed"}
1055 label={S.review.railUnconfirmed}
1056 count={counts.unconfirmed}
1057 onClick={() => select("unconfirmed")}
1058 />
1059 <RailItem
1060 active={active === "lowconf"}
1061 label={S.review.railLowConfidence}
1062 count={counts.lowconf}
1063 onClick={() => select("lowconf")}
1064 />
1065 <RailItem
1066 active={active === "violations"}
1067 label={S.review.railViolations}
1068 count={counts.violations}
1069 onClick={() => select("violations")}
1070 />
1071 <RailItem
1072 active={active === "defects"}
1073 label={S.review.railDefects}
1074 count={counts.defects}
1075 onClick={() => select("defects")}
1076 />
1077 </div>
1078 <RailHeader label={S.review.tabHistory} />
1079 <div className="px-2 space-y-0.5">
1080 <RailItem
1081 active={active === "decisions"}
1082 label={S.review.railDecisions}
1083 count={null}
1084 onClick={() => select("decisions")}
1085 />
1086 <RailItem
1087 active={active === "merges"}
1088 label={S.review.railMerges}
1089 count={counts.merges}
1090 onClick={() => select("merges")}
1091 />
1092 </div>
1093
1094 {/* 数据映射:**两组都不属于,所以压在底部单独一条。**
1095 上面那七档问的都是「这条知识对不对」,而口径问的是「这个数怎么算」
1096 (0011 已经在数据层把它分出去了);下面那两档是本页办过的事的流水,
1097 而口径的决定从来不进 `review_history`(它只捞 review./fact./
1098 conflict./merge.,口径记的是 mapping.decided)。
1099 **计数留着**——收件箱该说「有几条等你」,但活在有上下文的那一页干 */}
1100 <div className="mt-auto border-t border-white/5 px-2 py-2">
1101 <RailItem
1102 active={false}
1103 label={S.review.railMappings}
1104 count={counts.mappings}
1105 onClick={() =>
1106 navigate({ to: "/kb/$kbId/mappings", params: { kbId } })
1107 }
1108 external
1109 />
1110 </div>
1111 </aside>
1112
1113 {/* 右侧:一次只显示选中的一类,单一分页 */}
1114 <div className="flex-1 min-w-0 overflow-y-auto u-scroll px-8 py-6">
1115 <div className="max-w-4xl">
1116 {review.isPending && (
1117 <p className="text-sm text-neutral-500">{S.nav.loading}</p>
1118 )}
1119 {review.isError && (
1120 <p className="text-sm text-rose-400">
1121 {(review.error as Error).message}
1122 </p>
1123 )}
1124
1125 {review.data && (
1126 <section>
1127 {/* 页级标题:与 Library/KB Settings 同级(text-lg),不是卡片头 */}
1128 <h2 className="u-title text-lg mb-1">{SECTION[active].title}</h2>
1129 {SECTION[active].hint && (
1130 <p className="text-xs text-neutral-500 mb-3">
1131 {SECTION[active].hint}
1132 </p>
1133 )}
1134
1135 {/* 空态:整个待办全清 vs 单类清空。**公理这一档除外**——它自己那句要
1136 分清「查过、没矛盾」和「还没查过」,通用空态说不出这个差别 */}
1137 {isQueueSel &&
1138 active !== "violations" &&
1139 active !== "defects" &&
1140 counts[active] === 0 && (
1141 <div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">
1142 {queueEmpty ? S.review.empty : S.review.categoryEmpty}
1143 </div>
1144 )}
1145
1146 {active === "duplicates" && counts.duplicates > 0 && (
1147 <div className="space-y-3">
1148 {asDuplicates().map((item) => (
1149 <DuplicateCard
1150 key={item.id}
1151 item={item}
1152 busy={
1153 decide.isPending && decide.variables?.id === item.id
1154 }
1155 onDecide={(action) =>
1156 decide.mutate({ id: item.id, action })
1157 }
1158 />
1159 ))}
1160 </div>
1161 )}
1162
1163 {active === "conflicts" && counts.conflicts > 0 && (
1164 <div className="space-y-3">
1165 {asConflicts().map((c) => (
1166 <ConflictRow
1167 key={c.id}
1168 conflict={c}
1169 busy={
1170 conflictAction.isPending &&
1171 conflictAction.variables?.id === c.id
1172 }
1173 onResolve={(action, closeAt) =>
1174 conflictAction.mutate({ id: c.id, action, closeAt })
1175 }
1176 />
1177 ))}
1178 </div>
1179 )}
1180
1181 {active === "unconfirmed" && counts.unconfirmed > 0 && (
1182 <div className="space-y-3">
1183 {asFacts().map((fact) => (
1184 <UnconfirmedRow
1185 key={fact.id}
1186 fact={fact}
1187 busy={
1188 (factAction.isPending &&
1189 factAction.variables?.id === fact.id) ||
1190 (closeFactAction.isPending &&
1191 closeFactAction.variables?.id === fact.id)
1192 }
1193 onReject={() =>
1194 factAction.mutate({ id: fact.id, action: "reject" })
1195 }
1196 onClose={(validTo) =>
1197 closeFactAction.mutate({ id: fact.id, validTo })
1198 }
1199 />
1200 ))}
1201 </div>
1202 )}
1203
1204 {active === "pending" && counts.pending > 0 && (
1205 <div className="space-y-3">
1206 {asPending().map((fact) => (
1207 <PendingFactRow
1208 key={fact.id}
1209 fact={fact}
1210 canDecide={canDecidePending}
1211 busy={
1212 pendingAction.isPending &&
1213 pendingAction.variables?.id === fact.id
1214 }
1215 onConfirm={() =>
1216 pendingAction.mutate({ id: fact.id, action: "confirm" })
1217 }
1218 onReject={() =>
1219 pendingAction.mutate({ id: fact.id, action: "reject" })
1220 }
1221 />
1222 ))}
1223 </div>
1224 )}
1225
1226 {active === "lowconf" && counts.lowconf > 0 && (
1227 <div className="space-y-3">
1228 {asFacts().map((fact) => (
1229 <FactRow
1230 key={fact.id}
1231 fact={fact}
1232 busy={
1233 factAction.isPending &&
1234 factAction.variables?.id === fact.id
1235 }
1236 onConfirm={() =>
1237 factAction.mutate({ id: fact.id, action: "confirm" })
1238 }
1239 onReject={() =>
1240 factAction.mutate({ id: fact.id, action: "reject" })
1241 }
1242 />
1243 ))}
1244 </div>
1245 )}
1246
1247 {active === "defects" && (
1248 <div className="space-y-3">
1249 {counts.defects === 0 && (
1250 <div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">
1251 {S.review.categoryEmpty}
1252 </div>
1253 )}
1254 {asDefects().map((d) => (
1255 <DefectRow
1256 key={d.id}
1257 defect={d}
1258 busy={
1259 defectAction.isPending &&
1260 defectAction.variables?.id === d.id
1261 }
1262 onDecide={(resolution) =>
1263 defectAction.mutate({ id: d.id, resolution })
1264 }
1265 />
1266 ))}
1267 </div>
1268 )}
1269
1270 {active === "violations" && (
1271 <div className="space-y-3">
1272 {/* 按钮在这一档里,不在页头:只有看这一档的人才想重跑。
1273 报告留在按钮旁边——空结果要说清是「没矛盾」还是「没判据」 */}
1274 <div className="flex items-center gap-3">
1275 {/* ghost 而不是实心白:这和「探查映射」是同一种东西——
1276 手动触发一次分析,不是这一页的主操作。留一个实心白给
1277 真正的决定(确认 / 合并) */}
1278 <button
1279 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
1280 disabled={runCheck.isPending}
1281 onClick={() => runCheck.mutate()}
1282 >
1283 {runCheck.isPending
1284 ? S.review.checking
1285 : S.review.runCheck}
1286 </button>
1287 {runCheck.data && (
1288 <span className="text-xs text-neutral-500">
1289 {/* 三种结果说三句话。**`found` 不是要报的数**:
1290 重跑会把已裁决的那些重新算出来,说「3 处矛盾」而
1291 列表只剩一条,看起来像界面漏了东西 */}
1292 {runCheck.data.predicates_with_axioms === 0
1293 ? S.review.checkNoAxioms
1294 : runCheck.data.inserted > 0
1295 ? S.review.checkFound(runCheck.data.inserted)
1296 : runCheck.data.found > 0
1297 ? S.review.checkNothingNew
1298 : S.review.checkClean(runCheck.data.edges)}
1299 </span>
1300 )}
1301 </div>
1302 {counts.violations === 0 && !runCheck.data && (
1303 <div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">
1304 {S.review.checkNeverRun}
1305 </div>
1306 )}
1307 {asViolations().map((v) => (
1308 <div
1309 key={v.id}
1310 className={
1311 v.id === search.item
1312 ? "rounded-xl ring-1 ring-[var(--u-contest)]"
1313 : undefined
1314 }
1315 >
1316 <ViolationRow
1317 violation={v}
1318 busy={
1319 violationAction.isPending &&
1320 violationAction.variables?.id === v.id
1321 }
1322 onDecide={(resolution, closeAt) =>
1323 violationAction.mutate({ id: v.id, resolution, closeAt })
1324 }
1325 onDuplicates={() => select("duplicates")}
1326 onOntology={() => navigate({ to: "/ontology" })}
1327 />
1328 </div>
1329 ))}
1330 </div>
1331 )}
1332
1333 {active === "merges" &&
1334 (counts.merges === 0 ? (
1335 <div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">
1336 {S.review.historyEmpty}
1337 </div>
1338 ) : (
1339 <div className="space-y-2">
1340 {asMerges().map((m) => (
1341 <MergeRow
1342 key={m.id}
1343 merge={m}
1344 busy={revert.isPending && revert.variables === m.id}
1345 onRevert={() => revert.mutate(m.id)}
1346 />
1347 ))}
1348 </div>
1349 ))}
1350
1351 {active === "decisions" &&
1352 (history.isPending ? (
1353 <p className="text-sm text-neutral-500">{S.nav.loading}</p>
1354 ) : (history.data?.total ?? 0) === 0 ? (
1355 <div className="glass rounded-xl p-10 text-center text-sm text-neutral-500">
1356 {S.review.decisionsEmpty}
1357 </div>
1358 ) : (
1359 <div className="space-y-2">
1360 {(history.data?.events ?? []).map((e) => (
1361 <DecisionRow key={e.id} e={e} />
1362 ))}
1363 </div>
1364 ))}
1365
1366 {/* 单一分页:queue/merges 走客户端切片,decisions 服务端分页 */}
1367 {active !== "decisions" && (
1368 <Pager
1369 total={counts[active]}
1370 pageSize={PAGE_SIZE[active]}
1371 page={page}
1372 onPage={setPage}
1373 />
1374 )}
1375 {active === "decisions" && (
1376 <Pager
1377 total={history.data?.total ?? 0}
1378 pageSize={PAGE_SIZE.decisions}
1379 page={page}
1380 onPage={setPage}
1381 />
1382 )}
1383 </section>
1384 )}
1385 </div>
1386 </div>
1387 </div>
1388 );
1389}