KernelPage.tsx
19.6 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
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>
);
}