KernelPage.tsx 19.6 KB
import {
  Download, FileUp, GitCommit, Link2, Plus, Rocket, RotateCcw, Search, Sparkles, Upload, Wand2,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Badge, Card, Empty, Field, Modal, Pill, Progress, Spinner } from "@/components/ui";
import { api } from "@/lib/api";
import { useHashParams, go } from "@/lib/nav";
import {
  errText, fmtTime, KIND_COLOR, onto, type ConceptBrief, type Diff, type KernelMeta, type KernelStats, type LinkResult,
  type Me, type RevisionRec,
} from "@/lib/onto";
import type { DataSource } from "@/lib/types";
import { useJobPoll } from "@/lib/useJobPoll";
import { cn } from "@/lib/utils";
import { confirmDialog } from "@/lib/dialog";
import { toast } from "@/store/useAppStore";
import { ConceptEditor } from "./ConceptEditor";

export function KernelPage({ me }: { me: Me | null }) {
  const params = useHashParams();
  const canEdit = !!me?.permissions.includes("build");
  const [meta, setMeta] = useState<KernelMeta | null>(null);
  const [stats, setStats] = useState<KernelStats | null>(null);
  const [items, setItems] = useState<ConceptBrief[]>([]);
  const [kind, setKind] = useState("");
  const [status, setStatus] = useState("");
  const [q, setQ] = useState("");
  const [sel, setSel] = useState(params.get("id") || "");
  const [modal, setModal] = useState<"" | "new" | "publish" | "io" | "propose" | "link">("");

  const load = useCallback(() => {
    void onto.concepts({ status }).then(setItems).catch((e) => toast("error", "加载失败", errText(e)));
    void onto.kernelStats().then(setStats).catch(() => undefined);
  }, [status]);
  useEffect(() => { void onto.kernelMeta().then(setMeta); }, []);
  useEffect(load, [load]);
  useEffect(() => { const id = params.get("id"); if (id) setSel(id); }, [params]);

  const shown = useMemo(() => items.filter((c) => (!kind || c.kind === kind)
    && (!q || c.name.includes(q) || c.synonyms.some((s) => s.includes(q)) || c.description.includes(q))), [items, kind, q]);

  if (!meta) return <Spinner />;
  return (
    <div className="space-y-4">
      {/* 工具条 */}
      <Card className="flex flex-wrap items-center gap-2 p-3">
        <div className="flex items-center gap-4 pr-2">
          <div><p className="text-[11px] text-muted">线上版本</p><p className="text-[18px] font-semibold">v{stats?.revision ?? 0}</p></div>
          <div><p className="text-[11px] text-muted">待发布修改</p><p className={cn("text-[18px] font-semibold", stats?.dirty ? "text-warn" : "")}>{stats?.dirty ?? 0}</p></div>
        </div>
        <div className="ml-auto flex flex-wrap gap-2">
          <button className="btn btn-sm" onClick={() => setModal("link")}><Search className="h-3.5 w-3.5" />试链接</button>
          {canEdit && <>
            <button className="btn btn-sm" onClick={() => setModal("propose")}><Wand2 className="h-3.5 w-3.5" />AI 提议本体</button>
            <button className="btn btn-sm" onClick={() => setModal("io")}><FileUp className="h-3.5 w-3.5" />模板 / 导入导出</button>
            <button className="btn btn-sm" onClick={async () => {
              const r = await onto.graphLink(); toast("ok", `已把 ${r.linked} 个图谱实体挂到概念上`, `${r.concepts_with_evidence} 个概念补充了出处`);
            }}><Link2 className="h-3.5 w-3.5" />关联图谱</button>
            <button className="btn btn-sm" onClick={() => setModal("new")}><Plus className="h-3.5 w-3.5" />新建概念</button>
          </>}
          <button className="btn btn-primary btn-sm" onClick={() => setModal("publish")}>
            <Rocket className="h-3.5 w-3.5" />发布 / 版本
          </button>
        </div>
      </Card>

      <div className="grid gap-4 lg:grid-cols-[300px_minmax(0,1fr)]">
        {/* 列表 */}
        <Card className="flex max-h-[calc(100vh-220px)] flex-col">
          <div className="space-y-2 border-b border-line p-2">
            <input className="input" placeholder="搜索名称、别名、定义" value={q} onChange={(e) => setQ(e.target.value)} />
            <div className="flex flex-wrap gap-1">
              <button className={cn("chip", !kind && "border-brand text-brand")} onClick={() => setKind("")}>全部</button>
              {meta.kinds.map((k) => (
                <button key={k.kind} className={cn("chip", kind === k.kind && "border-brand text-brand")}
                        onClick={() => setKind(kind === k.kind ? "" : k.kind)} title={k.desc}>
                  <i className="h-1.5 w-1.5 rounded-full" style={{ background: KIND_COLOR[k.kind] }} />
                  {k.label} {stats?.by_kind[k.kind]?.total ?? 0}
                </button>
              ))}
            </div>
            <select className="input h-8" value={status} onChange={(e) => setStatus(e.target.value)}>
              <option value="">未废弃的</option><option value="draft">仅草稿</option><option value="published">仅已发布</option>
              <option value="dirty">有未发布修改</option><option value="deprecated">已废弃</option>
            </select>
          </div>
          <div className="min-h-0 flex-1 overflow-auto">
            {!shown.length && <Empty title="没有概念" desc={canEdit ? "从模板导入、让 AI 从文档/数据源提议,或手动新建。" : ""} />}
            {shown.map((c) => (
              <button key={c.id} onClick={() => { setSel(c.id); go("kernel", { id: c.id }); }}
                      className={cn("flex w-full items-center gap-2 border-b border-line/60 px-3 py-2 text-left hover:bg-ink/[0.03]",
                        sel === c.id && "bg-brand/5")}>
                <i className="h-2 w-2 shrink-0 rounded-full" style={{ background: KIND_COLOR[c.kind] }} />
                <div className="min-w-0 flex-1">
                  <p className="truncate text-[13px] font-medium">{c.name}</p>
                  <p className="truncate text-[11px] text-muted">{c.kind_label}{c.description ? ` · ${c.description}` : ""}</p>
                </div>
                {c.status === "draft" && <Badge>草稿</Badge>}
                {c.status === "published" && c.dirty && <Badge tone="bg-warn/10 text-warn">改</Badge>}
              </button>
            ))}
          </div>
        </Card>

        {/* 详情 */}
        <div className="min-w-0">
          {sel ? <ConceptEditor key={sel} id={sel} meta={meta} all={items} canEdit={canEdit}
                                onChanged={load} />
            : <Card><Empty icon={<Sparkles className="h-10 w-10" />} title="本体目录"
                           desc="这里是系统的「单一事实来源」:对象、指标、规则、周期、角色、流程都只定义一次,问答、取数、SOP、动作都引用它。编辑改的是草稿,发布后才生效,每个版本都能回滚。" /></Card>}
        </div>
      </div>

      {modal === "new" && <NewConcept meta={meta} onClose={() => setModal("")} onCreated={(id) => { setModal(""); load(); setSel(id); }} />}
      {modal === "publish" && <PublishModal canEdit={canEdit} onClose={() => setModal("")} onDone={load} />}
      {modal === "io" && <ImportExport onClose={() => setModal("")} onDone={load} />}
      {modal === "propose" && <ProposeModal onClose={() => setModal("")} />}
      {modal === "link" && <LinkTester onClose={() => setModal("")} />}
    </div>
  );
}

function NewConcept({ meta, onClose, onCreated }: { meta: KernelMeta; onClose: () => void; onCreated: (id: string) => void }) {
  const [kind, setKind] = useState("object_type");
  const [name, setName] = useState("");
  const [desc, setDesc] = useState("");
  return (
    <Modal open onClose={onClose} title="新建概念"
           footer={<><button className="btn" onClick={onClose}>取消</button>
             <button className="btn btn-primary" disabled={!name.trim()} onClick={async () => {
               try { const c = await onto.createConcept({ kind, name, description: desc }); onCreated(c.id); }
               catch (e) { toast("error", "创建失败", errText(e)); }
             }}>创建</button></>}>
      <div className="space-y-3">
        <Field label="类别">
          <div className="grid grid-cols-3 gap-1.5">
            {meta.kinds.map((k) => (
              <button key={k.kind} onClick={() => setKind(k.kind)} title={k.desc}
                      className={cn("rounded-lg border p-2 text-left text-[12.5px]", kind === k.kind ? "border-brand bg-brand/5" : "border-line")}>
                <span className="font-medium">{k.label}</span>
                <p className="line-clamp-2 text-[11px] text-muted">{k.desc}</p>
              </button>
            ))}
          </div>
        </Field>
        <Field label="名称" required><input className="input" value={name} onChange={(e) => setName(e.target.value)} /></Field>
        <Field label="定义"><textarea className="input" value={desc} onChange={(e) => setDesc(e.target.value)} /></Field>
      </div>
    </Modal>
  );
}

function DiffView({ diff }: { diff: Diff }) {
  return (
    <div className="space-y-1.5 text-[12.5px]">
      {diff.added.map((x) => <p key={x.id}><Badge tone="bg-ok/10 text-ok">新增</Badge> {x.name}</p>)}
      {diff.changed.map((x) => <p key={x.id}><Badge tone="bg-warn/10 text-warn">修改</Badge> {x.name} <span className="text-muted">({x.fields.join("、")})</span></p>)}
      {diff.removed.map((x) => <p key={x.id}><Badge tone="bg-bad/10 text-bad">移除</Badge> {x.name}</p>)}
      {!diff.added.length && !diff.changed.length && !diff.removed.length && <p className="text-muted">没有变化</p>}
    </div>
  );
}

function PublishModal({ canEdit, onClose, onDone }: { canEdit: boolean; onClose: () => void; onDone: () => void }) {
  const [diff, setDiff] = useState<Diff | null>(null);
  const [revs, setRevs] = useState<RevisionRec[]>([]);
  const [note, setNote] = useState("");
  const [busy, setBusy] = useState(false);
  const load = () => { void onto.pendingDiff().then(setDiff); void onto.revisions().then(setRevs); };
  useEffect(load, []);
  const publish = async () => {
    setBusy(true);
    try {
      const r = await onto.publish(note);
      toast("ok", `已发布第 ${r.revision} 版`, "问答、取数、SOP 立即使用新定义");
      setNote(""); load(); onDone();
    } catch (e) { toast("error", "发布失败", errText(e)); } finally { setBusy(false); }
  };
  return (
    <Modal open onClose={onClose} title="发布与版本" width="max-w-2xl"
           desc="发布 = 把草稿转正并冻结一份全量快照。开启「发布前评测闸门」后,需要先在评测中心对待发布版本跑评测。">
      <div className="space-y-4">
        <div>
          <p className="mb-1.5 text-[12px] font-medium text-muted">本次将发布的变更</p>
          {diff ? <DiffView diff={diff} /> : <Spinner />}
          {canEdit && (
            <div className="mt-2 flex gap-2">
              <input className="input flex-1" placeholder="发布说明" value={note} onChange={(e) => setNote(e.target.value)} />
              <button className="btn btn-primary" disabled={busy} onClick={() => void publish()}>
                {busy && <Spinner className="h-3.5 w-3.5" />}发布
              </button>
            </div>
          )}
        </div>
        <div>
          <p className="mb-1.5 text-[12px] font-medium text-muted">历史版本</p>
          <div className="divide-y divide-line rounded-lg border border-line">
            {revs.map((r, i) => (
              <div key={r.revision} className="flex items-center gap-2 px-3 py-2 text-[12.5px]">
                <GitCommit className="h-3.5 w-3.5 text-muted" />
                <span className="font-medium">v{r.revision}</span>
                <span className="min-w-0 flex-1 truncate text-muted">
                  {r.note || "(无说明)"} · +{r.diff.added?.length || 0} ~{r.diff.changed?.length || 0} -{r.diff.removed?.length || 0} · {r.published_by} · {fmtTime(r.created_at)}
                </span>
                {canEdit && i > 0 && (
                  <button className="btn btn-sm" onClick={async () => {
                    if (!(await confirmDialog(`回滚到 v${r.revision}?`, { desc: "会恢复该版本的全部定义,并记为一个新版本" }))) return;
                    try { await onto.rollback(r.revision); toast("ok", "已回滚"); load(); onDone(); }
                    catch (e) { toast("error", "回滚失败", errText(e)); }
                  }}><RotateCcw className="h-3 w-3" />回滚到此</button>
                )}
              </div>
            ))}
            {!revs.length && <p className="p-3 text-[12px] text-muted">还没有发布过</p>}
          </div>
        </div>
      </div>
    </Modal>
  );
}

function ImportExport({ onClose, onDone }: { onClose: () => void; onDone: () => void }) {
  const [tpls, setTpls] = useState<any[]>([]);
  const [yaml, setYaml] = useState("");
  const [result, setResult] = useState<any>(null);
  useEffect(() => { void onto.templates().then(setTpls); }, []);
  return (
    <Modal open onClose={onClose} title="模板 · 导入 · 导出" width="max-w-2xl"
           desc="本体即代码:本体、技能、动作、SOP 都可以导出成 YAML,在客户之间复用。模板导入后是草稿,审阅后发布。">
      <div className="space-y-4">
        <div>
          <p className="mb-1.5 text-[12px] font-medium text-muted">行业模板</p>
          <div className="grid gap-2 sm:grid-cols-2">
            {tpls.map((t) => (
              <div key={t.id} className="rounded-lg border border-line p-3">
                <p className="text-[13px] font-medium">{t.name}</p>
                <p className="mt-0.5 line-clamp-3 text-[12px] text-muted">{t.description}</p>
                <p className="mt-1 text-[11px] text-muted">{t.concepts} 个概念 · {t.capabilities} 个能力 · {t.sops} 个 SOP</p>
                <button className="btn btn-sm mt-2" onClick={async () => {
                  try { const r = await onto.applyTemplate(t.id); setResult(r); onDone(); } catch (e) { toast("error", errText(e)); }
                }}>导入</button>
              </div>
            ))}
          </div>
        </div>
        <div>
          <div className="mb-1.5 flex items-center justify-between">
            <p className="text-[12px] font-medium text-muted">YAML 导入</p>
            <a className="btn btn-sm" href={onto.exportYamlUrl} download="ontology.yaml"><Download className="h-3.5 w-3.5" />导出当前本体</a>
          </div>
          <textarea className="input min-h-[140px] font-mono text-[12px]" value={yaml} onChange={(e) => setYaml(e.target.value)}
                    placeholder={"concepts:\n  - kind: metric\n    name: 销售额\n    spec: {unit: 元}"} />
          <div className="mt-2 flex gap-2">
            <label className="btn btn-sm cursor-pointer"><Upload className="h-3.5 w-3.5" />选文件
              <input type="file" accept=".yaml,.yml" className="hidden" onChange={async (e) => {
                const f = e.target.files?.[0]; if (f) setYaml(await f.text());
              }} /></label>
            <button className="btn btn-primary btn-sm" disabled={!yaml.trim()} onClick={async () => {
              try { setResult(await onto.importYaml(yaml)); onDone(); } catch (e) { toast("error", "导入失败", errText(e)); }
            }}>导入</button>
          </div>
        </div>
        {result && (
          <div className="rounded-lg bg-ink/[0.03] p-3 text-[12.5px]">
            新增 {result.created.length},更新 {result.updated.length},跳过 {result.skipped.length}
            {result.errors.length > 0 && <ul className="mt-1 list-disc pl-5 text-bad">{result.errors.map((x: string) => <li key={x}>{x}</li>)}</ul>}
            {result.sections && Object.entries(result.sections).map(([k, v]: any) => (
              <p key={k} className="text-muted">{k}:{JSON.stringify(v)}</p>
            ))}
          </div>
        )}
      </div>
    </Modal>
  );
}

function ProposeModal({ onClose }: { onClose: () => void }) {
  const [dss, setDss] = useState<DataSource[]>([]);
  const [jobId, setJobId] = useState<number | null>(null);
  const [dsResult, setDsResult] = useState<string>("");
  const job = useJobPoll(jobId);
  useEffect(() => { void api.datasources().then(setDss).catch(() => setDss([])); }, []);
  return (
    <Modal open onClose={onClose} title="AI 提议本体" width="max-w-xl"
           desc="AI 按元模型从文档或数据源里找出对象、指标、规则、周期、角色、流程,全部进入审核队列 —— 人采纳后才会成为概念。">
      <div className="space-y-4">
        <div className="rounded-lg border border-line p-3">
          <p className="text-[13px] font-medium">从已抽取的文档提议</p>
          <p className="mt-0.5 text-[12px] text-muted">每条提议都带原文出处;与已有概念说法冲突的会单独标为「知识冲突」。</p>
          {job ? (
            <div className="mt-2 space-y-1">
              <Progress value={job.progress} />
              <p className="text-[12px] text-muted">{job.message || job.stage}</p>
              {job.status === "done" && <button className="btn btn-sm" onClick={() => go("inbox", { tab: "reviews" })}>去审核</button>}
            </div>
          ) : (
            <button className="btn btn-primary btn-sm mt-2" onClick={async () => {
              try { const r = await onto.proposeFromDocs(); setJobId(r.job_id); toast("info", `开始分析 ${r.chunks} 个片段`); }
              catch (e) { toast("error", errText(e)); }
            }}>开始</button>
          )}
        </div>
        <div className="rounded-lg border border-line p-3">
          <p className="text-[13px] font-medium">从数据源提议</p>
          <p className="mt-0.5 text-[12px] text-muted">已启用的表 → 对象类型(带数据绑定),已定义的指标 → 指标(带取数表达式)。</p>
          <div className="mt-2 flex flex-wrap gap-2">
            {dss.map((d) => (
              <button key={d.id} className="btn btn-sm" onClick={async () => {
                try { const r = await onto.proposeFromDatasource(d.id); setDsResult(`提议 ${r.proposed} 个,冲突 ${r.conflicts} 个,补充 ${r.enriched} 个`); }
                catch (e) { toast("error", errText(e)); }
              }}>{d.name}</button>
            ))}
            {!dss.length && <span className="text-[12px] text-muted">还没有接入数据源</span>}
          </div>
          {dsResult && <p className="mt-2 text-[12px]">{dsResult} <button className="text-brand underline" onClick={() => go("inbox", { tab: "reviews" })}>去审核</button></p>}
        </div>
      </div>
    </Modal>
  );
}

function LinkTester({ onClose }: { onClose: () => void }) {
  const [q, setQ] = useState("");
  const [r, setR] = useState<LinkResult | null>(null);
  return (
    <Modal open onClose={onClose} title="试一试:问句会链接到哪些概念" width="max-w-xl">
      <div className="space-y-3">
        <div className="flex gap-2">
          <input className="input flex-1" value={q} onChange={(e) => setQ(e.target.value)} placeholder="例如:上个月各区域的销售额"
                 onKeyDown={(e) => { if (e.key === "Enter") void onto.link(q).then(setR); }} />
          <button className="btn btn-primary" onClick={() => void onto.link(q).then(setR)}>链接</button>
        </div>
        {r && (
          <div className="flex flex-wrap gap-1.5">
            {r.concepts.map((c) => <Pill key={c.id} color={KIND_COLOR[c.kind]}>{c.name} ← {c.matched.join("、")}</Pill>)}
            {r.instances.map((i) => <Pill key={i.key} color="#64748b">{i.type_name}:{i.label}</Pill>)}
            {r.time && <Badge tone="bg-ok/10 text-ok">时间:{r.time.phrase}</Badge>}
            {!r.concepts.length && !r.instances.length && !r.time && <p className="text-[12px] text-muted">没有识别到(只看已发布的概念)</p>}
          </div>
        )}
      </div>
    </Modal>
  );
}