InboxPage.tsx 28.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
import {
  Bell, Bot, CheckCircle2, ClipboardList, ExternalLink, GitPullRequest, ShieldCheck, Undo2, User, Workflow, XCircle,
} from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Badge, Card, CardHeader, Empty, Field, Modal, Segmented, Spinner } from "@/components/ui";
import { go, useHashParams } from "@/lib/nav";
import {
  errText, fmtTime, onto, STATUS_LABEL, STATUS_TONE, type ActionRun, type InboxCounts, type NotificationRec,
  type ReviewItem, type TaskRec,
} from "@/lib/onto";
import { cn } from "@/lib/utils";
import { promptText } from "@/lib/dialog";
import { toast } from "@/store/useAppStore";
import { EffectList } from "../ask/ActionCard";

type Tab = "approvals" | "tasks" | "reviews" | "runs" | "notifications";

export function InboxPage({ onChanged }: { onChanged?: () => void }) {
  const params = useHashParams();
  const [tab, setTab] = useState<Tab>((params.get("tab") as Tab) || (params.get("task") ? "tasks" : "approvals"));
  const [counts, setCounts] = useState<InboxCounts | null>(null);
  const refreshCounts = useCallback(() => {
    void onto.inbox().then(setCounts).catch(() => undefined);
    onChanged?.();
  }, [onChanged]);
  useEffect(refreshCounts, [refreshCounts, tab]);
  useEffect(() => { const t = params.get("tab") as Tab; if (t) setTab(t); }, [params]);

  const badge = (n?: number) => (n ? <Badge tone="bg-bad/10 text-bad">{n}</Badge> : undefined);
  return (
    <div className="space-y-4">
      <Segmented value={tab} onChange={setTab} options={[
        { key: "approvals", label: "待我审批", badge: badge(counts?.approvals) },
        { key: "tasks", label: "我的待办", badge: badge(counts?.tasks) },
        { key: "reviews", label: "审核队列", badge: badge(counts?.reviews) },
        { key: "runs", label: "动作记录" },
        { key: "notifications", label: "通知", badge: badge(counts?.notifications) },
      ]} />
      {tab === "approvals" && <Approvals focus={params.get("run") || ""} onChanged={refreshCounts} />}
      {tab === "tasks" && <Tasks focus={params.get("task") || ""} onChanged={refreshCounts} />}
      {tab === "reviews" && <Reviews onChanged={refreshCounts} />}
      {tab === "runs" && <Runs focus={params.get("run") || ""} onChanged={refreshCounts} />}
      {tab === "notifications" && <Notifications onChanged={refreshCounts} />}
    </div>
  );
}

// ---------------------------------------------------------------- 审批
const INITIATOR: Record<string, { label: string; icon: React.ReactNode }> = {
  ai: { label: "AI 建议", icon: <Bot className="h-3 w-3" /> },
  sop: { label: "SOP 流程", icon: <Workflow className="h-3 w-3" /> },
  user: { label: "人工", icon: <User className="h-3 w-3" /> },
};

export function RunDetail({ run, onDone }: { run: ActionRun; onDone: () => void }) {
  const [comment, setComment] = useState("");
  const [busy, setBusy] = useState(false);
  const decide = async (approve: boolean) => {
    setBusy(true);
    try {
      const r = await onto.decideAction(run.id, approve, comment);
      toast(r.status === "done" ? "ok" : r.status === "failed" ? "error" : "info",
        approve ? (r.status === "done" ? "已批准并执行" : `已批准,执行结果:${STATUS_LABEL[r.status] || r.status}`) : "已驳回",
        r.error || undefined);
      onDone();
    } catch (e) { toast("error", "操作失败", errText(e)); } finally { setBusy(false); }
  };
  const revert = async () => {
    const reason = await promptText("撤销原因", { desc: "撤销同样需要审批,批准后才会恢复" });
    if (!reason) return;
    try { await onto.revertAction(run.id, reason); toast("ok", "撤销申请已提交审批"); onDone(); }
    catch (e) { toast("error", "撤销失败", errText(e)); }
  };
  const ini = INITIATOR[run.initiator_kind] || INITIATOR.user;
  return (
    <div className="space-y-3 text-[13px]">
      <div className="flex flex-wrap items-center gap-2">
        <Badge tone={STATUS_TONE[run.status]}>{STATUS_LABEL[run.status] || run.status}</Badge>
        <Badge tone="bg-brand/10 text-brand">{ini.icon}{ini.label}</Badge>
        {run.kind === "revert" && <Badge tone="bg-warn/10 text-warn"><Undo2 className="h-3 w-3" />撤销申请</Badge>}
        <span className="text-muted">发起:{run.submitted_by || run.initiator_id} · {fmtTime(run.created_at)}</span>
      </div>
      {run.reason && <p className="rounded-md bg-ink/[0.03] p-2"><b>理由:</b>{run.reason}</p>}
      {run.target_ref && (
        <p className="text-muted">作用对象:
          <button className="text-brand underline" onClick={() => {
            const [, type, key] = run.target_ref.split(":");
            go("objects", { type, key });
          }}>{run.target_ref.split(":").slice(2).join(":")}</button>
        </p>
      )}
      {Object.keys(run.params || {}).length > 0 && (
        <div className="flex flex-wrap gap-1.5">
          {Object.entries(run.params).map(([k, v]) => <Badge key={k}>{k}:{String(v)}</Badge>)}
        </div>
      )}
      <div>
        <p className="mb-1 text-[12px] font-medium text-muted">将执行的效果(审批的就是这份,批准后不会再改)</p>
        <EffectList preview={run.preview} />
      </div>
      {run.result?.effects && (
        <div>
          <p className="mb-1 text-[12px] font-medium text-muted">执行结果</p>
          {run.result.effects.map((e: any, i: number) => (
            <p key={i} className="flex items-center gap-1.5">
              {e.ok ? <CheckCircle2 className="h-3.5 w-3.5 text-ok" /> : <XCircle className="h-3.5 w-3.5 text-bad" />}
              <code>{e.tool}</code> {e.ok ? JSON.stringify(e.result) : e.error}
            </p>
          ))}
        </div>
      )}
      {run.approvals.filter((a) => a.status !== "pending").map((a) => (
        <p key={a.id} className="text-muted">审批:{a.decided_by} {STATUS_LABEL[a.status] || a.status}
          {a.comment ? `(${a.comment})` : ""} · {fmtTime(a.decided_at)}</p>
      ))}
      {run.status === "pending_approval" && (
        run.can_approve === false ? (
          <p className="rounded-md bg-warn/10 p-2 text-warn">{run.cannot_reason}</p>
        ) : (
          <div className="space-y-2 border-t border-line pt-3">
            <textarea className="input min-h-[56px]" placeholder="审批意见(驳回时必填)"
                      value={comment} onChange={(e) => setComment(e.target.value)} />
            <div className="flex justify-end gap-2">
              <button className="btn" disabled={busy || !comment.trim()} onClick={() => void decide(false)}>驳回</button>
              <button className="btn btn-primary" disabled={busy} onClick={() => void decide(true)}>
                {busy && <Spinner className="h-3.5 w-3.5" />}批准并执行
              </button>
            </div>
          </div>
        )
      )}
      {run.status === "done" && run.kind === "normal" && run.preview.action.reversible && (
        <div className="flex justify-end border-t border-line pt-3">
          <button className="btn btn-sm" onClick={() => void revert()}><Undo2 className="h-3.5 w-3.5" />申请撤销</button>
        </div>
      )}
    </div>
  );
}

function RunList({ runs, focus, onDone, empty }: { runs: ActionRun[]; focus: string; onDone: () => void; empty: string }) {
  const [sel, setSel] = useState<string>(focus);
  useEffect(() => { if (focus) setSel(focus); }, [focus]);
  const cur = runs.find((r) => r.id === sel) || null;
  if (!runs.length) return <Card><Empty icon={<ShieldCheck className="h-10 w-10" />} title={empty} /></Card>;
  return (
    <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,1.3fr)]">
      <Card className="divide-y divide-line">
        {runs.map((r) => (
          <button key={r.id} onClick={() => setSel(r.id)}
                  className={cn("block w-full px-3 py-2.5 text-left hover:bg-ink/[0.03]", sel === r.id && "bg-brand/5")}>
            <div className="flex items-center gap-2">
              <span className="min-w-0 flex-1 truncate text-[13px] font-medium">{r.action_name}</span>
              <Badge tone={STATUS_TONE[r.status]}>{STATUS_LABEL[r.status] || r.status}</Badge>
            </div>
            <p className="mt-0.5 truncate text-[12px] text-muted">{r.preview.summary}</p>
            <p className="mt-0.5 text-[11px] text-muted">
              {(INITIATOR[r.initiator_kind] || INITIATOR.user).label} · {r.submitted_by || r.initiator_id} · {fmtTime(r.created_at)}
            </p>
          </button>
        ))}
      </Card>
      <Card>
        {cur ? (
          <>
            <CardHeader title={cur.action_name} desc={`审批单 ${cur.id}`} />
            <div className="p-4"><RunDetail run={cur} onDone={onDone} /></div>
          </>
        ) : <Empty title="选择左侧一条查看详情" />}
      </Card>
    </div>
  );
}

function Approvals({ focus, onChanged }: { focus: string; onChanged: () => void }) {
  const [runs, setRuns] = useState<ActionRun[] | null>(null);
  const load = useCallback(() => { void onto.approvals().then(setRuns).catch((e) => toast("error", errText(e))); }, []);
  useEffect(load, [load]);
  if (!runs) return <Spinner />;
  return <RunList runs={runs} focus={focus} empty="没有待审批的动作"
                  onDone={() => { load(); onChanged(); }} />;
}

function Runs({ focus, onChanged }: { focus: string; onChanged: () => void }) {
  const [runs, setRuns] = useState<ActionRun[] | null>(null);
  const [status, setStatus] = useState("");
  const load = useCallback(() => {
    void onto.actionRuns({ status, limit: 200 }).then(async (rs) => {
      if (focus && !rs.find((r) => r.id === focus)) {
        try { rs = [await onto.actionRun(focus), ...rs]; } catch { /* ignore */ }
      }
      setRuns(rs);
    });
  }, [status, focus]);
  useEffect(load, [load]);
  return (
    <div className="space-y-3">
      <select className="input w-40" value={status} onChange={(e) => setStatus(e.target.value)}>
        <option value="">全部状态</option>
        {["pending_approval", "done", "failed", "rejected", "cancelled", "reverted"].map((s) =>
          <option key={s} value={s}>{STATUS_LABEL[s]}</option>)}
      </select>
      {runs ? <RunList runs={runs} focus={focus} empty="还没有动作记录" onDone={() => { load(); onChanged(); }} /> : <Spinner />}
    </div>
  );
}

// ---------------------------------------------------------------- 任务
function Tasks({ focus, onChanged }: { focus: string; onChanged: () => void }) {
  const [scope, setScope] = useState<"mine" | "all">("mine");
  const [status, setStatus] = useState("open");
  const [items, setItems] = useState<TaskRec[] | null>(null);
  const [sel, setSel] = useState(focus);
  const load = useCallback(() => {
    void onto.tasks({ scope, status }).then(async (ts) => {
      if (focus && !ts.find((t) => t.id === focus)) {
        try { ts = [await onto.task(focus), ...ts]; } catch { /* ignore */ }
      }
      setItems(ts);
    });
  }, [scope, status, focus]);
  useEffect(load, [load]);
  const cur = items?.find((t) => t.id === sel) || null;
  return (
    <div className="space-y-3">
      <div className="flex gap-2">
        <Segmented value={scope} onChange={setScope} options={[{ key: "mine", label: "派给我的" }, { key: "all", label: "全部" }]} />
        <Segmented value={status} onChange={setStatus} options={[
          { key: "open", label: "待办" }, { key: "done", label: "已完成" }, { key: "cancelled", label: "已取消" }]} />
      </div>
      {!items ? <Spinner /> : !items.length ? (
        <Card><Empty icon={<ClipboardList className="h-10 w-10" />} title="没有任务"
                     desc="任务由 SOP 的人工步骤或审批通过的动作派发,派给你本人或你所属的角色。" /></Card>
      ) : (
        <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,1.3fr)]">
          <Card className="divide-y divide-line">
            {items.map((t) => (
              <button key={t.id} onClick={() => setSel(t.id)}
                      className={cn("block w-full px-3 py-2.5 text-left hover:bg-ink/[0.03]", sel === t.id && "bg-brand/5")}>
                <div className="flex items-center gap-2">
                  <span className="min-w-0 flex-1 truncate text-[13px] font-medium">{t.title}</span>
                  {t.overdue && <Badge tone="bg-bad/10 text-bad">已超时</Badge>}
                  <Badge tone={STATUS_TONE[t.status]}>{STATUS_LABEL[t.status]}</Badge>
                </div>
                <p className="mt-0.5 text-[11px] text-muted">
                  派给 {t.assignee || `角色「${t.role}」`} · {t.source_type === "sop" ? "来自 SOP" : "来自动作"} · 截止 {fmtTime(t.due_at)}
                </p>
              </button>
            ))}
          </Card>
          <Card>{cur ? <TaskDetail t={cur} onDone={() => { load(); onChanged(); }} /> : <Empty title="选择一项任务" />}</Card>
        </div>
      )}
    </div>
  );
}

function TaskDetail({ t, onDone }: { t: TaskRec; onDone: () => void }) {
  const [vals, setVals] = useState<Record<string, string>>({});
  const [checks, setChecks] = useState<Record<number, boolean>>({});
  const [busy, setBusy] = useState(false);
  useEffect(() => { setVals({}); setChecks({}); }, [t.id]);
  const allChecked = t.checklist.every((_, i) => checks[i]);
  const submit = async () => {
    setBusy(true);
    try {
      await onto.completeTask(t.id, { ...vals, _checklist: t.checklist.filter((_, i) => checks[i]) });
      toast("ok", "任务已完成", t.source_type === "sop" ? "流程会自动进入下一步" : undefined);
      onDone();
    } catch (e) { toast("error", "提交失败", errText(e)); } finally { setBusy(false); }
  };
  const sopRun = t.context?.sop_run;
  return (
    <>
      <CardHeader title={t.title} desc={`任务 ${t.id}`}
                  right={sopRun && <button className="btn btn-sm" onClick={() => go("sop", { run: sopRun })}>查看流程 <ExternalLink className="h-3 w-3" /></button>} />
      <div className="space-y-3 p-4 text-[13px]">
        {t.description && <p className="whitespace-pre-wrap">{t.description}</p>}
        {t.object_ref && <p className="text-muted">关联对象:{t.object_ref}</p>}
        {t.context?.vars && Object.keys(t.context.vars).length > 0 && (
          <details className="rounded-md border border-line p-2">
            <summary className="cursor-pointer text-[12px] text-muted">流程上下文(前面步骤的结果)</summary>
            <pre className="mt-2 max-h-48 overflow-auto text-[11px]">{JSON.stringify(t.context.vars, null, 2)}</pre>
          </details>
        )}
        {t.status === "open" ? (
          <>
            {t.checklist.length > 0 && (
              <div className="space-y-1">
                <p className="text-[12px] font-medium text-muted">检查清单</p>
                {t.checklist.map((c, i) => (
                  <label key={i} className="flex items-center gap-2">
                    <input type="checkbox" checked={!!checks[i]} onChange={(e) => setChecks({ ...checks, [i]: e.target.checked })} />
                    {c}
                  </label>
                ))}
              </div>
            )}
            {t.form.map((f) => (
              <Field key={f.name} label={f.label} required={f.required}>
                {f.options?.length ? (
                  <select className="input" value={vals[f.name] || ""} onChange={(e) => setVals({ ...vals, [f.name]: e.target.value })}>
                    <option value="">请选择</option>
                    {f.options.map((o) => <option key={o}>{o}</option>)}
                  </select>
                ) : (
                  <textarea className="input min-h-[60px]" value={vals[f.name] || ""}
                            onChange={(e) => setVals({ ...vals, [f.name]: e.target.value })} />
                )}
              </Field>
            ))}
            <div className="flex justify-end gap-2">
              {!t.assignee && <button className="btn" onClick={() => void onto.claimTask(t.id).then(onDone)}>认领</button>}
              <button className="btn btn-primary" disabled={busy || !allChecked} onClick={() => void submit()}
                      title={allChecked ? "" : "请先勾完检查清单"}>
                {busy && <Spinner className="h-3.5 w-3.5" />}完成任务
              </button>
            </div>
          </>
        ) : (
          <div>
            <p className="text-muted">{STATUS_LABEL[t.status]} · {t.completed_by} · {fmtTime(t.completed_at)}</p>
            <pre className="mt-2 rounded bg-ink/5 p-2 text-[12px]">{JSON.stringify(t.result, null, 2)}</pre>
          </div>
        )}
      </div>
    </>
  );
}

// ---------------------------------------------------------------- 审核队列
const SOURCE_LABEL: Record<string, string> = {
  extract: "文档提议", introspect: "数据源提议", ai: "AI", user: "用户", feedback: "答案反馈", template: "模板",
};

function Reviews({ onChanged }: { onChanged: () => void }) {
  const [kind, setKind] = useState("");
  const [status, setStatus] = useState("pending");
  const [data, setData] = useState<{ total: number; items: ReviewItem[] } | null>(null);
  const [picked, setPicked] = useState<Set<string>>(new Set());
  const [open, setOpen] = useState<ReviewItem | null>(null);
  const load = useCallback(() => {
    void onto.reviews({ kind, status, limit: 300 }).then(setData).catch((e) => toast("error", errText(e)));
    setPicked(new Set());
  }, [kind, status]);
  useEffect(load, [load]);
  const batch = async (accept: boolean) => {
    const comment = accept ? "" : (await promptText("驳回意见") || "");
    if (!accept && !comment) return;
    const r = await onto.batchReview([...picked], accept, comment);
    toast(r.failed.length ? "warn" : "ok", `处理 ${r.ok.length} 条${r.failed.length ? `,失败 ${r.failed.length} 条` : ""}`,
      r.failed.slice(0, 3).map((f) => f.error).join(";"));
    load(); onChanged();
  };
  return (
    <div className="space-y-3">
      <div className="flex flex-wrap items-center gap-2">
        <select className="input w-36" value={kind} onChange={(e) => setKind(e.target.value)}>
          <option value="">全部类型</option>
          {[["concept_create", "新概念"], ["concept_update", "概念修改"], ["conflict", "知识冲突"], ["sop_publish", "SOP 发布"],
            ["feedback", "答案反馈"], ["binding", "数据绑定"]].map(([k, l]) => <option key={k} value={k}>{l}</option>)}
        </select>
        <Segmented value={status} onChange={setStatus} options={[
          { key: "pending", label: "待处理" }, { key: "accepted", label: "已采纳" }, { key: "rejected", label: "已驳回" }]} />
        {status === "pending" && picked.size > 0 && (
          <>
            <button className="btn btn-primary btn-sm" onClick={() => void batch(true)}>批量采纳 {picked.size}</button>
            <button className="btn btn-sm" onClick={() => void batch(false)}>批量驳回</button>
          </>
        )}
        <span className="ml-auto text-[12px] text-muted">共 {data?.total ?? 0} 条</span>
      </div>
      {!data ? <Spinner /> : !data.items.length ? (
        <Card><Empty icon={<GitPullRequest className="h-10 w-10" />} title="审核队列是空的"
                     desc="AI 从文档/数据源提议的概念、知识冲突、SOP 发布申请、用户纠错都会出现在这里,采纳后才生效。" /></Card>
      ) : (
        <Card className="divide-y divide-line">
          {status === "pending" && (
            <label className="flex items-center gap-2 px-3 py-2 text-[12px] text-muted">
              <input type="checkbox" checked={picked.size === data.items.length}
                     onChange={(e) => setPicked(e.target.checked ? new Set(data.items.map((i) => i.id)) : new Set())} />
              全选
            </label>
          )}
          {data.items.map((it) => (
            <div key={it.id} className="flex items-center gap-2 px-3 py-2">
              {status === "pending" && (
                <input type="checkbox" checked={picked.has(it.id)} onChange={(e) => {
                  const n = new Set(picked); if (e.target.checked) n.add(it.id); else n.delete(it.id); setPicked(n);
                }} />
              )}
              <button className="min-w-0 flex-1 text-left" onClick={() => setOpen(it)}>
                <div className="flex items-center gap-2">
                  <Badge tone={it.kind === "conflict" ? "bg-bad/10 text-bad" : "bg-brand/10 text-brand"}>{it.kind_label}</Badge>
                  <span className="truncate text-[13px] font-medium">{it.title}</span>
                </div>
                <p className="mt-0.5 truncate text-[12px] text-muted">
                  {SOURCE_LABEL[it.source] || it.source}
                  {it.confidence ? ` · 置信度 ${(it.confidence * 100).toFixed(0)}%` : ""}
                  {it.payload?.description ? ` · ${it.payload.description}` : ""}
                  {it.comment ? ` · 意见:${it.comment}` : ""}
                </p>
              </button>
              <span className="text-[11px] text-muted">{fmtTime(it.created_at)}</span>
            </div>
          ))}
        </Card>
      )}
      {open && <ReviewModal item={open} onClose={() => setOpen(null)} onDone={() => { setOpen(null); load(); onChanged(); }} />}
    </div>
  );
}

function ReviewModal({ item, onClose, onDone }: { item: ReviewItem; onClose: () => void; onDone: () => void }) {
  const [payload, setPayload] = useState<any>(item.payload);
  const [comment, setComment] = useState("");
  const [busy, setBusy] = useState(false);
  const pending = item.status === "pending";
  const decide = async (accept: boolean) => {
    setBusy(true);
    try {
      await onto.decideReview(item.id, { accept, comment, payload: accept ? payload : undefined });
      toast("ok", accept ? "已采纳" : "已驳回");
      onDone();
    } catch (e) { toast("error", "处理失败", errText(e)); } finally { setBusy(false); }
  };
  return (
    <Modal open onClose={onClose} title={item.title} desc={`${item.kind_label} · ${SOURCE_LABEL[item.source] || item.source}`}
           width="max-w-2xl"
           footer={pending ? <>
             <input className="input mr-auto h-8 max-w-xs" placeholder="意见(驳回必填)" value={comment} onChange={(e) => setComment(e.target.value)} />
             <button className="btn" disabled={busy || !comment.trim()} onClick={() => void decide(false)}>驳回</button>
             <button className="btn btn-primary" disabled={busy} onClick={() => void decide(true)}>
               {item.kind === "conflict" ? "采用提议的定义" : "采纳"}
             </button>
           </> : undefined}>
      <div className="space-y-3 text-[13px]">
        {item.kind === "concept_create" && (
          <>
            <div className="grid grid-cols-2 gap-3">
              <Field label="名称"><input className="input" value={payload.name} disabled={!pending}
                                         onChange={(e) => setPayload({ ...payload, name: e.target.value })} /></Field>
              <Field label="类别"><input className="input" value={payload.kind} disabled /></Field>
            </div>
            <Field label="定义"><textarea className="input min-h-[56px]" value={payload.description || ""} disabled={!pending}
                                        onChange={(e) => setPayload({ ...payload, description: e.target.value })} /></Field>
            <Field label="别名(逗号分隔)"><input className="input" value={(payload.synonyms || []).join(",")} disabled={!pending}
                                              onChange={(e) => setPayload({ ...payload, synonyms: e.target.value.split(/[,,、]/).map((s) => s.trim()).filter(Boolean) })} /></Field>
            <Field label="结构定义(spec)"><pre className="max-h-40 overflow-auto rounded bg-ink/5 p-2 text-[11.5px]">{JSON.stringify(payload.spec, null, 2)}</pre></Field>
            {payload.bindings?.length > 0 && <p className="text-muted">附带 {payload.bindings.length} 条数据绑定,采纳后一并创建</p>}
            <Evidence items={payload.evidence} />
          </>
        )}
        {item.kind === "conflict" && (
          <>
            <div className="grid gap-3 md:grid-cols-2">
              <div className="rounded-lg border border-line p-2.5">
                <p className="mb-1 text-[12px] font-medium text-muted">当前定义</p>
                <p>{payload.current?.description}</p>
                <pre className="mt-1 text-[11.5px]">{JSON.stringify(payload.current?.spec, null, 2)}</pre>
              </div>
              <div className="rounded-lg border border-warn/40 bg-warn/5 p-2.5">
                <p className="mb-1 text-[12px] font-medium text-warn">文档里的新说法</p>
                <p>{payload.proposed?.description}</p>
                <pre className="mt-1 text-[11.5px]">{JSON.stringify(payload.proposed?.spec, null, 2)}</pre>
              </div>
            </div>
            <Evidence items={payload.evidence} />
            <p className="text-[12px] text-muted">采纳 = 用新说法覆盖(修改会进入草稿,需发布才生效);驳回 = 保留现有定义。</p>
          </>
        )}
        {item.kind === "concept_update" && <pre className="rounded bg-ink/5 p-2 text-[12px]">{JSON.stringify(payload, null, 2)}</pre>}
        {item.kind === "sop_publish" && (
          <>
            <p>试运行:{payload.dry_run?.ok ? "通过" : "未通过"}({fmtTime(payload.dry_run?.at)})</p>
            {payload.note && <p>发布说明:{payload.note}</p>}
            {payload.warnings?.length > 0 && <ul className="list-disc pl-5 text-warn">{payload.warnings.map((w: string) => <li key={w}>{w}</li>)}</ul>}
            <button className="btn btn-sm" onClick={() => go("sop", { id: payload.def_id })}>打开 SOP 查看 <ExternalLink className="h-3 w-3" /></button>
          </>
        )}
        {item.kind === "feedback" && (
          <>
            <p><b>问题:</b>{payload.question}</p>
            <div className="max-h-40 overflow-auto rounded bg-ink/5 p-2 text-[12px] whitespace-pre-wrap">{payload.answer}</div>
            <p><b>用户意见:</b>{payload.comment}</p>
            <Field label="正确答案要点(采纳后成为评测用例)">
              <textarea className="input min-h-[56px]" value={payload.correction || ""} disabled={!pending}
                        onChange={(e) => setPayload({ ...payload, correction: e.target.value })} />
            </Field>
          </>
        )}
        {!pending && <p className="text-muted">{STATUS_LABEL[item.status]} · {item.decided_by} · {fmtTime(item.decided_at)} {item.comment}</p>}
      </div>
    </Modal>
  );
}

function Evidence({ items }: { items?: any[] }) {
  if (!items?.length) return null;
  return (
    <div>
      <p className="mb-1 text-[12px] font-medium text-muted">文档出处</p>
      <ul className="space-y-1">
        {items.slice(0, 5).map((e: any, i: number) => (
          <li key={i} className="rounded bg-ink/[0.03] p-2 text-[12px]"><b>{e.heading || e.chunk_id}</b> {e.snippet}</li>
        ))}
      </ul>
    </div>
  );
}

// ---------------------------------------------------------------- 通知
function Notifications({ onChanged }: { onChanged: () => void }) {
  const [items, setItems] = useState<NotificationRec[]>([]);
  const load = useCallback(() => { void onto.notifications().then((r) => setItems(r.items)); }, []);
  useEffect(load, [load]);
  return (
    <Card>
      <CardHeader title="通知" right={<button className="btn btn-sm" onClick={() => void onto.readNotifications().then(() => { load(); onChanged(); })}>全部已读</button>} />
      {!items.length ? <Empty icon={<Bell className="h-10 w-10" />} title="没有通知" /> : (
        <div className="divide-y divide-line">
          {items.map((n) => (
            <button key={n.id} className="block w-full px-4 py-2.5 text-left hover:bg-ink/[0.03]"
                    onClick={() => {
                      void onto.readNotifications([n.id]).then(onChanged);
                      if (n.link) window.location.hash = n.link.replace(/^#/, "#");
                    }}>
              <div className="flex items-center gap-2">
                {!n.read && <i className="h-2 w-2 rounded-full bg-brand" />}
                <span className={cn("text-[13px]", !n.read && "font-medium")}>{n.title}</span>
                <span className="ml-auto text-[11px] text-muted">{fmtTime(n.created_at)}</span>
              </div>
              {n.body && <p className="mt-0.5 truncate text-[12px] text-muted">{n.body}</p>}
            </button>
          ))}
        </div>
      )}
    </Card>
  );
}