DraftWorkbench.tsx 25.1 KB
/**
 * 草案工作台:左边是草案列表(按种类分页签、可搜索筛选、可勾选批量处理),右边是选中那条的完整配置。
 * 采纳即上线(不进审批与待办);体检没过的照样能采纳,差什么就地显示,也能就地改(表单或一句话让 AI 改)。
 * 采纳时自动带上它依赖的待定草案(流程卡引用的对象、动作的审批决策表……)。
 * 状态筛选按当前页签生效;「对账」页签列出文档里的要求哪些落实了、哪些有出入、哪些漏了。
 */
import { Search, Sparkles } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Tabs } from "@/components/kit";
import { Badge, Card, Empty, Spinner, Term } from "@/components/ui";
import { confirmDialog } from "@/lib/dialog";
import { errText, onto, TYPE_LABEL, type ConceptBrief, type ModelDraftItem, type ModelRunFull, type ModelSopDraft, type ModelWatchDraft } from "@/lib/onto";
import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { TypeBadge } from "../common";
import { CheckView } from "./CheckView";
import { DraftDetail, type DraftCtx } from "./DraftDetail";
import { DraftGraph } from "./DraftGraph";
import { SopDraftView, sopState } from "./SopDraftView";
import { WatchDraftView, WatchRow } from "./WatchDraftView";
import { bindLabel, DRAFT_STATE, draftState, itemKind, itemName, itemTypeKey, weakReason, type DraftState } from "./util";

type Tab = "all" | "object_type" | "link_type" | "function" | "action" | "sop" | "watch" | "check" | "graph" | "other";
const KINDS: { key: Exclude<Tab, "all" | "sop" | "watch" | "check" | "graph" | "other">; label: string }[] = [
  { key: "object_type", label: "对象" }, { key: "link_type", label: "关系" },
  { key: "function", label: "函数" }, { key: "action", label: "动作" },
];
const STATE_ORDER: Record<DraftState, number> = { pending: 0, held: 1, live: 2, rejected: 3 };
/** 函数先按类别排:指标 → 规则 → 决策表 → 对象集 → AI,同类里再按对象归在一起 */
const FN_ORDER = ["aggregate", "rule", "decision", "object_set", "ai"];
const fnRank = (it: ModelDraftItem) => { const i = FN_ORDER.indexOf(itemTypeKey(it)); return i < 0 ? FN_ORDER.length : i; };
const fnObject = (it: ModelDraftItem) => String(it.payload?.spec?.object_type || "");

/** 每个页签自己的状态筛选:元素看「待定 / 需补全 / 已上线…」,流程卡看「要改」,定时看「有问题」 */
type Filter = "" | "pending" | "weak" | "ready" | "live" | "held" | "rejected" | "errors" | "issue" | "done" | "dropped";
const sopErrors = (s: ModelSopDraft) => (s.validation?.errors || []).length;
function sopFilter(s: ModelSopDraft, f: Filter): boolean {
  const st = sopState(s).label;
  if (f === "pending") return st === "待定";
  if (f === "errors") return st === "待定" && sopErrors(s) > 0;
  if (f === "done") return st === "已上线";
  if (f === "dropped") return st === "不采纳";
  return true;
}
function watchFilter(w: ModelWatchDraft, f: Filter): boolean {
  if (f === "pending") return w.status === "pending";
  if (f === "issue") return w.status === "pending" && !!w.issue;
  if (f === "done") return w.status === "accepted";
  if (f === "dropped") return w.status === "discarded";
  return true;
}
function itemFilter(it: ModelDraftItem, f: Filter): boolean {
  if (!f) return true;
  if (f === "weak") return it.status === "pending" && !!weakReason(it);
  if (f === "ready") return it.status === "pending" && !weakReason(it);
  return draftState(it) === f;
}

export function DraftWorkbench({ run, canEdit, onChanged }: { run: ModelRunFull; canEdit: boolean; onChanged: () => void }) {
  const [tab, setTab] = useState<Tab>("all");
  const [q, setQ] = useState("");
  const [filter, setFilter] = useState<Filter>("");
  const [picked, setPicked] = useState<Set<string>>(new Set());
  const [sel, setSel] = useState("");
  const [busy, setBusy] = useState("");
  const [existing, setExisting] = useState<ConceptBrief[]>([]);
  const loadExisting = useCallback(() => { void onto.concepts({}).then(setExisting).catch(() => setExisting([])); }, []);
  useEffect(loadExisting, [loadExisting]);
  useEffect(() => setFilter(""), [tab]);

  const items = useMemo(() => KINDS.flatMap((k) => run.items[k.key] || []), [run]);
  const others = run.items.other || [];
  const sops = run.sops || [];
  const watches = run.watches || [];
  const reqs = run.reqs || [];
  const ctx: DraftCtx = useMemo(() => {
    const mine = new Set(items.map((x) => `${itemKind(x)}:${itemName(x)}`));
    return {
      items,
      // 这次采纳上线的元素也在「已有」里,去掉,免得同一条出现两次
      existing: existing.filter((c) => !mine.has(`${c.kind}:${c.name}`)),
      objName: Object.fromEntries(existing.filter((c) => c.kind === "object_type").map((c) => [c.id, c.name])),
    };
  }, [items, existing]);

  // 刚跑完那一下,默认勾上能直接用的(体检全过的元素、没错误的流程卡、没问题的定时任务)
  const autoPicked = useRef(false);
  useEffect(() => {
    if (run.status !== "done" || autoPicked.current) return;
    autoPicked.current = true;
    setPicked(new Set([
      ...items.filter((x) => x.status === "pending" && !weakReason(x)).map((x) => x.id),
      ...watches.filter((w) => w.status === "pending" && !w.weak).map((w) => w.id),
    ]));
  }, [run.status, items, watches]);

  const match = (it: ModelDraftItem) => {
    if (q && ![itemName(it), it.payload?.description || "", ...(it.payload?.synonyms || [])].some((s: string) => s.includes(q))) return false;
    return itemFilter(it, filter);
  };
  const sorted = (xs: ModelDraftItem[]) => [...xs].sort((a, b) =>
    (itemKind(a) === "function" && itemKind(b) === "function"
      ? fnRank(a) - fnRank(b) || fnObject(a).localeCompare(fnObject(b), "zh") : 0)
    || STATE_ORDER[draftState(a)] - STATE_ORDER[draftState(b)] || Number(!!weakReason(a)) - Number(!!weakReason(b)));
  const groups = tab === "all" ? KINDS.map((k) => ({ ...k, list: sorted((run.items[k.key] || []).filter(match)) }))
    : KINDS.filter((k) => k.key === tab).map((k) => ({ ...k, list: sorted((run.items[k.key] || []).filter(match)) }));
  const sopList = sops.filter((s) => (!q || s.title.includes(q) || s.description.includes(q)) && sopFilter(s, filter));
  const watchList = watches.filter((w) => (!q || w.title.includes(q)) && watchFilter(w, filter));
  const visible = tab === "sop" ? sopList.map((s) => s.id) : tab === "watch" ? watchList.map((w) => w.id)
    : tab === "other" ? others.map((x) => x.id) : groups.flatMap((g) => g.list.map((x) => x.id));
  useEffect(() => {
    if (tab === "graph" || tab === "check") return;
    if (!visible.includes(sel)) setSel(visible[0] || "");
  }, [tab, visible.join(","), sel]); // eslint-disable-line react-hooks/exhaustive-deps

  // 筛选条:按当前页签算数
  const chips: { key: Filter; label: string; n: number; tone?: string }[] = useMemo(() => {
    if (tab === "check" || tab === "graph" || tab === "other") return [];
    if (tab === "sop") {
      return [{ key: "pending" as Filter, label: "待定", n: sops.filter((s) => sopFilter(s, "pending")).length },
        { key: "errors" as Filter, label: "要改", n: sops.filter((s) => sopFilter(s, "errors")).length, tone: "text-bad" },
        { key: "done" as Filter, label: "已上线", n: sops.filter((s) => sopFilter(s, "done")).length },
        { key: "dropped" as Filter, label: "不采纳", n: sops.filter((s) => sopFilter(s, "dropped")).length }];
    }
    if (tab === "watch") {
      return [{ key: "pending" as Filter, label: "待定", n: watches.filter((w) => watchFilter(w, "pending")).length },
        { key: "issue" as Filter, label: "有问题", n: watches.filter((w) => watchFilter(w, "issue")).length, tone: "text-bad" },
        { key: "done" as Filter, label: "已建好", n: watches.filter((w) => watchFilter(w, "done")).length },
        { key: "dropped" as Filter, label: "不要", n: watches.filter((w) => watchFilter(w, "dropped")).length }];
    }
    const pool = tab === "all" ? items : run.items[tab as keyof typeof run.items] || [];
    return (["pending", "ready", "weak", "live", "held", "rejected"] as Filter[]).map((k) => ({
      key: k, label: k === "weak" ? "需补全" : k === "ready" ? "能直接用" : DRAFT_STATE[k as DraftState].label,
      n: pool.filter((x) => itemFilter(x, k)).length, tone: k === "weak" ? "text-[#b45309]" : k === "ready" ? "text-ok" : undefined,
    }));
  }, [tab, items, sops, watches, run.items]);

  const pickedItems = [...picked].filter((id) => items.some((x) => x.id === id) || others.some((x) => x.id === id));
  const pickedSops = [...picked].filter((id) => sops.some((s) => s.id === id));
  const pickedWatches = [...picked].filter((id) => watches.some((w) => w.id === id));

  const adopt = async (ids: string[], sopIds: string[], watchIds: string[] = []) => {
    if (!ids.length && !sopIds.length && !watchIds.length) return;
    setBusy("adopt");
    try {
      const dep = await onto.modelingDeps(run.id, ids, sopIds, watchIds).catch(() => ({ item_ids: [], items: [] }));
      if (dep.items.length && !(await confirmDialog(`还会一起采纳 ${dep.items.length} 条它们用到的草案`, {
        desc: dep.items.slice(0, 8).map((x) => `「${x.name}」——${x.why}`).join("\n") + (dep.items.length > 8 ? "\n…" : ""),
      }))) { setBusy(""); return; }
      const r = await onto.adoptModeling(run.id, ids, sopIds, watchIds);
      const wr = r.watches || {};
      const held = Object.keys(r.held).length;
      const failed = Object.keys(r.failed).length + Object.values(r.sops).filter(Boolean).length + Object.values(wr).filter(Boolean).length;
      const sopOk = Object.values(r.sops).filter((e) => !e).length;
      const watchOk = Object.values(wr).filter((e) => !e).length;
      toast(held || failed ? "warn" : "ok",
        `采纳 ${r.accepted.length} 条,上线 ${r.published} 个元素${sopOk ? `、${sopOk} 张流程卡` : ""}${watchOk ? `,启用 ${watchOk} 条定时任务` : ""}`,
        held || failed ? `${held + failed} 条没成功,原因写在各条详情里` : "已经生效,提问、流程卡、定时任务都能用了");
      setPicked((old) => new Set([...old].filter((id) => r.failed[id] || (r.sops[id] ?? "") !== "" || (wr[id] ?? "") !== "")));
      loadExisting();
      onChanged();
    } catch (e) { toast("error", "采纳失败", errText(e)); } finally { setBusy(""); }
  };
  const discard = async (ids: string[], sopIds: string[], ask = true, watchIds: string[] = []) => {
    const n = ids.length + sopIds.length + watchIds.length;
    if (!n) return;
    if (ask && !(await confirmDialog(`不要这 ${n} 条?`, { desc: "草案标成不采纳;流程卡草稿归档;定时任务草稿不建。" }))) return;
    setBusy("discard");
    try {
      await onto.discardModeling(run.id, ids, sopIds, watchIds);
      const gone = new Set([...ids, ...sopIds, ...watchIds]);
      setPicked((old) => new Set([...old].filter((id) => !gone.has(id))));
      onChanged();
    } catch (e) { toast("error", errText(e)); } finally { setBusy(""); }
  };
  const toggle = (id: string, on: boolean) => {
    const n = new Set(picked); if (on) n.add(id); else n.delete(id); setPicked(n);
  };
  const pickUsable = () => setPicked(new Set([
    ...items.filter((x) => x.status === "pending" && !weakReason(x)).map((x) => x.id),
    ...sops.filter((s) => sopState(s).label === "待定" && !sopErrors(s)).map((s) => s.id),
    ...watches.filter((w) => w.status === "pending" && !w.weak).map((w) => w.id),
  ]));

  const selItem = [...items, ...others].find((x) => x.id === sel);
  const selSop = sops.find((s) => s.id === sel);
  const selWatch = watches.find((w) => w.id === sel);
  const jumpByName = (name: string) => {
    const hit = items.find((x) => itemName(x) === name || (x.payload?.synonyms || []).includes(name))
      || sops.find((x) => x.title === name) || watches.find((x) => x.title === name);
    if (!hit) return;
    setTab(sops.some((x) => x.id === hit.id) ? "sop" : watches.some((x) => x.id === hit.id) ? "watch" : "all");
    setFilter(""); setQ(""); setSel(hit.id);
  };
  const chk = run.check || {};
  const todo = (chk.items || []).filter((x) => (x.status === "partial" || x.status === "missing") && !x.ignored).length;
  const running = run.status === "running";
  if (running && !items.length && !sops.length) {
    return (
      <Card className="grid min-h-[240px] flex-1 place-items-center p-6 text-center">
        <div><Spinner /><p className="mt-2 text-label text-muted">草案会在「读文档」完成后出现在这里</p></div>
      </Card>
    );
  }
  if (!items.length && !sops.length && !others.length) {
    return <Card className="p-6"><Empty icon={<Sparkles className="h-9 w-9" />} title="这次没有起草出草案"
                                       desc={run.status === "done" ? "文档里可能没有能建模的内容,或者都已经建过了。" : undefined} /></Card>;
  }

  return (
    <Card className="flex min-h-[560px] flex-1 flex-col overflow-hidden">
      <div className="flex flex-wrap items-center gap-2 border-b border-line px-3 pt-1">
        <Tabs className="border-b-0" value={tab} onChange={(t) => { setTab(t); }}
              options={[
                { key: "all", label: "全部", count: items.length },
                ...KINDS.map((k) => ({ key: k.key as Tab, label: <Term>{k.label}</Term>, count: (run.items[k.key] || []).length })),
                { key: "sop", label: <Term>流程卡</Term>, count: sops.length },
                { key: "watch", label: "定时与监控", count: watches.length },
                ...((chk.items || []).length ? [{ key: "check" as Tab, label: <span className={cn(todo && "text-bad")}>对账</span>,
                                                   count: todo || null }] : []),
                { key: "graph", label: "关系图" },
                ...(others.length ? [{ key: "other" as Tab, label: "补充与冲突", count: others.length }] : []),
              ]} />
        <span className="flex-1" />
        {tab !== "check" && tab !== "graph" && (
          <div className="relative py-1.5">
            <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted" />
            <input className="input h-8 w-48 pl-8" placeholder="搜索草案" value={q} onChange={(e) => setQ(e.target.value)} />
          </div>
        )}
      </div>

      {tab !== "check" && (
        <div className="flex flex-wrap items-center gap-1.5 border-b border-line bg-ink/[0.015] px-3 py-2 text-label">
          {chips.filter((c) => c.n || c.key === "pending").map((c) => (
            <button key={c.key} onClick={() => setFilter(filter === c.key ? "" : c.key)}
                    className={cn("chip", c.tone, filter === c.key && "border-brand bg-brand/5 text-brand")}>{c.label} {c.n}</button>
          ))}
          <span className="flex-1" />
          {canEdit && <>
            <button className="btn btn-ghost btn-sm" onClick={pickUsable}>勾选能直接用的</button>
            {picked.size > 0 && <button className="btn btn-ghost btn-sm" onClick={() => setPicked(new Set())}>全不选</button>}
            <button className="btn btn-sm" disabled={!picked.size || !!busy || running} onClick={() => void discard(pickedItems, pickedSops, true, pickedWatches)}>不要所选</button>
            <button className="btn btn-primary btn-sm" disabled={!picked.size || !!busy || running}
                    title={running ? "等这次建模跑完再采纳" : "采纳后直接上线,不用再审批;用到的待定草案会一起带上"}
                    onClick={() => void adopt(pickedItems, pickedSops, pickedWatches)}>
              {busy === "adopt" && <Spinner className="h-3.5 w-3.5" />}采纳并上线({picked.size})</button>
          </>}
        </div>
      )}

      {tab === "check" ? (
        <div className="min-h-0 flex-1"><CheckView run={run} canEdit={canEdit} onJump={jumpByName} onChanged={onChanged} /></div>
      ) : tab === "graph" ? (
        <div className="grid min-h-0 flex-1 lg:grid-cols-[1fr_minmax(320px,34%)]">
          <div className="min-h-[360px] border-line lg:border-r"><DraftGraph ctx={ctx} selected={sel} onSelect={setSel} /></div>
          <div className="min-h-0 overflow-auto">
            {selItem ? <DraftDetail it={selItem} ctx={ctx} runId={run.id} canEdit={canEdit} busy={!!busy} onChanged={onChanged}
                                    onAdopt={() => void adopt([selItem.id], [])} onDiscard={() => void discard([selItem.id], [], false)} onJump={setSel} />
              : <p className="p-4 text-label text-muted">点图上的对象或连线看详情</p>}
          </div>
        </div>
      ) : (
        <div className="grid min-h-0 flex-1 md:grid-cols-[minmax(280px,38%)_1fr]">
          <div className="min-h-0 overflow-auto border-line md:border-r">
            {tab === "sop" ? sopList.map((s) => (
              <SopRow key={s.id} s={s} active={s.id === sel} picked={picked.has(s.id)} canPick={canEdit && sopState(s).label === "待定"}
                      onPick={(on) => toggle(s.id, on)} onOpen={() => setSel(s.id)} />
            )) : tab === "watch" ? watchList.map((w) => (
              <WatchRow key={w.id} w={w} active={w.id === sel} picked={picked.has(w.id)} canPick={canEdit && w.status === "pending"}
                        onPick={(on) => toggle(w.id, on)} onOpen={() => setSel(w.id)} />
            )) : tab === "other" ? others.map((it) => (
              <ItemRow key={it.id} it={it} active={it.id === sel} picked={picked.has(it.id)} canEdit={canEdit}
                       onPick={(on) => toggle(it.id, on)} onOpen={() => setSel(it.id)} />
            )) : groups.map((g) => (
              <div key={g.key}>
                {tab === "all" && (
                  <p className="sticky top-0 z-[1] flex items-center gap-2 border-b border-line bg-surface/95 px-3 py-1.5 text-caption font-semibold text-muted backdrop-blur">
                    <TypeBadge t={g.key} /><span>{g.list.length} 条</span>
                    {canEdit && g.list.some((x) => x.status === "pending") && (
                      <button className="ml-auto font-normal text-brand" onClick={() => {
                        const ids = g.list.filter((x) => x.status === "pending").map((x) => x.id);
                        const all = ids.every((id) => picked.has(id));
                        const n = new Set(picked); ids.forEach((id) => (all ? n.delete(id) : n.add(id))); setPicked(n);
                      }}>{g.list.filter((x) => x.status === "pending").every((x) => picked.has(x.id)) ? "这组全不选" : "这组全选"}</button>
                    )}
                  </p>
                )}
                {g.list.map((it, i) => (
                  <div key={it.id}>
                    {g.key === "function" && (i === 0 || itemTypeKey(g.list[i - 1]) !== itemTypeKey(it)) && (
                      <p className="flex items-center gap-2 border-b border-line/60 bg-ink/[0.025] px-3 py-1 text-caption text-muted">
                        <span className="font-medium text-ink/80">{TYPE_LABEL[itemTypeKey(it)] || "其他"}</span>
                        <span>{g.list.filter((x) => itemTypeKey(x) === itemTypeKey(it)).length} 条</span>
                      </p>
                    )}
                    <ItemRow it={it} active={it.id === sel} picked={picked.has(it.id)} canEdit={canEdit}
                             onPick={(on) => toggle(it.id, on)} onOpen={() => setSel(it.id)} />
                  </div>
                ))}
                {!g.list.length && tab !== "all" && <p className="p-4 text-label text-muted">没有符合条件的</p>}
              </div>
            ))}
            {tab === "watch" && !watchList.length && (
              <p className="p-4 text-label text-muted">{filter ? "没有符合条件的" : run.stages.find((s) => s.key === "schedule")?.status === "skipped"
                ? "这次跳过了「定时与监控」" : "文档里没写要定时做、或要盯着的事"}</p>
            )}
            {tab === "sop" && !sopList.length && (
              <p className="p-4 text-label text-muted">{filter ? "没有符合条件的" : run.stages.find((s) => s.key === "sop")?.status === "skipped"
                ? "这次跳过了「起草流程卡」" : "文档里没有识别出完整的流程"}</p>
            )}
          </div>
          <div className="min-h-0 overflow-auto">
            {selSop ? <SopDraftView s={selSop} runId={run.id} reqs={reqs} canEdit={canEdit} busy={!!busy} onChanged={onChanged}
                                    onJumpName={jumpByName}
                                    onAdopt={() => void adopt([], [selSop.id])} onDiscard={() => void discard([], [selSop.id], false)} />
              : selWatch ? <WatchDraftView w={selWatch} runId={run.id} canEdit={canEdit} busy={!!busy} onChanged={onChanged}
                                           onAdopt={() => void adopt([], [], [selWatch.id])}
                                           onDiscard={() => void discard([], [], false, [selWatch.id])} />
              : selItem ? <DraftDetail it={selItem} ctx={ctx} runId={run.id} canEdit={canEdit} busy={!!busy} onChanged={onChanged}
                                       onAdopt={() => void adopt([selItem.id], [])} onDiscard={() => void discard([selItem.id], [], false)}
                                       onJump={(id) => { setTab("all"); setFilter(""); setQ(""); setSel(id); }} />
                : <p className="p-4 text-label text-muted">选一条看详情</p>}
          </div>
        </div>
      )}
    </Card>
  );
}

function ItemRow({ it, active, picked, canEdit, onPick, onOpen }: {
  it: ModelDraftItem; active: boolean; picked: boolean; canEdit: boolean; onPick: (on: boolean) => void; onOpen: () => void;
}) {
  const st = draftState(it);
  const weak = st === "pending" ? weakReason(it) : "";
  const isConcept = it.kind === "concept_create";
  const desc = isConcept ? it.payload?.description : it.kind_label;
  const fixed = (it.payload?.fix_log || []).length > 0;
  return (
    <div onClick={onOpen}
         className={cn("flex cursor-pointer items-start gap-2 border-b border-line/60 px-3 py-2 hover:bg-ink/[0.03]",
           active && "bg-brand/[0.07] hover:bg-brand/[0.07]")}>
      <input type="checkbox" className="mt-1" disabled={!canEdit || (st !== "pending" && st !== "held")} checked={picked}
             onClick={(e) => e.stopPropagation()} onChange={(e) => onPick(e.target.checked)} />
      <div className="min-w-0 flex-1">
        <p className="flex items-start gap-2">
          <span className={cn("min-w-0 flex-1 break-words text-body font-medium", st === "rejected" && "text-muted line-through")}>{isConcept ? itemName(it) : it.title}</span>
          {isConcept && <span className="ml-auto shrink-0"><TypeBadge t={itemTypeKey(it)} /></span>}
        </p>
        {desc && <p className="mt-0.5 line-clamp-2 break-words text-caption text-muted" title={desc}>{desc}</p>}
        <p className="mt-1 flex flex-wrap items-center gap-1">
          {st !== "pending" && <Badge variant={DRAFT_STATE[st].variant}>{DRAFT_STATE[st].label}</Badge>}
          {st === "pending" && isConcept && (weak
            ? <Badge variant="warn" title={weak}>需补全</Badge>
            : <Badge variant="ok">能直接用</Badge>)}
          {bindLabel(it) && <span className="text-caption text-ok">{bindLabel(it)}</span>}
          {(it.issue || it.concept?.issue) && <Badge variant="danger" title={it.issue || it.concept?.issue}>有问题</Badge>}
          {fixed && <Badge variant="info">AI 按对账改过</Badge>}
          {it.payload?.edited && !fixed && <span className="text-caption text-brand">改过</span>}
        </p>
        {weak && <p className="mt-0.5 line-clamp-1 text-caption text-[#b45309]" title={weak}>{weak}</p>}
      </div>
    </div>
  );
}

function SopRow({ s, active, picked, canPick, onPick, onOpen }: {
  s: ModelSopDraft; active: boolean; picked: boolean; canPick: boolean; onPick: (on: boolean) => void; onOpen: () => void;
}) {
  const st = sopState(s);
  const errs = sopErrors(s);
  const refs = new Set((s.validation?.draft_refs || []).map((r: any) => r.name)).size;
  const cov = s.coverage || {};
  return (
    <div onClick={onOpen}
         className={cn("flex cursor-pointer items-start gap-2 border-b border-line/60 px-3 py-2 hover:bg-ink/[0.03]",
           active && "bg-brand/[0.07] hover:bg-brand/[0.07]")}>
      <input type="checkbox" className="mt-1" disabled={!canPick} checked={picked}
             onClick={(e) => e.stopPropagation()} onChange={(e) => onPick(e.target.checked)} />
      <div className="min-w-0 flex-1">
        <p className="break-words text-body font-medium">{s.title}</p>
        {s.description && <p className="mt-0.5 line-clamp-2 text-caption text-muted">{s.description}</p>}
        <p className="mt-1 flex flex-wrap items-center gap-1">
          <Badge variant={st.variant}>{st.label}</Badge><Badge>{s.step_count} 步</Badge>
          {errs > 0 && <Badge variant="danger">{errs} 处要改</Badge>}
          {refs > 0 && <Badge variant="warn" title="采纳时会一起带上">用到 {refs} 个待采纳草案</Badge>}
          {(cov.total || 0) > 0 && <span className={cn("text-caption", cov.covered === cov.total ? "text-ok" : "text-[#b45309]")}>
            文档 {cov.covered}/{cov.total} 步</span>}
          {s.dry_run?.ok && <span className="text-caption text-ok">试运行通过</span>}
        </p>
      </div>
    </div>
  );
}