Commit 006919cf by 黄南光

大幅优化本体论系统_8107版本

1 parent 11608bac
Showing 99 changed files with 2535 additions and 468 deletions
...@@ -70,6 +70,19 @@ ...@@ -70,6 +70,19 @@
"WEB_DIST": "dist_8106" "WEB_DIST": "dist_8106"
}, },
"port": 8106 "port": 8106
},
{
"name": "onto-8107",
"runtimeExecutable": "./.venv/Scripts/python.exe",
"runtimeArgs": [
"scripts/serve_8103.py"
],
"env": {
"PORT": "8107",
"WEB_DIST": "dist_8107",
"ONTO_WORKSPACE": "xianda_inv"
},
"port": 8107
} }
] ]
} }
\ No newline at end of file \ No newline at end of file
"""多智能体提问(Ask 2.0)。
主 Agent(编排)把问题拆给子 Agent:
- 知识 Agent:本体概念、文档原文、关系网多跳推理、影响分析
- 问数 Agent:实时取数、结果解读、按需下钻
- 行动 Agent:把结论变成可提交的动作卡、可运行的流程卡
每个 Agent 都是「思考 → 调用 → 观察 → 再思考」的循环;工具调用一律经 `capability/mcp.call_logged`
(审计 via=ask:<agent>),和外部 Agent 同一份目录、同一套权限与审批 —— 没有内部特权通道。
全过程以事件流推给前端,并完整落库,历史对话可以原样回放。
"""
"""行动 Agent:把知识与数据的结论变成可提交审批的动作卡、可运行的流程卡。只建议,不执行。"""
from __future__ import annotations
import json
import logging
import time
from fastapi import HTTPException
from ..capability import actions, defs
from ..core import llm
from ..kernel import service as ksvc
from . import prompts
from .base import AGENT_META, think_json
from .trace import Tracer
log = logging.getLogger(__name__)
def actions_catalog() -> str:
out = []
for a in defs.list_defs("action", "published"):
ps = ", ".join(f"{p['name']}({p['label']}{',必填' if p['required'] else ''}"
f"{',可选值 ' + '/'.join(p['enum']) if p['enum'] else ''})"
for p in a["spec"].get("params") or [])
tgt = a["spec"].get("target_type")
tname = ""
if tgt:
t = ksvc.rt_get(tgt)
tname = t["name"] if t else tgt
out.append(f"- {a['name']}({a['display_name'] or a['name']}):{a['description']} 参数 [{ps}]"
+ (f" 作用于对象类型「{tname}」,需给 object_key" if tgt else ""))
return "\n".join(out) or "(无)"
def sops_catalog() -> str:
from ..sop import service as sop_service
return "\n".join(f"- {d['title']}:{d['description']}"
for d in sop_service.list_defs(status="published")[:30]) or "(无)"
def run(tracer: Tracer, question: str, links: dict, links_text: str, results: dict,
results_text: str) -> dict:
span = tracer.span("agent")
started = time.time()
label = AGENT_META["action"]["label"]
tracer.emit({"type": "agent_start", "span": span, "parent": "lead", "agent": "action", "label": label,
"task": "根据结论给出可提交的动作与可运行的流程卡"})
try:
d = think_json(tracer, span, "action", [
{"role": "system", "content": prompts.ACTION_SYSTEM.format(actions=actions_catalog(),
sops=sops_catalog())},
{"role": "user", "content": prompts.ACTION_USER.format(
question=question, links=links_text, results=llm.truncate_to_tokens(results_text, 9000))}])
except Exception as e: # noqa: BLE001
log.warning("行动 Agent 失败:%s", str(e)[:200])
d = {}
suggest = [a for a in d.get("suggest_actions") or [] if isinstance(a, dict)][:3]
sops = [s for s in d.get("suggest_sops") or [] if isinstance(s, dict)][:2]
cards = prepare_cards(suggest, links, results, results_text, question)
ok_cards = [c for c in cards if not c.get("error")]
summary = (f"建议 {len(ok_cards)} 个动作" + (f"、{len(sops)} 个流程卡" if sops else "")
if (ok_cards or sops) else "没有需要执行的动作")
tracer.emit({"type": "agent_done", "span": span, "parent": "lead", "agent": "action", "label": label,
"summary": summary, "findings": [f"{c['display_name']}:{c.get('reason', '')}" for c in ok_cards],
"insights": [], "confidence": 0.8 if ok_cards else 0.5, "ok": True,
"ms": int((time.time() - started) * 1000)})
return {"cards": cards, "sops": sops, "summary": summary}
def prepare_cards(suggest: list[dict], links: dict, results: dict, results_text: str,
question: str) -> list[dict]:
"""动作建议 → 可提交的卡片。参数常常要等取数之后才定得下来:先替换 $k1.字段 引用;
还不能通过校验,就拿执行结果让模型补一次参数。卡片带参数定义,人可以改了再提交。"""
out = []
for s in suggest:
ref = str(s.get("action") or "")
a = defs.find(ref, "action")
params = actions.render(s.get("params") or {}, results or {})
card = {"action": ref, "display_name": (a or {}).get("display_name") or ref,
"params": params if isinstance(params, dict) else {},
"object_key": str(actions.render(s.get("object_key") or "", results or {}) or ""),
"reason": s.get("reason") or ""}
if a is None or a["status"] != "published":
card["error"] = "动作不存在或未发布"
out.append(card)
continue
spec = a["spec"]
card["action_id"] = a["id"]
card["param_defs"] = spec.get("params") or []
card["target_type"] = spec.get("target_type") or ""
if not card["object_key"] and spec.get("target_type"):
inst = next((i for i in links.get("instances") or []
if i["concept_id"] == spec["target_type"]), None)
if inst:
card["object_key"] = inst["key"]
try:
card["preview"] = actions.prepare(a["id"], card["params"], card["object_key"])
except HTTPException as e:
card["error"] = str(e.detail)
fixed = _fill_params(a, card, results_text, links, question) if results_text else None
if fixed:
try:
card["preview"] = actions.prepare(a["id"], fixed["params"], fixed["object_key"])
card.update(params=fixed["params"], object_key=fixed["object_key"])
card.pop("error", None)
except HTTPException as e2:
card["error"] = str(e2.detail)
out.append(card)
return out
def _fill_params(a: dict, card: dict, results_text: str, links: dict, question: str) -> dict | None:
from .lead import links_text
spec = a["spec"]
target = ""
if spec.get("target_type"):
ot = ksvc.rt_get(spec["target_type"]) or {}
target = ot.get("name") or spec["target_type"]
try:
res = llm.chat_json([{"role": "user", "content": prompts.FILL_PROMPT.format(
name=a.get("display_name") or a["name"], desc=a.get("description") or "", target=target or "无",
params=json.dumps(spec.get("params") or [], ensure_ascii=False),
criteria=";".join(c["expression"] for c in spec.get("criteria") or []) or "无",
question=question or card.get("reason") or "", links=links_text(links),
results=llm.truncate_to_tokens(results_text, 6000))}], temperature=0)
except Exception as e: # noqa: BLE001
log.info("补全动作参数失败:%s", str(e)[:120])
return None
if not isinstance(res, dict):
return None
params = {k: v for k, v in (res.get("params") or {}).items() if v not in ("", None)}
if res.get("why"):
card["reason"] = f"{card.get('reason') or ''}({res['why']})".strip()
return {"params": params, "object_key": str(res.get("object_key") or card.get("object_key") or "")}
"""会话、轮次、推理轨迹的读写与反馈。"""
from __future__ import annotations
import datetime as dt
import time
from typing import Any
from fastapi import HTTPException
from sqlalchemy import func, select
from ..core import identity
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit
from ..orchestrator.models import AskTrace, Conversation, Turn
EMPTY_LINKS = {"concepts": [], "instances": [], "time": None}
# 服务重启等原因留下的「running」轮次,超过这个时间就当作已中断显示
STALE_RUNNING = dt.timedelta(minutes=10)
def ensure_conversation(conv_id: str, question: str) -> str:
actor = identity.current()
with session() as s:
if conv_id:
c = s.get(Conversation, conv_id)
if c is not None and c.workspace == actor.workspace:
c.updated_at = now()
s.commit()
return c.id
c = Conversation(id=new_id("cv"), workspace=actor.workspace, title=question[:60],
created_by=actor.id)
s.add(c)
s.commit()
return c.id
def new_turn(conv_id: str, question: str) -> str:
actor = identity.current()
with session() as s:
seq = (s.scalar(select(func.max(Turn.seq)).where(Turn.conversation_id == conv_id)) or 0) + 1
turn = Turn(id=new_id("tn"), conversation_id=conv_id, seq=seq, question=question,
created_by=actor.id, links_json=jdump(EMPTY_LINKS))
s.add(turn)
s.commit()
return turn.id
def history(conv_id: str, limit: int = 3) -> list[dict]:
with session() as s:
rows = s.scalars(select(Turn).where(Turn.conversation_id == conv_id,
Turn.status == "done")
.order_by(Turn.seq.desc()).limit(limit)).all()
return [{"question": t.question, "answer": (t.answer or "")[:500],
"plan": jload(t.plan_json, {})} for t in reversed(rows)]
def _links(raw: str) -> dict:
v = jload(raw, {})
if not isinstance(v, dict):
v = {}
return {"concepts": v.get("concepts") or [], "instances": v.get("instances") or [],
"time": v.get("time")}
def _status(t: Turn) -> str:
if t.status == "running" and t.created_at and now() - t.created_at > STALE_RUNNING:
return "aborted"
return t.status or "done"
def turn_dict(t: Turn) -> dict:
return {"id": t.id, "conversation_id": t.conversation_id, "seq": t.seq,
"question": t.question, "status": _status(t), "links": _links(t.links_json),
"plan": jload(t.plan_json, {}) or {}, "steps": jload(t.steps_json, []) or [],
"answer": t.answer or "", "citations": jload(t.citations_json, []) or [],
"data_refs": jload(t.data_refs_json, []) or [], "actions": jload(t.actions_json, []) or [],
"sops": jload(t.sops_json, []) or [], "rating": t.rating or 0, "feedback": t.feedback or "",
"duration_ms": t.duration_ms or 0, "created_at": iso(t.created_at)}
def list_conversations(limit: int = 50) -> list[dict]:
actor = identity.current()
with session() as s:
rows = s.scalars(select(Conversation).where(
Conversation.workspace == actor.workspace, Conversation.created_by == actor.id)
.order_by(Conversation.updated_at.desc()).limit(limit)).all()
counts = dict(s.execute(select(Turn.conversation_id, func.count(Turn.id))
.where(Turn.conversation_id.in_([r.id for r in rows] or ["-"]))
.group_by(Turn.conversation_id)).all())
return [{"id": c.id, "title": c.title, "turns": int(counts.get(c.id, 0)),
"updated_at": iso(c.updated_at)} for c in rows]
def get_conversation(conv_id: str) -> dict:
with session() as s:
c = s.get(Conversation, conv_id)
if c is None or c.workspace != identity.current().workspace:
raise HTTPException(404, "会话不存在")
rows = s.scalars(select(Turn).where(Turn.conversation_id == conv_id).order_by(Turn.seq)).all()
stats = {r.turn_id: jload(r.stats_json, {}) for r in s.scalars(
select(AskTrace).where(AskTrace.turn_id.in_([t.id for t in rows] or ["-"]))).all()}
turns = []
for t in rows:
d = turn_dict(t)
d["stats"] = stats.get(t.id) or {}
d["has_trace"] = t.id in stats
turns.append(d)
return {"id": c.id, "title": c.title, "turns": turns}
def delete_conversation(conv_id: str) -> None:
get_conversation(conv_id)
with session() as s:
for t in s.scalars(select(Turn).where(Turn.conversation_id == conv_id)).all():
tr = s.get(AskTrace, t.id)
if tr is not None:
s.delete(tr)
s.delete(t)
s.delete(s.get(Conversation, conv_id))
s.commit()
def get_turn(turn_id: str) -> dict:
with session() as s:
t = s.get(Turn, turn_id)
if t is None:
raise HTTPException(404, "记录不存在")
return turn_dict(t)
def get_trace(turn_id: str) -> dict:
get_turn(turn_id)
with session() as s:
tr = s.get(AskTrace, turn_id)
if tr is None:
return {"turn_id": turn_id, "events": [], "stats": {}, "memory": {}}
return {"turn_id": turn_id, "events": jload(tr.events_json, []) or [],
"stats": jload(tr.stats_json, {}) or {}, "memory": jload(tr.memory_json, {}) or {}}
def save_turn(turn_id: str, status: str, *, links: dict | None = None, plan: dict | None = None,
steps: list | None = None, answer: str | None = None, citations: list | None = None,
data_refs: list | None = None, cards: list | None = None, sops: list | None = None,
started: float | None = None) -> None:
with session() as s:
t = s.get(Turn, turn_id)
if t is None:
return
t.status = status
if links is not None:
t.links_json = jdump({**EMPTY_LINKS, **links})
if plan is not None:
t.plan_json = jdump(plan)
if steps is not None:
t.steps_json = jdump(steps)
if answer is not None:
t.answer = answer
if citations is not None:
t.citations_json = jdump(citations)
if data_refs is not None:
t.data_refs_json = jdump(data_refs)
if cards is not None:
t.actions_json = jdump(cards)
if sops is not None:
t.sops_json = jdump(sops)
if started is not None:
t.duration_ms = int((time.time() - started) * 1000)
s.commit()
def save_trace(turn_id: str, events: list[dict], stats: dict, memory: dict | None = None) -> None:
with session() as s:
tr = s.get(AskTrace, turn_id)
if tr is None:
tr = AskTrace(turn_id=turn_id)
s.add(tr)
tr.events_json = jdump(events)
tr.stats_json = jdump(stats)
tr.memory_json = jdump(memory or {})
s.commit()
def feedback(turn_id: str, rating: int, comment: str = "", correction: str = "") -> dict:
from ..governance import review
from ..memory import service as memory
t = get_turn(turn_id)
with session() as s:
row = s.get(Turn, turn_id)
row.rating = 1 if rating > 0 else -1 if rating < 0 else 0
row.feedback = (comment or "")[:4000]
s.commit()
audit.record("ask.feedback", "turn", turn_id, f"{'👍' if rating > 0 else '👎'} {comment[:200]}")
learned: dict[str, Any] = memory.on_feedback(turn_id, rating, comment, correction)
item = None
if rating < 0 or correction:
item = review.propose("feedback", f"答案纠错:{t['question'][:80]}", {
"turn_id": turn_id, "question": t["question"], "answer": t["answer"][:3000],
"comment": comment, "correction": correction,
"plan": t["plan"], "links": t["links"]}, source="feedback", target_ref=turn_id)
return {"ok": True, "review_item": item, "learned": learned}
"""推理轨迹:一次提问里所有 Agent、工具调用、思考与中间结果的事件流。
事件都带 `span`(这件事的编号)和 `parent`(谁发起的),前端据此画成
「主 Agent → 子 Agent → 工具调用」的树;`ts` 是相对提问开始的毫秒数,回放按它还原节奏。
多个子 Agent 在不同线程里并行跑,都往同一个 Tracer 里写;提问的生成器从队列里取出来推给前端。
落库时把逐字的思考片段合并成整段,逐字的作答片段不存(答案本身另存)。
"""
from __future__ import annotations
import itertools
import queue
import threading
import time
from typing import Any
_DONE = object()
# 落库时要瘦身的大字段
_MAX_ROWS = 50
def _slim(ev: dict) -> dict:
out = dict(ev)
for key in ("result", "event"):
v = out.get(key)
if isinstance(v, dict) and isinstance(v.get("rows"), list) and len(v["rows"]) > _MAX_ROWS:
out[key] = {**v, "rows": v["rows"][:_MAX_ROWS], "rows_truncated": True}
if isinstance(out.get("rows"), list) and len(out["rows"]) > _MAX_ROWS:
out["rows"] = out["rows"][:_MAX_ROWS]
return out
class Tracer:
def __init__(self) -> None:
self.started = time.time()
self.q: queue.Queue = queue.Queue()
self.events: list[dict] = []
self.cancel = threading.Event()
self._lock = threading.Lock()
self._seq = itertools.count(1)
self._ids: dict[str, itertools.count] = {}
self._open_thought: dict[str, int] = {} # span → events 里正在拼接的思考事件下标
self.stats = {"agents": 0, "tools": 0, "hops": 0, "sql": 0, "llm": 0, "memory": 0}
# ---------- 编号 ----------
def span(self, prefix: str) -> str:
with self._lock:
c = self._ids.setdefault(prefix, itertools.count(1))
return f"{prefix}{next(c)}"
def elapsed_ms(self) -> int:
return int((time.time() - self.started) * 1000)
# ---------- 写 ----------
def emit(self, ev: dict) -> None:
ev = dict(ev)
with self._lock:
ev["seq"] = next(self._seq)
ev.setdefault("ts", self.elapsed_ms())
t = ev.get("type")
if t == "agent_start":
self.stats["agents"] += 1
elif t == "tool_start":
self.stats["tools"] += 1
elif t == "tool_event":
et = (ev.get("event") or {}).get("type")
if et == "hop":
self.stats["hops"] += 1
elif et in ("sql", "execute"):
self.stats["sql"] += 1
self._persist(ev)
self.q.put(ev)
def _persist(self, ev: dict) -> None:
t = ev.get("type")
if t == "answer_delta":
return
sp = str(ev.get("span") or "")
if t == "thought":
idx = self._open_thought.get(sp)
if idx is not None:
self.events[idx]["text"] += ev.get("text", "")
return
self.events.append(dict(ev))
self._open_thought[sp] = len(self.events) - 1
return
self._open_thought.pop(sp, None)
self.events.append(_slim(ev))
def thought(self, span: str, text: str, agent: str = "") -> None:
if text:
self.emit({"type": "thought", "span": span, "agent": agent, "text": text})
def close(self) -> None:
self.q.put(_DONE)
# ---------- 读 ----------
def drain(self):
"""生成器:把事件按顺序吐出来,直到 close()。"""
while True:
ev = self.q.get()
if ev is _DONE:
return
yield ev
def snapshot(self) -> list[dict]:
with self._lock:
return [dict(e) for e in self.events]
def summary(self) -> dict[str, Any]:
return {**self.stats, "duration_ms": self.elapsed_ms()}
...@@ -196,13 +196,92 @@ def _prepare(action: dict, params: dict, object_key: str = "") -> dict: ...@@ -196,13 +196,92 @@ def _prepare(action: dict, params: dict, object_key: str = "") -> dict:
raise HTTPException(422, f"效果「{e.get('label') or tool.title}」无法执行:{ex.detail}") from ex raise HTTPException(422, f"效果「{e.get('label') or tool.title}」无法执行:{ex.detail}") from ex
effects.append({"tool": tool.name, "label": e.get("label") or tool.title, "args": args, effects.append({"tool": tool.name, "label": e.get("label") or tool.title, "args": args,
"preview": pv, "risk_level": tool.risk_level, "external": tool.external}) "preview": pv, "risk_level": tool.risk_level, "external": tool.external})
return {"action": {"id": action["id"], "name": action["name"], # 效果渲染后的实际取值(如采购金额)也进环境:审批决策要按「这一单多少钱」判,
"display_name": action["display_name"], "version": action["version"], # 而金额是效果里算出来的,不是入参。
"reversible": spec.get("reversible", False), eff: dict[str, Any] = {}
"risk_level": action["risk_level"], for e in effects:
"approver_roles": spec["approval"]["approver_roles"]}, for k, v in (e["args"] or {}).items():
"params": p, "target_ref": target_ref, "effects": effects, if isinstance(v, dict):
"summary": ";".join(e["preview"].get("summary", "") for e in effects)} eff.update({str(kk): vv for kk, vv in v.items() if not isinstance(vv, (dict, list))})
elif not isinstance(v, list):
eff[str(k)] = v
env["eff"] = eff
out = {"action": {"id": action["id"], "name": action["name"],
"display_name": action["display_name"], "version": action["version"],
"reversible": spec.get("reversible", False),
"risk_level": action["risk_level"],
"approver_roles": spec["approval"]["approver_roles"]},
"params": p, "target_ref": target_ref, "effects": effects,
"summary": ";".join(e["preview"].get("summary", "") for e in effects)}
if (spec["approval"].get("decision") or {}).get("function"):
env["rel"] = _related(spec.get("target_type") or "", env.get("obj_key") or "")
dec = _approval_decision(spec["approval"]["decision"], env)
if dec:
out["approval_decision"] = dec
if dec.get("priority"):
out["action"]["priority"] = dec["priority"]
if dec.get("approver_roles"):
out["action"]["approver_roles"] = dec["approver_roles"]
return out
def _related(type_id: str, key: str) -> dict:
"""目标对象沿 n:1 关系走一跳,按关系名放进 rel,供审批决策写
`rel.供货.status == '延期'` 这类跨对象条件。查不到就给空,不让审批流程挂掉。"""
if not type_id or not key:
return {}
out: dict[str, Any] = {}
try:
# 取 2 条:正好 1 条才说明这一侧是唯一的,才敢当成「这一单的供应商」用。
# 方向不限 —— 「商品 ← 供货 ← 供应商」从商品这边看是入边,但供应商依然唯一。
for g in objects.linked(type_id, key, limit=2) or []:
items = g.get("items") or []
if len(items) != 1:
continue
props = {**(items[0].get("properties") or {}),
"key": items[0].get("key"), "label": items[0].get("label")}
out[g["link_type"]] = props # 按关系名,如 rel.供货.status
out.setdefault(g["object_type"], props) # 也按对象名,如 rel.供应商.status
except Exception: # noqa: BLE001
log.debug("解析关联对象失败", exc_info=True)
return out
def _approval_decision(cfg: dict, env: dict) -> dict:
"""用本体里的决策表算这一单的优先级与审批人。
决策表算不出来(没发布、输入缺失、表达式报错)时返回空,调用方退回动作的静态 risk_level ——
审批本身绝不能因为决策表有问题就卡住。
"""
from ..kernel import decision as decision_engine, service as ksvc
name = cfg.get("function") or ""
try:
fn = ksvc.rt_fn(name, "decision")
except Exception: # noqa: BLE001
log.info("审批决策表「%s」不可用,按动作风险等级定优先级", name)
return {}
values = {}
for k, v in (cfg.get("inputs") or {}).items():
try:
values[k] = render(v, env)
except Exception: # noqa: BLE001
log.info("审批决策输入「%s」求值失败", k)
return {}
try:
r = decision_engine.evaluate(fn.get("spec") or {}, values)
except Exception: # noqa: BLE001
log.info("审批决策表「%s」求值失败", name)
return {}
res = r.get("result") or {}
if isinstance(res, list):
res = res[0] if res else {}
prio = str(res.get("priority") or "").upper()
approver = res.get("approver_roles") or res.get("approver") or ""
roles = [str(x) for x in approver] if isinstance(approver, list) else ([str(approver)] if approver else [])
return {"function": name, "inputs": values, "matched": r.get("matched") or [],
"priority": prio if prio in PRIORITIES else "",
"approver_roles": roles,
"why": f"按决策表「{name}」:" + ",".join(f"{k}={v}" for k, v in values.items())}
# ---------------- 提议 ---------------- # ---------------- 提议 ----------------
...@@ -248,7 +327,12 @@ def propose(action_ref: str, params: dict, *, object_key: str = "", reason: str ...@@ -248,7 +327,12 @@ def propose(action_ref: str, params: dict, *, object_key: str = "", reason: str
prio = (priority or "").upper() prio = (priority or "").upper()
if prio and prio not in PRIORITIES: if prio and prio not in PRIORITIES:
raise HTTPException(422, f"优先级只能是 {'/'.join(PRIORITIES)}") raise HTTPException(422, f"优先级只能是 {'/'.join(PRIORITIES)}")
prio = prio or _RISK_PRIORITY.get(prep["action"]["risk_level"], "P2") # 优先级三级兜底:调用方显式指定 → 本体里的审批决策表按这一单的实际情况算 → 动作的静态风险等级
dec = prep.get("approval_decision") or {}
prio = prio or dec.get("priority") or _RISK_PRIORITY.get(prep["action"]["risk_level"], "P2")
if dec.get("why"):
evidence = list(evidence or []) + [{"kind": "rule", "text": dec["why"],
"ref": dec.get("function", "")}]
key_src = jdump({"a": prep["action"]["id"], "p": prep["params"], "t": prep["target_ref"], key_src = jdump({"a": prep["action"]["id"], "p": prep["params"], "t": prep["target_ref"],
"s": source_ref}) "s": source_ref})
idem = hashlib.sha1(key_src.encode("utf-8")).hexdigest() idem = hashlib.sha1(key_src.encode("utf-8")).hexdigest()
......
...@@ -123,6 +123,25 @@ def validate_action(spec: dict) -> tuple[dict, str]: ...@@ -123,6 +123,25 @@ def validate_action(spec: dict) -> tuple[dict, str]:
appr = spec.get("approval") or {} appr = spec.get("approval") or {}
approval = {"mode": "manual", # 当前阶段:所有动作一律人工审批 approval = {"mode": "manual", # 当前阶段:所有动作一律人工审批
"approver_roles": [str(x) for x in appr.get("approver_roles") or [] if x]} "approver_roles": [str(x) for x in appr.get("approver_roles") or [] if x]}
# 审批决策函数:用本体里的决策表按「这一单的实际情况」算优先级和审批人。
# 没有它的话优先级只能取动作的静态 risk_level —— 手册里「金额≥5万归采购经理、
# 涉及延期供应商 P0」这类规则就永远落不了地。
dec = appr.get("decision") or {}
if isinstance(dec, dict) and str(dec.get("function") or "").strip():
inputs = {}
for k, v in (dec.get("inputs") or {}).items():
k = str(k).strip()
if not k:
continue
inputs[k] = v
if isinstance(v, str) and v.startswith("="):
try:
unknown = [x for x in rules.free_names(v[1:]) if x not in env_names | {"eff", "rel"}]
except rules.RuleError as ex:
raise HTTPException(422, f"审批决策输入「{k}」的表达式有误:{ex}") from ex
if unknown:
raise HTTPException(422, f"审批决策输入「{k}」引用了未定义的变量:{'、'.join(unknown)}")
approval["decision"] = {"function": str(dec["function"]).strip(), "inputs": inputs}
reversible = bool(spec.get("reversible", True)) and all( reversible = bool(spec.get("reversible", True)) and all(
registry.TOOLS[e["tool"]].revert is not None for e in effects) registry.TOOLS[e["tool"]].revert is not None for e in effects)
return ({"target_type": target, "params": params, "criteria": criteria, "effects": effects, return ({"target_type": target, "params": params, "criteria": criteria, "effects": effects,
......
...@@ -189,6 +189,7 @@ def init_db() -> None: ...@@ -189,6 +189,7 @@ def init_db() -> None:
from ..orchestrator import models as _orc_models # noqa: F401 from ..orchestrator import models as _orc_models # noqa: F401
from ..evals import models as _eval_models # noqa: F401 from ..evals import models as _eval_models # noqa: F401
from ..memory import models as _mem_models # noqa: F401 from ..memory import models as _mem_models # noqa: F401
from ..watch import models as _watch_models # noqa: F401
Base.metadata.create_all(engine) Base.metadata.create_all(engine)
insp = inspect(engine) insp = inspect(engine)
with engine.begin() as conn: with engine.begin() as conn:
......
...@@ -28,7 +28,9 @@ PERMISSIONS: dict[str, tuple[str, ...]] = { ...@@ -28,7 +28,9 @@ PERMISSIONS: dict[str, tuple[str, ...]] = {
"ask": ("viewer", "operator", "builder", "approver"), "ask": ("viewer", "operator", "builder", "approver"),
"operate": ("operator", "builder", "approver"), # 发起 Action 提议、启动 SOP、完成任务 "operate": ("operator", "builder", "approver"), # 发起 Action 提议、启动 SOP、完成任务
"build": ("builder",), # 改本体、能力、SOP 定义 "build": ("builder",), # 改本体、能力、SOP 定义
"review": ("builder",), # 处理审核队列 # 处理审核队列(含变更提案)。审批人也要有:菜单把「审批与待办」给了他们,
# 里面就有变更提案,以前点下去直接 403 —— 审批人看得见、批不了。
"review": ("builder", "approver"),
"approve": ("approver",), # 审批 Action "approve": ("approver",), # 审批 Action
"admin": (), "admin": (),
} }
......
...@@ -226,7 +226,8 @@ async def delete_concept(cid: str, _: identity.Actor = Depends(require("build")) ...@@ -226,7 +226,8 @@ async def delete_concept(cid: str, _: identity.Actor = Depends(require("build"))
@router.post("/concepts/{cid}/deprecate") @router.post("/concepts/{cid}/deprecate")
async def deprecate(cid: str, body: dict | None = None, async def deprecate(cid: str, body: dict | None = None,
_: identity.Actor = Depends(require("build"))): _: identity.Actor = Depends(require("build"))):
return service.deprecate_concept(cid, (body or {}).get("reason", "")) b = body or {}
return service.deprecate_concept(cid, b.get("reason", ""), force=bool(b.get("force")))
@router.get("/concepts/{cid}/usage") @router.get("/concepts/{cid}/usage")
......
...@@ -24,8 +24,14 @@ def metric(ref: str) -> dict: ...@@ -24,8 +24,14 @@ def metric(ref: str) -> dict:
def resolve_time(m: dict, time: Any, calendar_ref: str = "") -> dict | None: def resolve_time(m: dict, time: Any, calendar_ref: str = "") -> dict | None:
"""time 可以是 {start,end} / {ref} / 'last' / '2026-08'。按指标关联的日历解析期。""" """time 可以是 {start,end} / {ref} / 'last' / '2026-08'。按指标关联的日历解析期。
if not time:
'none' / '' 表示显式不按时间过滤 —— 像「库存缺口」这种快照指标本来就没有时间列,
强行塞一个 'current' 会让它取不了数。
"""
if not time or (isinstance(time, str) and time.strip().lower() in ("none", "不限")):
return None
if isinstance(time, dict) and str(time.get("ref") or "").strip().lower() in ("none", "不限"):
return None return None
if isinstance(time, str): if isinstance(time, str):
time = {"ref": time} time = {"ref": time}
......
...@@ -366,8 +366,17 @@ def save_layout(positions: dict[str, dict]) -> int: ...@@ -366,8 +366,17 @@ def save_layout(positions: dict[str, dict]) -> int:
return n return n
def deprecate_concept(cid: str, reason: str = "") -> dict: def deprecate_concept(cid: str, reason: str = "", force: bool = False) -> dict:
"""废弃一块积木。被别的积木或流程卡引用时默认拦住 —— 以前不拦,废弃「商品」不会有
任何提示,但「库存→记录→商品」这条关系和「库存缺口」这个指标当场就哑了。"""
before = get_concept(cid) before = get_concept(cid)
if not force:
refs = usage(cid)
if refs:
names = "、".join(f"「{r['name']}」" for r in refs[:5])
raise HTTPException(409, f"「{before['name']}」还被 {len(refs)} 处引用({names}"
f"{' 等' if len(refs) > 5 else ''}),"
"确认要废弃就勾选「仍然废弃」,否则先改掉这些引用")
with session() as s: with session() as s:
c = _load(s, cid) c = _load(s, cid)
c.status = "deprecated" c.status = "deprecated"
......
...@@ -23,6 +23,7 @@ from .kernel import api as kernel_api ...@@ -23,6 +23,7 @@ from .kernel import api as kernel_api
from .memory import api as memory_api from .memory import api as memory_api
from .orchestrator import api as ask_api from .orchestrator import api as ask_api
from .sop import api as sop_api, triggers as sop_triggers from .sop import api as sop_api, triggers as sop_triggers
from .watch import api as watch_api, scheduler as watch_scheduler
from .core import db from .core import db
from .core.config import get_settings from .core.config import get_settings
from .ingest.parse import ParseError from .ingest.parse import ParseError
...@@ -52,7 +53,12 @@ async def lifespan(app: FastAPI): ...@@ -52,7 +53,12 @@ async def lifespan(app: FastAPI):
if pipeline.reap_stale(): if pipeline.reap_stale():
log.warning("清理了上次进程残留的数据管道 / 业务建模运行") log.warning("清理了上次进程残留的数据管道 / 业务建模运行")
gov_users.seed() gov_users.seed()
sop_triggers.start_scheduler() try:
from .watch import service as watch_service
watch_service.migrate_sop_triggers()
except Exception: # noqa: BLE001
log.exception("迁移流程卡触发器失败")
watch_scheduler.start()
log.info("服务启动完成,数据目录 %s", settings.data_path) log.info("服务启动完成,数据目录 %s", settings.data_path)
yield yield
...@@ -113,6 +119,7 @@ app.include_router(sop_api.router) ...@@ -113,6 +119,7 @@ app.include_router(sop_api.router)
app.include_router(ask_api.router) app.include_router(ask_api.router)
app.include_router(eval_api.router) app.include_router(eval_api.router)
app.include_router(memory_api.router) app.include_router(memory_api.router)
app.include_router(watch_api.router)
app.include_router(mcp_api.router) app.include_router(mcp_api.router)
......
"""经验中枢:问答案例、组织记忆(mem0 式)、操作习惯与纠错回流,让系统越用越聪明。"""
"""经验中枢接口 /api/memory:案例、组织记忆、操作习惯的查看与维护。"""
from __future__ import annotations
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from ..core import identity
from ..core.identity import require
from . import service
router = APIRouter(prefix="/api/memory", tags=["memory"])
class CaseIn(BaseModel):
status: str | None = None
question: str | None = None
answer_summary: str | None = None
class FactIn(BaseModel):
text: str = ""
kind: str = "fact"
scope: str = ""
status: str | None = None
class PinIn(BaseModel):
question: str
class PatternIn(BaseModel):
adopt: bool = True
adopted_ref: str = ""
@router.get("/stats")
async def stats(_: identity.Actor = Depends(require("ask"))):
return service.stats()
@router.get("/cases")
async def cases(status: str = "", q: str = "", _: identity.Actor = Depends(require("ask"))):
return service.list_cases(status, q)
@router.put("/cases/{case_id}")
async def update_case(case_id: str, body: CaseIn, _: identity.Actor = Depends(require("build"))):
return service.update_case(case_id, **body.model_dump(exclude_none=True))
@router.delete("/cases/{case_id}")
async def delete_case(case_id: str, _: identity.Actor = Depends(require("build"))):
service.delete_case(case_id)
return {"ok": True}
@router.get("/facts")
async def facts(status: str = "", kind: str = "", _: identity.Actor = Depends(require("ask"))):
return service.list_facts(status, kind)
@router.post("/facts")
async def add_fact(body: FactIn, actor: identity.Actor = Depends(require("ask"))):
# 组织口径只有搭建者能直接写;其他人写的都是个人偏好
scope = body.scope if actor.can("build") else "user"
kind = body.kind if actor.can("build") else "preference"
return service.add_fact(body.text.strip(), kind, scope=scope, source="manual")
@router.put("/facts/{fact_id}")
async def update_fact(fact_id: str, body: FactIn, _: identity.Actor = Depends(require("build"))):
return service.update_fact(fact_id, text=body.text or None, status=body.status, kind=body.kind,
scope=body.scope or None)
@router.delete("/facts/{fact_id}")
async def delete_fact(fact_id: str, _: identity.Actor = Depends(require("build"))):
service.delete_fact(fact_id)
return {"ok": True}
@router.get("/patterns")
async def patterns(status: str = "", _: identity.Actor = Depends(require("build"))):
return service.list_patterns(status)
@router.get("/suggestions")
async def suggestions(_: identity.Actor = Depends(require("ask"))):
return service.suggestions()
@router.post("/patterns/{pattern_id}/decide")
async def decide(pattern_id: str, body: PatternIn, _: identity.Actor = Depends(require("ask"))):
return service.decide_pattern(pattern_id, body.adopt, body.adopted_ref)
@router.post("/pin")
async def pin(body: PinIn, _: identity.Actor = Depends(require("ask"))):
return service.pin_question(body.question)
"""经验中枢的表:问答案例、组织记忆、操作习惯。全部按工作区(本体)隔离。"""
from __future__ import annotations
import datetime as dt
from sqlalchemy import DateTime, Float, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column
from ..core.db import _LONGTEXT, Base
from ..core.dbx import now
class MemCase(Base):
"""问答案例:一次成功提问的「问题 → 用到的概念 → 分派与工具路径 → 取数 SQL → 结论」。
status:draft(自动沉淀)→ verified(点赞或人工确认,可走快路径)/ deprecated(点踩过多或人工废弃)。
"""
__tablename__ = "onto_mem_case"
id: Mapped[str] = mapped_column(String(64), primary_key=True)
workspace: Mapped[str] = mapped_column(String(64), default="default", index=True)
question: Mapped[str] = mapped_column(Text, default="")
question_norm: Mapped[str] = mapped_column(String(512), default="", index=True)
intent: Mapped[str] = mapped_column(String(32), default="")
concepts_json: Mapped[str] = mapped_column(Text, default="[]")
plan_json: Mapped[str] = mapped_column(_LONGTEXT, default="{}")
sql_json: Mapped[str] = mapped_column(_LONGTEXT, default="[]")
answer_summary: Mapped[str] = mapped_column(Text, default="")
embedding_json: Mapped[str] = mapped_column(_LONGTEXT, default="")
status: Mapped[str] = mapped_column(String(16), default="draft", index=True)
score: Mapped[float] = mapped_column(Float, default=0.5)
hits: Mapped[int] = mapped_column(Integer, default=0)
up_votes: Mapped[int] = mapped_column(Integer, default=0)
down_votes: Mapped[int] = mapped_column(Integer, default=0)
fast_hits: Mapped[int] = mapped_column(Integer, default=0)
source_turn: Mapped[str] = mapped_column(String(64), default="")
created_by: Mapped[str] = mapped_column(String(128), default="")
last_hit_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True)
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
updated_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now, onupdate=now)
class MemFact(Base):
"""组织记忆:口径、偏好、事实。
scope:workspace(全组织)/ role(某业务角色)/ user(个人)。
kind:definition(业务口径,改动要审核)/ preference(个人偏好,直接生效)/ fact(其他事实)。
status:active / pending(等审核)/ deprecated。
"""
__tablename__ = "onto_mem_fact"
id: Mapped[str] = mapped_column(String(64), primary_key=True)
workspace: Mapped[str] = mapped_column(String(64), default="default", index=True)
scope: Mapped[str] = mapped_column(String(16), default="workspace")
scope_ref: Mapped[str] = mapped_column(String(128), default="")
kind: Mapped[str] = mapped_column(String(16), default="fact")
text: Mapped[str] = mapped_column(Text, default="")
embedding_json: Mapped[str] = mapped_column(_LONGTEXT, default="")
status: Mapped[str] = mapped_column(String(16), default="active", index=True)
source: Mapped[str] = mapped_column(String(32), default="ask")
source_turn: Mapped[str] = mapped_column(String(64), default="")
hits: Mapped[int] = mapped_column(Integer, default=0)
created_by: Mapped[str] = mapped_column(String(128), default="")
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
updated_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now, onupdate=now)
class MemPattern(Base):
"""操作习惯:某个人反复做的「问题 → 动作 / 流程卡 / 同类问题」。次数够了就建议固化。"""
__tablename__ = "onto_mem_pattern"
id: Mapped[str] = mapped_column(String(64), primary_key=True)
workspace: Mapped[str] = mapped_column(String(64), default="default", index=True)
owner: Mapped[str] = mapped_column(String(128), default="", index=True) # 谁的习惯(用户 id)
kind: Mapped[str] = mapped_column(String(16), default="question") # question / action / sop
ref: Mapped[str] = mapped_column(String(255), default="") # 动作名 / 流程卡 id / 案例 id
title: Mapped[str] = mapped_column(String(255), default="")
samples_json: Mapped[str] = mapped_column(Text, default="[]")
count: Mapped[int] = mapped_column(Integer, default=0)
status: Mapped[str] = mapped_column(String(16), default="watching") # watching / suggested / adopted / dismissed
adopted_ref: Mapped[str] = mapped_column(String(128), default="")
last_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
...@@ -69,6 +69,16 @@ async def archive(def_id: str, _: identity.Actor = Depends(require("build"))): ...@@ -69,6 +69,16 @@ async def archive(def_id: str, _: identity.Actor = Depends(require("build"))):
return service.archive(def_id) return service.archive(def_id)
@router.get("/defs/{def_id}/referenced-by")
async def referenced_by(def_id: str, _: identity.Actor = Depends(require("view"))):
return service.referenced_by(def_id)
@router.post("/defs/{def_id}/unarchive")
async def unarchive(def_id: str, _: identity.Actor = Depends(require("build"))):
return service.unarchive(def_id)
@router.post("/validate") @router.post("/validate")
async def validate(body: dict, _: identity.Actor = Depends(require("view"))): async def validate(body: dict, _: identity.Actor = Depends(require("view"))):
norm = sop_spec.normalize(body.get("spec") or body) norm = sop_spec.normalize(body.get("spec") or body)
...@@ -81,6 +91,13 @@ async def dry_run(def_id: str, body: RunIn, _: identity.Actor = Depends(require( ...@@ -81,6 +91,13 @@ async def dry_run(def_id: str, body: RunIn, _: identity.Actor = Depends(require(
return run return run
@router.post("/defs/{def_id}/steps/{step_id}/try")
async def try_step(def_id: str, step_id: str, body: dict | None = None,
_: identity.Actor = Depends(require("build"))):
"""单步试跑:只跑这一个步骤,上游变量可以手填模拟值。动作类只出预览。"""
return engine.try_step(def_id, step_id, (body or {}).get("env") or {})
@router.post("/defs/{def_id}/submit") @router.post("/defs/{def_id}/submit")
async def submit(def_id: str, body: dict | None = None, async def submit(def_id: str, body: dict | None = None,
_: identity.Actor = Depends(require("build"))): _: identity.Actor = Depends(require("build"))):
......
...@@ -12,6 +12,7 @@ ...@@ -12,6 +12,7 @@
from __future__ import annotations from __future__ import annotations
import contextvars import contextvars
import time
import logging import logging
import threading import threading
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
...@@ -137,7 +138,9 @@ def _foreach(run: dict, step: dict, sid: str, rows: list[dict], env: dict, mode: ...@@ -137,7 +138,9 @@ def _foreach(run: dict, step: dict, sid: str, rows: list[dict], env: dict, mode:
try: try:
ar = actions.propose(step["action"], params, object_key=str(okey or ""), ar = actions.propose(step["action"], params, object_key=str(okey or ""),
reason=f"SOP「{run['title']}」逐行处理「{step['title']}」第 {i} 行", reason=f"SOP「{run['title']}」逐行处理「{step['title']}」第 {i} 行",
initiator_kind="sop", source_ref=f"sop_step:{sid}:{i}") initiator_kind="sop", source_ref=f"sop_step:{sid}:{i}",
evidence=_step_evidence(run, step, env)
+ [{"kind": "data", "text": f"本行数据:{str(row)[:200]}", "ref": ""}])
finally: finally:
identity.reset(tok) identity.reset(tok)
results.append({"row": i, "ok": True, "action_run_id": ar["id"], results.append({"row": i, "ok": True, "action_run_id": ar["id"],
...@@ -177,9 +180,31 @@ def _load_param(p: dict, v: Any) -> Any: ...@@ -177,9 +180,31 @@ def _load_param(p: dict, v: Any) -> Any:
# ---------------- 启动 ---------------- # ---------------- 启动 ----------------
def _step_evidence(run: dict, step: dict, env: dict) -> list[dict]:
"""把上游步骤取到的数据整理成审批依据。
审批人要看到「凭什么建议我批这一单」。以前流程卡提议的动作既没有依据也没有优先级,
同一个动作外部 Agent 提的有、流程卡提的没有 —— 而流程卡才是日常主路径。
"""
ev: list[dict] = [{"kind": "sop", "text": f"由流程卡「{run['title']}」的步骤「{step['title']}」发起",
"ref": run["id"]}]
for name, val in (env or {}).items():
if not isinstance(val, dict):
continue
if val.get("columns") and isinstance(val.get("rows"), list):
ev.append({"kind": "data",
"text": f"{name}:{len(val['rows'])} 行({'、'.join(map(str, val['columns'][:6]))})",
"ref": val.get("sql") or ""})
elif val.get("summary"):
ev.append({"kind": "data", "text": f"{name}:{str(val['summary'])[:180]}", "ref": ""})
return ev[:8]
def start(def_id: str, params: dict | None = None, *, mode: str = "live", trigger: str = "manual", def start(def_id: str, params: dict | None = None, *, mode: str = "live", trigger: str = "manual",
version: int | None = None, parent_step_run: str = "", wait: bool = False) -> dict: version: int | None = None, parent_step_run: str = "", wait: bool = False) -> dict:
d = service.get(def_id) d = service.get(def_id)
if d["status"] == "archived":
raise HTTPException(409, f"流程卡「{d['title']}」已归档,先在流程卡列表里恢复才能运行")
if mode == "dry_run": if mode == "dry_run":
spec, ver, vid = d["spec"], 0, "" spec, ver, vid = d["spec"], 0, ""
if d["validation"]["errors"]: if d["validation"]["errors"]:
...@@ -430,7 +455,8 @@ def advance(run_id: str) -> dict: ...@@ -430,7 +455,8 @@ def advance(run_id: str) -> dict:
try: try:
ar = actions.propose(step["action"], params, object_key=str(okey or ""), ar = actions.propose(step["action"], params, object_key=str(okey or ""),
reason=f"SOP「{run['title']}」步骤「{step['title']}」", reason=f"SOP「{run['title']}」步骤「{step['title']}」",
initiator_kind="sop", source_ref=f"sop_step:{sid}") initiator_kind="sop", source_ref=f"sop_step:{sid}",
evidence=_step_evidence(run, step, env))
except HTTPException as e: except HTTPException as e:
identity.reset(tok) identity.reset(tok)
_update_step(sid, status="failed", error=str(e.detail)) _update_step(sid, status="failed", error=str(e.detail))
...@@ -617,3 +643,71 @@ def object_section(type_id: str, key: str) -> tuple[str, Any]: ...@@ -617,3 +643,71 @@ def object_section(type_id: str, key: str) -> tuple[str, Any]:
def validate_params_spec(spec: dict) -> dict: def validate_params_spec(spec: dict) -> dict:
return sop_spec.validate(spec) return sop_spec.validate(spec)
def try_step(def_id: str, step_id: str, env: dict | None = None) -> dict:
"""单步试跑:只执行这一个步骤,不建运行实例、不推进流程。
编辑流程卡时最常问的是「这一步到底取到了什么」,以前只能把整张卡试运行一遍,
而且结果弹在一个 Modal 里。现在检查器里点一下就能看这一步的结果,
上游变量还能手填模拟值。
会改数据的步骤(动作、逐行处理)一律只出预览,不会真的提交审批。
"""
d = service.get(def_id)
spec = d["spec"]
step = next((s for s in spec.get("steps") or [] if s["id"] == step_id), None)
if step is None:
raise HTTPException(404, f"步骤「{step_id}」不存在")
env = dict(env or {})
t = step["type"]
started = time.time()
def done(output: Any, note: str = "") -> dict:
return {"step_id": step_id, "type": t, "title": step["title"], "ok": True,
"output": output, "note": note, "var": step.get("output") or "",
"ms": int((time.time() - started) * 1000)}
try:
if t == "function":
res = registry.call_function(step["function"], _render(step.get("args") or {}, env))
return done(res, res.get("summary", "") if isinstance(res, dict) else "")
if t == "skill":
res = skills.run(step["skill"], _render(step.get("inputs") or {}, env),
require_published=False)
return done(res, res.get("summary", ""))
if t == "decision":
for i, br in enumerate(step.get("branches") or []):
if rules.evaluate(br["when"], env):
return done({"branch": i, "next": br["next"]},
f"走分支「{br.get('label') or br['when']}」")
return done({"branch": -1, "next": step.get("default")}, "走默认分支")
if t in ("action", "foreach"):
if t == "foreach":
rows = _rows_of(env.get(str(step.get("items") or "").lstrip("$")))
rows = rows[: int(step.get("limit") or 10)]
out = []
for i, row in enumerate(rows, 1):
env_i = {**env, "item": row, "index": i}
prep = actions.prepare(step["action"], _render(step.get("params") or {}, env_i),
str(_render(step.get("object_key") or "", env_i) or ""))
out.append({"row": i, "summary": prep["summary"],
"priority": (prep.get("approval_decision") or {}).get("priority", "")})
return done({"preview_rows": out}, f"预览 {len(out)} 行,正式运行时每行一张审批单")
prep = actions.prepare(step["action"], _render(step.get("params") or {}, env),
str(_render(step.get("object_key") or "", env) or ""))
return done({"preview": prep},
f"{prep['summary']}(试跑只预览,不会真的提交审批)")
if t == "human_task":
return done({"role": step.get("role"), "form": step.get("form") or []},
"人工任务:正式运行时会生成待办,这里只看它会长什么样")
if t == "subprocess":
return done({"sop": step.get("sop")}, "子流程:请到那张流程卡里单独试跑")
return done({}, "结束步骤,没有可执行的内容")
except HTTPException as e:
return {"step_id": step_id, "type": t, "title": step["title"], "ok": False,
"error": str(e.detail), "ms": int((time.time() - started) * 1000)}
except Exception as e: # noqa: BLE001
log.exception("单步试跑失败 sop=%s step=%s", def_id, step_id)
return {"step_id": step_id, "type": t, "title": step["title"], "ok": False,
"error": str(e)[:300], "ms": int((time.time() - started) * 1000)}
...@@ -18,7 +18,14 @@ from .models import SopDefinition, SopRun, SopVersion ...@@ -18,7 +18,14 @@ from .models import SopDefinition, SopRun, SopVersion
def _hash(spec: dict) -> str: def _hash(spec: dict) -> str:
return hashlib.sha1(jdump(spec).encode("utf-8")).hexdigest() """草稿指纹:只算「会影响执行」的部分。
画布位置(layout)纯展示,不进指纹 —— 否则在画布上挪一下节点就会让试运行作废、
把发布按钮锁住,人得重新保存、重新试运行、重新提交。积木那边早就是这个规矩
(test_画布数据与布局不算修改),流程卡这里之前是不一致的。
"""
return hashlib.sha1(jdump({k: v for k, v in spec.items() if k != "layout"})
.encode("utf-8")).hexdigest()
def _ws() -> str: def _ws() -> str:
...@@ -126,13 +133,47 @@ def update(def_id: str, *, title: str | None = None, description: str | None = N ...@@ -126,13 +133,47 @@ def update(def_id: str, *, title: str | None = None, description: str | None = N
return after return after
def referenced_by(def_id: str) -> list[dict]:
"""哪些流程卡把它当子流程调用。归档前要先告诉人,否则父流程会悄悄调用一张已归档的卡。"""
out = []
with session() as s:
rows = s.scalars(select(SopDefinition).where(
SopDefinition.workspace == _ws(), SopDefinition.id != def_id,
SopDefinition.status != "archived")).all()
for d in rows:
spec = jload(d.draft_spec_json, {}) or {}
for st in spec.get("steps") or []:
if st.get("type") == "subprocess" and st.get("sop") == def_id:
out.append({"id": d.id, "title": d.title, "step": st.get("title") or st.get("id")})
break
return out
def archive(def_id: str) -> dict: def archive(def_id: str) -> dict:
get(def_id) d0 = get(def_id)
refs = referenced_by(def_id)
if refs:
names = "、".join(f"「{r['title']}」" for r in refs[:5])
raise HTTPException(409, f"「{d0['title']}」还被 {len(refs)} 张流程卡当作子流程调用({names}),"
"先把这些引用改掉再归档")
with session() as s: with session() as s:
d = s.get(SopDefinition, def_id) d = s.get(SopDefinition, def_id)
d.status = "archived" d.status = "archived"
s.commit() s.commit()
audit.record("sop.archive", "sop", def_id, "归档 SOP") audit.record("sop.archive", "sop", def_id, f"归档 SOP「{d0['title']}」")
return get(def_id)
def unarchive(def_id: str) -> dict:
"""恢复归档的流程卡。已发布过的回到 published,没发布过的回到 draft。"""
d0 = get(def_id)
if d0["status"] != "archived":
raise HTTPException(409, "这张流程卡没有归档")
with session() as s:
d = s.get(SopDefinition, def_id)
d.status = "published" if d.current_version else "draft"
s.commit()
audit.record("sop.unarchive", "sop", def_id, f"恢复 SOP「{d0['title']}」")
return get(def_id) return get(def_id)
......
"""SOP 触发器:定时、指标条件;顺带驱动数据管道的定时同步。 """指标条件扫描。
- schedule:每天/每周/每月的某个时刻启动一次; 「什么时候跑」已经整体搬到 `app/watch/` —— 一张流程卡只能配一个触发器、没有管理界面、
- metric:到点后按指标取数(按对象维度拆分),对满足条件的每个对象各启动一次, 没有下次执行时间、失败只写日志、多进程还会重复触发,这些问题在那边一并解决了。
同一期同一对象只启动一次(trigger 字段记 `metric:<期>:<对象>` 去重)。 这里只留下 `metric_scan`,给流程卡编辑页的「试扫描」按钮用;调度线程已经删掉。
调度线程每分钟醒一次。以系统身份运行,审计里能看出是「系统 · 触发器」发起的。
""" """
from __future__ import annotations from __future__ import annotations
import datetime as dt
import logging import logging
import threading
import time
from fastapi import HTTPException from fastapi import HTTPException
from sqlalchemy import select from sqlalchemy import select
from ..core import identity from ..core.dbx import session
from ..core.dbx import now, session
from ..kernel import metrics, rules from ..kernel import metrics, rules
from . import engine, service from . import engine, service
from .models import SopDefinition, SopRun from .models import SopRun
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
_started = False
def _due(sched: dict, last: dt.datetime | None, at: dt.datetime) -> bool:
hh, mm = (int(x) for x in (sched.get("at") or "08:00").split(":")[:2])
slot = at.replace(hour=hh, minute=mm, second=0, microsecond=0)
every = sched.get("every") or "day"
if every == "week" and at.isoweekday() != int(sched.get("weekday") or 1):
return False
if every == "month" and at.day != int(sched.get("day") or 1):
return False
return at >= slot and (last is None or last < slot)
def _mark(def_id: str) -> None:
with session() as s:
d = s.get(SopDefinition, def_id)
d.last_triggered_at = now()
s.commit()
def metric_scan(def_id: str, *, dry: bool = False) -> dict: def metric_scan(def_id: str, *, dry: bool = False) -> dict:
...@@ -53,7 +28,7 @@ def metric_scan(def_id: str, *, dry: bool = False) -> dict: ...@@ -53,7 +28,7 @@ def metric_scan(def_id: str, *, dry: bool = False) -> dict:
raise HTTPException(422, "这个 SOP 不是指标触发的") raise HTTPException(422, "这个 SOP 不是指标触发的")
mt = trig["metric"] mt = trig["metric"]
dims = [mt["dimension"]] if mt.get("dimension") else [] dims = [mt["dimension"]] if mt.get("dimension") else []
res = metrics.query(mt["metric"], dimensions=dims, time=mt.get("time") or "current", res = metrics.query(mt["metric"], dimensions=dims, time=mt.get("time") or "",
question=f"[触发器] {d['title']}") question=f"[触发器] {d['title']}")
period = (res.get("period") or {}).get("period", "") period = (res.get("period") or {}).get("period", "")
hits, started = [], [] hits, started = [], []
...@@ -82,54 +57,3 @@ def metric_scan(def_id: str, *, dry: bool = False) -> dict: ...@@ -82,54 +57,3 @@ def metric_scan(def_id: str, *, dry: bool = False) -> dict:
except HTTPException as e: except HTTPException as e:
log.warning("触发器启动 SOP 失败 %s %s:%s", def_id, key, e.detail) log.warning("触发器启动 SOP 失败 %s %s:%s", def_id, key, e.detail)
return {"period": period, "hits": hits, "started": started, "rows": len(res["rows"])} return {"period": period, "hits": hits, "started": started, "rows": len(res["rows"])}
def tick(at: dt.datetime | None = None) -> list[str]:
at = at or dt.datetime.now()
fired = []
with session() as s:
defs = s.scalars(select(SopDefinition).where(SopDefinition.status == "published")).all()
items = [(d.id, d.workspace, d.last_triggered_at) for d in defs]
for def_id, ws, last in items:
tok = identity.set_current(identity.Actor(id="system", name="系统 · 触发器", kind="system",
roles=["admin"], workspace=ws))
try:
_, _, spec = service.version_spec(def_id)
trig = spec.get("trigger") or {}
if trig.get("kind") == "schedule" and _due(trig.get("schedule") or {}, last, at):
_mark(def_id)
engine.start(def_id, {}, trigger=f"schedule:{at:%Y-%m-%d %H:%M}")
fired.append(def_id)
elif trig.get("kind") == "metric" and _due({"every": "day", "at": trig["metric"].get("at")},
last, at):
_mark(def_id)
metric_scan(def_id)
fired.append(def_id)
except Exception: # noqa: BLE001
log.exception("触发器执行失败 sop=%s", def_id)
finally:
identity.reset(tok)
return fired
def start_scheduler() -> None:
global _started
if _started:
return
_started = True
def loop():
while True:
time.sleep(60)
try:
tick()
except Exception: # noqa: BLE001
log.exception("SOP 调度异常")
try:
from ..kernel import pipeline
pipeline.tick()
except Exception: # noqa: BLE001
log.exception("数据管道调度异常")
threading.Thread(target=loop, name="sop-scheduler", daemon=True).start()
"""监控与定时的接口。"""
from __future__ import annotations
from fastapi import APIRouter, Depends
from pydantic import BaseModel, Field
from ..core import identity
from ..core.identity import require
from . import cron, engine, service
router = APIRouter(prefix="/api/watch", tags=["watch"])
class WatchIn(BaseModel):
title: str = ""
description: str = ""
enabled: bool = True
owner_role: str = ""
schedule: dict = Field(default_factory=dict)
source: dict = Field(default_factory=dict)
condition: str = ""
strategies: list = Field(default_factory=list)
dedup: dict = Field(default_factory=dict)
@router.get("/meta")
async def meta(_: identity.Actor = Depends(require("view"))):
"""界面用的元信息:排程方式、看什么、能做什么,全部带中文说明。"""
return {
"schedule_kinds": [
{"key": "interval", "label": "按间隔", "desc": "每 N 分钟 / 小时看一次,适合盯库存这种变化快的"},
{"key": "daily", "label": "每天", "desc": "每天固定时刻"},
{"key": "weekly", "label": "每周", "desc": "每周某天固定时刻"},
{"key": "monthly", "label": "每月", "desc": "每月某日固定时刻(只到 28 号,避免 2 月漏跑)"},
{"key": "cron", "label": "cron 表达式", "desc": "分 时 日 月 周,例如 */30 9-18 * * 1-5"},
],
"source_kinds": [
{"key": "metric", "label": "盯指标", "desc": "本体里的指标按维度拆开逐个判,如「库存缺口」按仓库×商品"},
{"key": "object", "label": "盯对象", "desc": "某类对象的实例按属性逐个判,如「状态是延期的供应商」"},
{"key": "sop", "label": "只按点跑流程卡", "desc": "不看数据,到点就启动一张流程卡"},
],
"strategy_kinds": [
{"key": "propose_action", "label": "提交审批", "desc": "每个命中生成一张审批单,优先级按本体里的审批决策表算"},
{"key": "run_sop", "label": "启动流程卡", "desc": "命中行作为参数传给流程卡"},
{"key": "notify", "label": "生成待办", "desc": "给某个业务角色提一条待办"},
],
"max_hits": service.MAX_HITS,
}
@router.get("")
async def list_watches(q: str = "", _: identity.Actor = Depends(require("view"))):
return service.list_watches(q)
@router.post("")
async def create(body: WatchIn, _: identity.Actor = Depends(require("build"))):
return service.create(body.model_dump())
@router.get("/runs")
async def runs(watch_id: str = "", limit: int = 50,
_: identity.Actor = Depends(require("view"))):
return service.list_runs(watch_id, limit)
@router.post("/preview-schedule")
async def preview_schedule(body: dict, _: identity.Actor = Depends(require("view"))):
"""编辑排程时实时告诉人「下几次分别是什么时候」—— 比让人脑补 cron 靠谱得多。"""
import datetime as dt
try:
sched = cron.normalize(body.get("schedule"))
except cron.CronError as e:
return {"ok": False, "error": str(e), "text": "", "next": []}
at = dt.datetime.now()
out = []
for _i in range(5):
at = cron.next_fire(sched, at)
out.append(at.strftime("%Y-%m-%d %H:%M"))
return {"ok": True, "text": cron.describe(sched), "next": out}
@router.get("/{wid}")
async def get(wid: str, _: identity.Actor = Depends(require("view"))):
return service.get(wid)
@router.put("/{wid}")
async def update(wid: str, body: WatchIn, _: identity.Actor = Depends(require("build"))):
return service.update(wid, body.model_dump())
@router.delete("/{wid}")
async def delete(wid: str, _: identity.Actor = Depends(require("build"))):
service.delete(wid)
return {"ok": True}
@router.post("/{wid}/enabled")
async def set_enabled(wid: str, body: dict, _: identity.Actor = Depends(require("build"))):
return service.set_enabled(wid, bool(body.get("enabled", True)))
@router.post("/{wid}/scan")
async def scan(wid: str, body: dict | None = None,
_: identity.Actor = Depends(require("operate"))):
"""试扫描(dry=True,只看会命中谁)或手动跑一次(dry=False,真的触发策略)。"""
b = body or {}
dry = bool(b.get("dry", True))
return engine.scan(wid, dry=dry, trigger="manual", force=bool(b.get("force")))
"""排程:间隔 / 每天 / 每周 / 每月 / cron 五段式,统一算「下一次什么时候跑」。
自己写解析器而不是引 croniter:只需要标准的五段语法(`*`、`*/n`、`a-b`、`a,b`),
七十行能覆盖,少一个依赖就少一处装不上的风险。
所有时间按监控器自己的时区算,返回的是本地朴素时间(和库里存的一致)。
"""
from __future__ import annotations
import datetime as dt
KINDS = ("interval", "daily", "weekly", "monthly", "cron")
_FIELDS = (("minute", 0, 59), ("hour", 0, 23), ("day", 1, 31), ("month", 1, 12), ("weekday", 0, 6))
class CronError(ValueError):
pass
def _parse_field(expr: str, lo: int, hi: int, what: str) -> set[int]:
out: set[int] = set()
for part in str(expr).split(","):
part = part.strip()
if not part:
raise CronError(f"{what} 里有空段")
step = 1
if "/" in part:
part, _, st = part.partition("/")
if not st.isdigit() or int(st) < 1:
raise CronError(f"{what} 的步长「{st}」不是正整数")
step = int(st)
part = part or "*"
if part == "*":
a, b = lo, hi
elif "-" in part.lstrip("-"):
a_s, _, b_s = part.partition("-")
if not (a_s.isdigit() and b_s.isdigit()):
raise CronError(f"{what} 的区间「{part}」要写成 数字-数字")
a, b = int(a_s), int(b_s)
elif part.isdigit():
a = b = int(part)
else:
raise CronError(f"{what} 看不懂:「{part}」")
if a < lo or b > hi or a > b:
raise CronError(f"{what} 超出范围({lo}~{hi}):「{part}」")
out.update(range(a, b + 1, step))
if not out:
raise CronError(f"{what} 没有匹配到任何值")
return out
def parse_cron(expr: str) -> dict[str, set[int]]:
parts = str(expr or "").split()
if len(parts) != 5:
raise CronError("cron 要写成 5 段:分 时 日 月 周(例如 `*/30 * * * *` 每 30 分钟)")
return {name: _parse_field(p, lo, hi, name)
for p, (name, lo, hi) in zip(parts, _FIELDS)}
def describe(sched: dict) -> str:
"""给界面用的中文说明,省得人去脑补 cron。"""
kind = sched.get("kind") or "daily"
at = sched.get("at") or "08:00"
if kind == "interval":
n = int(sched.get("every_minutes") or 60)
return f"每 {n} 分钟" if n < 60 or n % 60 else f"每 {n // 60} 小时"
if kind == "daily":
return f"每天 {at}"
if kind == "weekly":
wd = "一二三四五六日"[(int(sched.get("weekday") or 1) - 1) % 7]
return f"每周{wd} {at}"
if kind == "monthly":
return f"每月 {int(sched.get('day') or 1)} 日 {at}"
if kind == "cron":
return f"cron:{sched.get('cron') or ''}"
return kind
def normalize(sched: dict | None) -> dict:
s = dict(sched or {})
kind = str(s.get("kind") or "daily")
if kind not in KINDS:
raise CronError(f"排程方式只能是 {'/'.join(KINDS)}")
out: dict = {"kind": kind, "tz": str(s.get("tz") or "Asia/Shanghai"),
"misfire": "run_once" if str(s.get("misfire") or "skip") == "run_once" else "skip"}
if kind == "interval":
n = int(s.get("every_minutes") or 60)
if not 1 <= n <= 60 * 24 * 7:
raise CronError("间隔要在 1 分钟到 7 天之间")
out["every_minutes"] = n
return out
if kind == "cron":
parse_cron(s.get("cron") or "") # 先验一遍,错的不许存
out["cron"] = str(s["cron"]).strip()
return out
hh, mm = _hhmm(s.get("at") or "08:00")
out["at"] = f"{hh:02d}:{mm:02d}"
if kind == "weekly":
out["weekday"] = min(7, max(1, int(s.get("weekday") or 1)))
if kind == "monthly":
out["day"] = min(28, max(1, int(s.get("day") or 1))) # 只到 28,避免 2 月漏跑
return out
def _hhmm(at: str) -> tuple[int, int]:
try:
hh, _, mm = str(at).partition(":")
h, m = int(hh), int(mm or 0)
except ValueError as e:
raise CronError(f"时间要写成 HH:MM,收到「{at}」") from e
if not (0 <= h <= 23 and 0 <= m <= 59):
raise CronError(f"时间超出范围:「{at}」")
return h, m
def next_fire(sched: dict, after: dt.datetime) -> dt.datetime:
"""算 after 之后的下一次触发时刻(不含 after 本身)。"""
s = normalize(sched)
base = after.replace(second=0, microsecond=0)
if s["kind"] == "interval":
return base + dt.timedelta(minutes=s["every_minutes"])
if s["kind"] == "cron":
f = parse_cron(s["cron"])
t = base + dt.timedelta(minutes=1)
for _ in range(367 * 24 * 60): # 最多往前找一年,找不到说明表达式永不命中
if (t.minute in f["minute"] and t.hour in f["hour"] and t.month in f["month"]
and t.day in f["day"] and (t.weekday() + 1) % 7 in f["weekday"]):
return t
t += dt.timedelta(minutes=1)
raise CronError("这个 cron 表达式一年之内都不会触发")
h, m = _hhmm(s["at"])
t = base.replace(hour=h, minute=m)
if t <= base:
t += dt.timedelta(days=1)
if s["kind"] == "daily":
return t
if s["kind"] == "weekly":
while t.isoweekday() != s["weekday"]:
t += dt.timedelta(days=1)
return t
while t.day != s["day"]:
t += dt.timedelta(days=1)
return t
"""监控与定时的表:监控器定义、每次扫描的记录、每个命中键的抑制状态。"""
from __future__ import annotations
import datetime as dt
from sqlalchemy import DateTime, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column
from ..core.db import _LONGTEXT, Base
from ..core.dbx import now
class Watch(Base):
"""一个监控器 = 什么时候看(schedule)+ 看什么(source)+ 命中了做什么(strategies)。"""
__tablename__ = "onto_watch"
id: Mapped[str] = mapped_column(String(64), primary_key=True)
workspace: Mapped[str] = mapped_column(String(64), default="default", index=True)
title: Mapped[str] = mapped_column(String(255), default="")
description: Mapped[str] = mapped_column(Text, default="")
enabled: Mapped[int] = mapped_column(Integer, default=1, index=True)
schedule_json: Mapped[str] = mapped_column(Text, default="{}")
source_json: Mapped[str] = mapped_column(Text, default="{}")
condition: Mapped[str] = mapped_column(Text, default="")
strategies_json: Mapped[str] = mapped_column(_LONGTEXT, default="[]")
dedup_json: Mapped[str] = mapped_column(Text, default="{}")
owner_role: Mapped[str] = mapped_column(String(128), default="")
# 调度水位:next_fire_at 提前算好落库,界面才能显示「下次执行时间」,
# 调度线程也只需要一条 WHERE 就能挑出到点的,不用每轮把所有监控器解析一遍。
next_fire_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True, index=True)
last_fired_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True)
last_status: Mapped[str] = mapped_column(String(16), default="") # ok / error / ""
last_error: Mapped[str] = mapped_column(Text, default="")
fail_count: Mapped[int] = mapped_column(Integer, default=0)
created_by: Mapped[str] = mapped_column(String(128), default="")
created_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
updated_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now, onupdate=now)
class WatchRun(Base):
"""一次扫描。扫了几行、命中几行、触发出去什么,都留痕。"""
__tablename__ = "onto_watch_run"
id: Mapped[str] = mapped_column(String(64), primary_key=True)
workspace: Mapped[str] = mapped_column(String(64), default="default", index=True)
watch_id: Mapped[str] = mapped_column(String(64), index=True)
trigger: Mapped[str] = mapped_column(String(64), default="schedule") # schedule / manual / dry
status: Mapped[str] = mapped_column(String(16), default="running") # running / done / failed
scanned: Mapped[int] = mapped_column(Integer, default=0)
hit_count: Mapped[int] = mapped_column(Integer, default=0)
fired_count: Mapped[int] = mapped_column(Integer, default=0)
suppressed: Mapped[int] = mapped_column(Integer, default=0)
hits_json: Mapped[str] = mapped_column(_LONGTEXT, default="[]")
fired_json: Mapped[str] = mapped_column(_LONGTEXT, default="[]")
error: Mapped[str] = mapped_column(Text, default="")
started_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
finished_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True)
class WatchState(Base):
"""每个命中键的抑制状态:冷却期内不重复触发;恢复(不再命中)后重新计数。"""
__tablename__ = "onto_watch_state"
id: Mapped[str] = mapped_column(String(128), primary_key=True) # <watch_id>:<key>
workspace: Mapped[str] = mapped_column(String(64), default="default", index=True)
watch_id: Mapped[str] = mapped_column(String(64), index=True)
hit_key: Mapped[str] = mapped_column(String(255), default="")
firing: Mapped[int] = mapped_column(Integer, default=0)
last_fired_at: Mapped[dt.datetime | None] = mapped_column(DateTime, nullable=True)
last_seen_at: Mapped[dt.datetime] = mapped_column(DateTime, default=now)
fire_count: Mapped[int] = mapped_column(Integer, default=0)
"""调度线程:把到点的监控器挑出来跑,顺带驱动数据管道的定时同步。
和旧的 SOP 触发器线程比,三处不同:
- 20 秒醒一次(旧的是 60 秒),才撑得住「每分钟」这种间隔;
- 到点判断靠库里的 next_fire_at,挑中的同时就把水位推到下一档,多进程不会重复触发;
- 执行成功才记 last_fired_at;连挂三次自动停用并标红,不再默默空转。
"""
from __future__ import annotations
import logging
import threading
import time
log = logging.getLogger(__name__)
_started = False
TICK_SECONDS = 20
def start() -> None:
global _started
if _started:
return
_started = True
def loop():
while True:
time.sleep(TICK_SECONDS)
try:
from . import engine
engine.tick()
except Exception: # noqa: BLE001
log.exception("监控调度异常")
try:
from ..kernel import pipeline
pipeline.tick()
except Exception: # noqa: BLE001
log.exception("数据管道调度异常")
threading.Thread(target=loop, name="watch-scheduler", daemon=True).start()
...@@ -177,3 +177,77 @@ cd web && npm run build:8103 # 构建前端 ...@@ -177,3 +177,77 @@ cd web && npm run build:8103 # 构建前端
原「三、没改、只提建议的」里有两条这次一并处理了: 原「三、没改、只提建议的」里有两条这次一并处理了:
- 第 4 条「流程卡不能按行循环」:已经新增「逐行处理」步骤。 - 第 4 条「流程卡不能按行循环」:已经新增「逐行处理」步骤。
- 第 1 条「提问太慢」:部分缓解。子 Agent 并行、问数最多下钻一次、快路径省掉一轮规划。但单次问数本身仍需 20~30 秒,一次完整提问约 60~100 秒。 - 第 1 条「提问太慢」:部分缓解。子 Agent 并行、问数最多下钻一次、快路径省掉一轮规划。但单次问数本身仍需 20~30 秒,一次完整提问约 60~100 秒。
---
## 七、v7 走查(2026-09-23)
这一轮针对「MCP 被砍掉」「归档后数据找不到」「流程卡编辑不流畅」「缺定时任务」「建模页面体验差」五个反馈。在 8107(工作区 `xianda_inv`)上用真实数据实跑,全程记录如下。
### 7.1 先说结论:以前跑不通的那一段,现在通了
建一个监控器:**每天 8:00 看所有「仓库×商品」,可用库存低于安全库存就开一张补货审批单**。
```
试扫描 → 扫了 60 行库存,命中 7 行(606ms)
W01 P005 安全150 / 在库40 / 在途0 → 缺口 110
W01 P006 安全120 / 在库60 / 在途0 → 缺口 60
W01 P010 安全80 / 在库30 / 在途0 → 缺口 50
W02 P005 安全160 / 在库35 / 在途100 → 缺口 25
W02 P013 安全220 / 在库90 / 在途0 → 缺口 130
W03 P001 安全100 / 在库50 / 在途0 → 缺口 50
W03 P007 安全90 / 在库20 / 在途0 → 缺口 70
真跑 → 命中 7,触发 7 张审批单,抑制 0
```
生成的 7 张审批单,优先级**逐条对照业务手册 §六 验证过**:
| 商品 | 供应商 | 状态 | 金额 | 手册应给 | 系统给 |
|---|---|---|---|---|---|
| P005 ×2 | S003 华南纸品 | 延期 | 4950 / 1125 | P0 | **P0** ✓ |
| P006 | S003 华南纸品 | 延期 | 3120 | P0 | **P0** ✓ |
| P007 | S003 华南纸品 | 延期 | 2520 | P0 | **P0** ✓ |
| P010 | S004 | 正常 | 3400 | P3 | **P3** ✓ |
| P013 | S005 | 正常 | 3744 | P3 | **P3** ✓ |
| P001 | S001 | 正常 | 1995 | P3 | **P3** ✓ |
**这在 v6 是做不到的**:优先级来自动作的静态 `risk_level`,所有单子一个优先级;手册里那张审批规则表在运行时完全没被读过。本体里「补货审批决策」这张决策表一直都在,只是没人调它。
审批单上的依据也留下了判断过程:
```
监控「每日缺货巡检」条件 safety_stock - on_hand - in_transit > 0 命中:{stock_id: 5, ...}
按决策表「补货审批决策」:amount_ge_5wan=False,involves_delayed_supplier=True
```
批准一张 P0(W01 的清风抽纸,补 110 件):
```
批准前:库存 5 在库 40 / 在途 0 / 安全 150;采购单共 26 张
批准 → done
批准后:库存 5 在库 40 / 在途 110;采购单共 27 张
新采购单 PO20260923112625 P005 / W01 / S003 / 110 件 / 4950 元 / 已下单
缺口:110 → 0
再试扫描:命中 6 条,库存 5 已不在命中列表里 ✓
```
**在途数量回写**也补上了(第三节第 3 条遗留问题)。以前建了采购单不改 `in_transit`,缺口不变,定时监控会每天重复开同一张单。
立刻再跑一次:命中 7、触发 0、**抑制 7** —— 冷却期内不重复开单。旧触发器按「统计期」去重,默认自然月,意味着一个缺货商品一个月只提醒一次。
### 7.2 归档:数据从来没丢,是找不到
直接查 `?status=archived`,三张归档的流程卡完整躺在库里。问题在于前端筛选只有 全部 / 已发布 / 草稿,而后端**根本没有恢复接口**。
现在:流程卡列表多了「已归档」筛选 → 三张卡都在,带「已归档」标记 → 点进去有「恢复」按钮 → 一键回到草稿。浏览器里实测走通。
还顺手堵了几个洞:归档前检查子流程引用(被引用直接拒绝并说明是哪几张卡)、已归档的卡不能再被 `/run` 或 MCP 启动、校验器对已归档子流程报错。积木废弃是同一个毛病,一并修了。
### 7.3 还没解决 / 新发现
1. **「审批人」角色批不了变更提案**。`approver` 的权限是 `view/ask/operate/approve`,而变更提案要 `review` —— 只有 builder / admin 有。走查时用 approver 批 release 直接 403。菜单却把「审批与待办」显示给 approver。角色权限设计需要重新对一遍。
2. **补货数量直接取缺口**,没按手册「向上取整到补货批量」。批量(`reorder_qty`)在商品对象上,而监控盯的是库存行,渲染参数时取不到。要么监控改盯商品,要么给动作加一步计算。
3. **指标维度名是原始列名**(`warehouse_id` / `product_id`,不是「仓库」「商品」)。按中文维度名查会 422 并提示可用维度。这是建模阶段没给维度起中文名,属于建模质量问题,不是引擎问题。
4. **`库存` 对象的建模元数据不全**:7 个属性没有一个标了时间或维度,`label_column` 为空,evidence 0 条。所以实例显示成「W01 · P005」而不是「上海中心仓 · 清风抽纸」。建议在对象编辑器顶部加「完备度检查条」逐条提示。
5. **`rel.*` 一跳关联是按需解析**,每次提议动作多打几次业务库。对象多时要加缓存。
...@@ -37,6 +37,7 @@ def env(tmp_path, monkeypatch): ...@@ -37,6 +37,7 @@ def env(tmp_path, monkeypatch):
from app.sop import models as _m6 # noqa: F401 from app.sop import models as _m6 # noqa: F401
from app.text2sql import models as _m7 # noqa: F401 from app.text2sql import models as _m7 # noqa: F401
from app.memory import models as _m8 # noqa: F401 from app.memory import models as _m8 # noqa: F401
from app.watch import models as _m9 # noqa: F401
meta = create_engine(f"sqlite:///{tmp_path / 'meta.db'}", future=True) meta = create_engine(f"sqlite:///{tmp_path / 'meta.db'}", future=True)
core_db.Base.metadata.create_all(meta) core_db.Base.metadata.create_all(meta)
with Session(meta) as s: with Session(meta) as s:
......
"""流程卡 v6:画布位置随草稿保存、逐行处理(foreach)、子流程不能调自己。"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from test_platform import build_basics, env, make_action # noqa: E402,F401
def foreach_spec() -> dict:
return {
"steps": [
{"id": "q", "type": "function", "title": "各网点成交金额", "function": "metric.query",
"args": {"metric": "成交金额", "dimensions": ["网点"]}, "output": "amt", "next": "each"},
{"id": "each", "type": "foreach", "title": "逐个网点标记跟进", "items": "$amt",
"action": "mark_follow", "params": {"reason": "成交 $item.value"}, "object_key": "$item.网点",
"limit": 2, "output": "marked", "next": "end"},
{"id": "end", "type": "end", "title": "完成", "outcome": "已逐个提交"}],
"layout": {"q": {"x": 10, "y": 20}, "each": {"x": 10, "y": 140}, "ghost": {"x": 0, "y": 0}}}
def test_画布位置随草稿保存_不存在的步骤丢掉(env):
from app.sop import service
d = service.create("巡检", spec=foreach_spec())
got = service.get(d["id"])["spec"]["layout"]
assert got == {"q": {"x": 10.0, "y": 20.0}, "each": {"x": 10.0, "y": 140.0}}
def test_逐行处理_试运行预览_正式运行每行一张审批单(env):
from app.capability import actions
from app.governance import review
from app.sop import engine, service
b = build_basics(env["ds_id"])
make_action(b["ot"]["id"])
d = service.create("逐行标记", spec=foreach_spec())
assert service.get(d["id"])["validation"]["errors"] == []
run = engine.start(d["id"], {}, mode="dry_run", wait=True)
step = next(s for s in run["steps"] if s["step_id"] == "each")
assert run["status"] == "done" and step["output"]["total"] == 2 # limit 生效
assert step["output"]["ok"] == 2 and actions.list_runs() == [] # 试运行只预览
review.decide(service.submit_publish(d["id"])["id"], True)
live = engine.start(d["id"], {}, mode="live", wait=True)
assert live["status"] == "done" # 不等审批,流程继续
runs = actions.list_runs()
assert len(runs) == 2 and all(r["status"] == "pending_approval" for r in runs)
def test_逐行处理与子流程的校验(env):
from app.sop import service, spec
bad = spec.normalize({"steps": [
{"id": "each", "type": "foreach", "title": "逐行", "action": "", "next": "end"},
{"id": "end", "type": "end"}]})
errs = " ".join(spec.validate(bad)["errors"])
assert "没有选择动作" in errs and "按哪份数据" in errs
d = service.create("自己调自己", spec={"steps": [{"id": "s", "type": "subprocess", "title": "子", "next": "e"},
{"id": "e", "type": "end"}]})
service.update(d["id"], spec={"steps": [{"id": "s", "type": "subprocess", "title": "子", "sop": d["id"], "next": "e"},
{"id": "e", "type": "end"}]})
assert any("调用了流程卡自己" in e for e in service.get(d["id"])["validation"]["errors"])
"""监控与定时:排程解析、下次执行时间、抑制去重、三种数据源、策略触发、失败自停。"""
from __future__ import annotations
import datetime as dt
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).parent))
from test_platform import build_basics, env, make_action # noqa: E402,F401
# ---------------------------------------------------------------- 排程
def test_cron_五段解析_与下次执行时间():
from app.watch import cron
n = dt.datetime(2026, 9, 23, 10, 30)
assert cron.next_fire({"kind": "interval", "every_minutes": 30}, n) == dt.datetime(2026, 9, 23, 11, 0)
assert cron.next_fire({"kind": "daily", "at": "08:00"}, n) == dt.datetime(2026, 9, 24, 8, 0)
assert cron.next_fire({"kind": "daily", "at": "23:00"}, n) == dt.datetime(2026, 9, 23, 23, 0)
# 2026-09-23 是周三,下一个周一是 28 号
assert cron.next_fire({"kind": "weekly", "at": "09:00", "weekday": 1}, n) == dt.datetime(2026, 9, 28, 9, 0)
assert cron.next_fire({"kind": "monthly", "at": "07:30", "day": 1}, n) == dt.datetime(2026, 10, 1, 7, 30)
# 工作日 9~18 点每 15 分钟
assert cron.next_fire({"kind": "cron", "cron": "*/15 9-18 * * 1-5"}, n) == dt.datetime(2026, 9, 23, 10, 45)
def test_cron_写错了要当场报错_而不是悄悄不跑():
from app.watch import cron
for bad in ["", "* * *", "*/0 * * * *", "99 * * * *", "abc * * * *"]:
with pytest.raises(cron.CronError):
cron.normalize({"kind": "cron", "cron": bad})
with pytest.raises(cron.CronError):
cron.normalize({"kind": "daily", "at": "25:00"})
def test_每月只到28号_二月不会漏跑():
from app.watch import cron
assert cron.normalize({"kind": "monthly", "day": 31})["day"] == 28
# ---------------------------------------------------------------- 盯指标
def _metric_watch(**kw) -> dict:
body = {"title": "缺口监控",
"schedule": {"kind": "daily", "at": "08:00"},
"source": {"kind": "metric", "metric": "成交金额", "dimensions": ["网点"]},
"condition": "value > 0",
"strategies": [{"kind": "notify", "role": "operator", "title": "去看一下"}],
"dedup": {"key": "$key", "cooldown_hours": 24}}
body.update(kw)
return body
def test_盯指标_试扫描只看命中不触发(env):
from app.watch import engine as wengine, service
build_basics(env["ds_id"])
w = service.create(_metric_watch())
assert w["next_fire_at"] # 建好就有下次执行时间,界面能显示
r = wengine.scan(w["id"], dry=True)
assert r["hit_count"] >= 1
assert r["fired"] == [] and r["run_id"] == ""
assert service.list_runs(w["id"]) == [] # 试扫描不留运行记录
def test_盯指标_正式跑一次_生成待办并写运行记录(env):
from app.capability import tasks
from app.watch import engine as wengine, service
build_basics(env["ds_id"])
w = service.create(_metric_watch())
r = wengine.scan(w["id"], dry=False)
assert r["hit_count"] >= 1
assert all(f["ok"] for f in r["fired"])
assert len(tasks.list_tasks()) >= r["hit_count"]
runs = service.list_runs(w["id"])
assert len(runs) == 1 and runs[0]["status"] == "done"
assert runs[0]["hit_count"] == r["hit_count"]
assert service.get(w["id"])["last_status"] == "ok"
def test_抑制_冷却期内不重复触发_恢复后重新计数(env):
from app.watch import engine as wengine, service
build_basics(env["ds_id"])
w = service.create(_metric_watch())
first = wengine.scan(w["id"], dry=False)
assert first["suppressed"] == 0
second = wengine.scan(w["id"], dry=False)
assert second["suppressed"] == second["hit_count"] and second["fired"] == []
# 条件改成永不命中:这一轮把所有键标成已恢复
service.update(w["id"], {**_metric_watch(), "condition": "value < 0"})
wengine.scan(w["id"], dry=False)
# 再改回去,冷却已经因为「恢复过」而重置
service.update(w["id"], _metric_watch())
third = wengine.scan(w["id"], dry=False)
assert third["suppressed"] == 0 and third["fired"]
def test_冷却设为0就每次都触发(env):
from app.watch import engine as wengine, service
build_basics(env["ds_id"])
w = service.create(_metric_watch(dedup={"key": "$key", "cooldown_hours": 0}))
wengine.scan(w["id"], dry=False)
again = wengine.scan(w["id"], dry=False)
assert again["suppressed"] == 0 and again["fired"]
# ---------------------------------------------------------------- 盯对象
def test_盯对象_按属性条件逐个实例判(env):
from app.watch import engine as wengine, service
b = build_basics(env["ds_id"])
w = service.create({"title": "盯网点", "schedule": {"kind": "daily", "at": "08:00"},
"source": {"kind": "object", "object_type": b["ot"]["id"]},
"condition": "等级 == 'A'",
"strategies": [{"kind": "notify", "role": "operator", "title": "A 级网点"}]})
r = wengine.scan(w["id"], dry=True)
assert r["scanned"] >= r["hit_count"]
assert all(h.get("等级") == "A" for h in r["hits"])
# ---------------------------------------------------------------- 策略:提交审批
def test_命中后提交审批_审批单带监控作为依据(env):
from app.capability import actions
from app.watch import engine as wengine, service
b = build_basics(env["ds_id"])
make_action(b["ot"]["id"])
w = service.create({"title": "自动提审批", "schedule": {"kind": "daily", "at": "08:00"},
"source": {"kind": "object", "object_type": b["ot"]["id"]},
"condition": "等级 == 'A'",
"dedup": {"key": "$key", "cooldown_hours": 24},
"strategies": [{"kind": "propose_action", "action": "mark_follow",
"params": {"reason": "监控命中"}, "object_key": "$key"}]})
r = wengine.scan(w["id"], dry=False)
assert r["fired"] and all(f["ok"] for f in r["fired"])
ar = actions.get(r["fired"][0]["ref"])
assert ar["status"] == "pending_approval"
assert ar["initiator_kind"] == "watch"
assert any("监控" in str(e.get("text", "")) for e in ar["evidence"])
# ---------------------------------------------------------------- 调度
def test_到点才跑_挑中就把水位推走_多进程不会重复触发(env):
from app.watch import engine as wengine, service
from app.watch.models import Watch
from app.core.dbx import session
build_basics(env["ds_id"])
w = service.create(_metric_watch(schedule={"kind": "interval", "every_minutes": 30}))
with session() as s:
s.get(Watch, w["id"]).next_fire_at = dt.datetime.now() - dt.timedelta(minutes=1)
s.commit()
at = dt.datetime.now()
assert [x[0] for x in wengine.due(at)] == [w["id"]]
assert wengine.due(at) == [] # 水位已经推走,第二个进程挑不到
assert service.get(w["id"])["next_fire_at"]
def test_停用的监控不参与调度(env):
from app.watch import engine as wengine, service
build_basics(env["ds_id"])
w = service.create(_metric_watch())
service.set_enabled(w["id"], False)
assert service.get(w["id"])["next_fire_at"] is None
assert wengine.due(dt.datetime.now() + dt.timedelta(days=2)) == []
def test_连续失败三次自动停用并标红(env):
from app.watch import engine as wengine, service
build_basics(env["ds_id"])
w = service.create(_metric_watch(source={"kind": "metric", "metric": "不存在的指标"}))
for _ in range(3):
with pytest.raises(Exception):
wengine.scan(w["id"], dry=False)
got = service.get(w["id"])
assert got["last_status"] == "error" and got["fail_count"] >= 3
assert got["enabled"] is False
# ---------------------------------------------------------------- 接口与校验
def test_校验_条件写错_策略缺失都要当场拒绝(env):
from fastapi import HTTPException
from app.watch import service
build_basics(env["ds_id"])
with pytest.raises(HTTPException):
service.create(_metric_watch(condition="value >"))
with pytest.raises(HTTPException):
service.create(_metric_watch(strategies=[]))
with pytest.raises(HTTPException):
service.create(_metric_watch(source={"kind": "metric", "metric": ""}))
def test_接口_列表_排程预览_试扫描(env):
from app.watch import service
build_basics(env["ds_id"])
w = service.create(_metric_watch())
from fastapi.testclient import TestClient
from app.main import app
c = TestClient(app)
assert c.get("/api/watch").status_code == 200
assert any(x["id"] == w["id"] for x in c.get("/api/watch").json())
r = c.post("/api/watch/preview-schedule",
json={"schedule": {"kind": "cron", "cron": "*/30 * * * *"}}).json()
assert r["ok"] and len(r["next"]) == 5
bad = c.post("/api/watch/preview-schedule",
json={"schedule": {"kind": "cron", "cron": "bad"}}).json()
assert bad["ok"] is False and bad["error"]
scan = c.post(f"/api/watch/{w['id']}/scan", json={"dry": True})
assert scan.status_code == 200 and scan.json()["hit_count"] >= 1
meta = c.get("/api/watch/meta").json()
assert {k["key"] for k in meta["source_kinds"]} == {"metric", "object", "sop"}
This diff could not be displayed because it is too large.
...@@ -9,7 +9,8 @@ ...@@ -9,7 +9,8 @@
"build:8103": "tsc -b && vite build --outDir dist_8103 --emptyOutDir", "build:8103": "tsc -b && vite build --outDir dist_8103 --emptyOutDir",
"typecheck": "tsc -b", "typecheck": "tsc -b",
"preview": "vite preview", "preview": "vite preview",
"test": "vitest run" "test": "vitest run",
"build:8107": "tsc -b && vite build --outDir dist_8107 --emptyOutDir"
}, },
"dependencies": { "dependencies": {
"@codemirror/lang-sql": "^6.10.0", "@codemirror/lang-sql": "^6.10.0",
......
import { describe, expect, it } from "vitest";
import { applyEvent, buildGraph, emptyTrace, foldEvents, traceSummary } from "@/features/ask/trace";
import { normalizeTurn } from "@/lib/onto";
const EVENTS = [
{ type: "link", concepts: [{ id: "c1", name: "成交金额", kind: "function", type_key: "aggregate", matched: ["销售额"] }], instances: [], time: null, ts: 1 },
{ type: "agent_start", span: "lead", agent: "lead", label: "主 Agent", ts: 2 },
{ type: "thought", span: "lead", agent: "lead", text: "先取数,", ts: 3 },
{ type: "thought", span: "lead", agent: "lead", text: "再看原因。", ts: 4 },
{ type: "agent_start", span: "agent1", parent: "lead", agent: "knowledge", label: "知识 Agent", task: "查口径", ts: 5 },
{ type: "tool_start", span: "k1", parent: "agent1", agent: "knowledge", tool: "search_knowledge", label: "知识图谱多跳检索", args: {}, ts: 6 },
{ type: "tool_event", span: "k1", event: { type: "link", links: [{ term: "成交", matches: [{ id: "e1", label: "成交金额", type: "指标" }] }] }, ts: 7 },
{ type: "tool_event", span: "k1", event: { type: "hop", round: 1, paths: [{ id: "p1", source: "e1", target: "e2", relation: "依据", occurrence: 2 }] }, ts: 8 },
{ type: "tool_done", span: "k1", ok: true, summary: "命中 3 段", result: { chunks: [] }, ts: 9 },
{ type: "agent_done", span: "agent1", ok: true, summary: "口径是含税", confidence: 0.8, ts: 10 },
{ type: "memory", cases: [{ id: "mc1", question: "x", score: 0.95, status: "verified" }], facts: [], fast: "mc1", ts: 11 },
];
describe("提问推理轨迹", () => {
it("实时事件与回放用同一个 reducer,思考逐段拼接", () => {
const s = foldEvents(EVENTS);
expect(s.order).toEqual(["lead", "agent1"]);
expect(s.agents.lead.thought).toBe("先取数,再看原因。");
expect(s.agents.agent1.tools).toEqual(["k1"]);
expect(s.tools.k1.status).toBe("done");
expect(s.tools.k1.events.length).toBe(2);
expect(s.agents.agent1.confidence).toBe(0.8);
expect(traceSummary(s, 12300)).toContain("调度 1 个智能体");
expect(traceSummary(s, 12300)).toContain("复用已验证路径");
});
it("未知或残缺事件不会让界面崩", () => {
let s = emptyTrace();
for (const ev of [null, 1, {}, { type: "tool_done", span: "nope" }, { type: "agent_done", span: "x" }, { type: "tool_event" }]) {
s = applyEvent(s, ev as any);
}
expect(s.order).toEqual([]);
});
it("本体图谱:概念、检索入口、多跳路径都画出来,同名节点连起来", () => {
const g = buildGraph(foldEvents(EVENTS));
const keys = g.payload!.nodes.map((n) => n.key);
expect(keys).toEqual(expect.arrayContaining(["c:c1", "e1", "e2"]));
expect(g.payload!.edges.some((e) => e.source === "e1" && e.target === "e2")).toBe(true);
expect(g.payload!.edges.some((e) => e.attributes.relation === "即")).toBe(true);
expect(buildGraph(emptyTrace()).payload).toBeNull();
});
it("历史轮次归一化:中断轮次的空 links、缺字段都补默认值", () => {
const t = normalizeTurn({ id: "t1", question: "q", status: "aborted", links: {}, plan: null });
expect(t.links.concepts).toEqual([]);
expect(t.links.instances).toEqual([]);
expect(t.steps).toEqual([]);
expect(t.citations).toEqual([]);
expect(t.status).toBe("aborted");
const t2 = normalizeTurn({ links: { concepts: [{ id: "c", name: "n" }] } });
expect(t2.links.concepts[0].matched).toEqual([]);
});
});
import { describe, expect, it } from "vitest";
import type { SopSpec } from "@/lib/onto";
import {
addStep, autoLayout, changeType, connect, deleteStep, disconnect, exits, renameStep, upstreamVars,
} from "@/features/sop/specOps";
const base = (): SopSpec => ({
params: [{ name: "store", label: "网点", type: "object", object_type: "ot", calendar: "", required: true }],
roles: [], trigger: { kind: "manual" }, evidence: [], start: "q",
steps: [
{ id: "q", type: "function", title: "取数", description: "", lane: "", next: "d", output: "amt", function: "metric.query", args: {} },
{ id: "d", type: "decision", title: "判断", description: "", lane: "", next: "", output: "",
branches: [{ when: "amt.value < 1", next: "a", label: "低" }], default: "e" },
{ id: "a", type: "action", title: "动作", description: "", lane: "", next: "e", output: "", action: "x", params: {}, on_reject: "e" },
{ id: "e", type: "end", title: "结束", description: "", lane: "", next: "", output: "", outcome: "" },
],
layout: { q: { x: 0, y: 0 } },
});
describe("流程卡 specOps", () => {
it("删除步骤时清掉所有指向它的引用、布局和开始步骤", () => {
const s = deleteStep(base(), "e");
expect(s.steps.map((x) => x.id)).toEqual(["q", "d", "a"]);
const d = s.steps.find((x) => x.id === "d")!;
const a = s.steps.find((x) => x.id === "a")!;
expect(d.default).toBe("");
expect(a.next).toBe("");
expect(a.on_reject).toBe("");
const s2 = deleteStep(base(), "q");
expect(s2.start).toBe("d");
expect(s2.layout?.q).toBeUndefined();
});
it("改编号时所有引用跟着改;重名或空编号不改", () => {
const s = renameStep(base(), "e", "finish");
expect(s.steps.find((x) => x.id === "d")!.default).toBe("finish");
expect(s.steps.find((x) => x.id === "a")!.on_reject).toBe("finish");
expect(renameStep(base(), "e", "q")).toEqual(base());
expect(renameStep(base(), "e", "!!")).toEqual(base());
expect(renameStep(base(), "q", "start1").start).toBe("start1");
});
it("换类型:清掉旧字段,补上新类型需要的,保留去向", () => {
const s = changeType(base(), "q", "decision");
const d = s.steps.find((x) => x.id === "q")!;
expect(d.function).toBeUndefined();
expect(d.branches?.length).toBe(1);
expect(d.default).toBe("d");
const back = changeType(s, "q", "human_task");
expect(back.steps.find((x) => x.id === "q")!.next).toBe("d");
});
it("连线按出口写到对应字段,断开清空", () => {
let s = connect(base(), "d", "b0", "e");
expect(s.steps.find((x) => x.id === "d")!.branches![0].next).toBe("e");
s = connect(s, "a", "reject", "d");
expect(s.steps.find((x) => x.id === "a")!.on_reject).toBe("d");
s = disconnect(s, "q", "next");
expect(s.steps.find((x) => x.id === "q")!.next).toBe("");
expect(connect(base(), "q", "next", "q")).toEqual(base()); // 不能连自己
});
it("新增步骤:编号不重复,接在后面时自动连上空着的下一步", () => {
const b = base();
b.steps[0].next = "";
const r = addStep(b, "foreach", { after: "q", pos: { x: 1, y: 2 } });
expect(r.id).toBe("s5");
expect(r.spec.steps.find((x) => x.id === "q")!.next).toBe("s5");
expect(r.spec.steps.find((x) => x.id === "s5")!.limit).toBe(20);
expect(r.spec.layout?.s5).toEqual({ x: 1, y: 2 });
});
it("出口与上游变量", () => {
const b = base();
expect(exits(b.steps[1]).map((e) => e.handle)).toEqual(["b0", "default"]);
expect(exits(b.steps[2]).map((e) => e.handle)).toEqual(["next", "reject"]);
expect(upstreamVars(b, "a").map((v) => v.name)).toEqual(["store", "amt"]);
expect(upstreamVars(b, "q").map((v) => v.name)).toEqual(["store"]);
});
it("自动布局按最长路径分层,走不到的放一边", () => {
const b = base();
b.steps.push({ id: "z", type: "end", title: "孤立", description: "", lane: "", next: "", output: "" });
const pos = autoLayout(b);
expect(pos.q.y).toBe(0);
expect(pos.e.y).toBeGreaterThan(pos.a.y); // e 在 a 之后(最长路径)
expect(pos.z.x).toBeGreaterThan(Math.max(pos.q.x, pos.d.x, pos.a.x, pos.e.x));
});
});
...@@ -15,11 +15,11 @@ export function EffectList({ preview }: { preview: ActionPreview }) { ...@@ -15,11 +15,11 @@ export function EffectList({ preview }: { preview: ActionPreview }) {
return ( return (
<ul className="space-y-1.5"> <ul className="space-y-1.5">
{(preview.effects || []).map((e, i) => ( {(preview.effects || []).map((e, i) => (
<li key={i} className="flex items-start gap-2 rounded-md bg-ink/[0.03] px-2 py-1.5 text-[12.5px]"> <li key={i} className="flex items-start gap-2 rounded-md bg-ink/[0.03] px-2 py-1.5 text-label">
<Zap className="mt-0.5 h-3.5 w-3.5 shrink-0 text-brand" /> <Zap className="mt-0.5 h-3.5 w-3.5 shrink-0 text-brand" />
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p>{e.preview?.summary || e.tool}</p> <p>{e.preview?.summary || e.tool}</p>
<p className="mt-0.5 text-[11px] text-muted"> <p className="mt-0.5 text-caption text-muted">
工具 <code className="font-mono">{e.tool}</code> 工具 <code className="font-mono">{e.tool}</code>
{e.external && <span className="ml-1 text-bad">· 调用外部系统</span>} {e.external && <span className="ml-1 text-bad">· 调用外部系统</span>}
</p> </p>
...@@ -72,26 +72,26 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s ...@@ -72,26 +72,26 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s
<div className="rounded-lg border border-brand/30 bg-brand/[0.03] p-3"> <div className="rounded-lg border border-brand/30 bg-brand/[0.03] p-3">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<ShieldCheck className="h-4 w-4 text-brand" /> <ShieldCheck className="h-4 w-4 text-brand" />
<span className="text-[13px] font-medium">建议动作:{card.display_name}</span> <span className="text-body font-medium">建议动作:{card.display_name}</span>
{preview && <Badge tone={RISK_TONE[preview.action.risk_level]}>{RISK[preview.action.risk_level]}</Badge>} {preview && <Badge tone={RISK_TONE[preview.action.risk_level]}>{RISK[preview.action.risk_level]}</Badge>}
{preview?.action.reversible && <Badge tone="bg-ink/5 text-muted"><Undo2 className="h-3 w-3" />可撤销</Badge>} {preview?.action.reversible && <Badge tone="bg-ink/5 text-muted"><Undo2 className="h-3 w-3" />可撤销</Badge>}
</div> </div>
{(defs.length > 0 || card.target_type) && !runId && ( {(defs.length > 0 || card.target_type) && !runId && (
<div className="mt-2 grid gap-2 sm:grid-cols-2"> <div className="mt-2 grid gap-2 sm:grid-cols-2">
{card.target_type && ( {card.target_type && (
<label className="flex items-center gap-2 text-[12px]"><span className="w-20 shrink-0 text-muted">作用对象</span> <label className="flex items-center gap-2 text-label"><span className="w-20 shrink-0 text-muted">作用对象</span>
<input className="input h-8 flex-1 font-mono text-[12px]" value={objKey} placeholder="对象主键" <input className="input h-8 flex-1 font-mono text-label" value={objKey} placeholder="对象主键"
onChange={(e) => { setObjKey(e.target.value); setDirty(true); }} /></label> onChange={(e) => { setObjKey(e.target.value); setDirty(true); }} /></label>
)} )}
{defs.map((d) => ( {defs.map((d) => (
<label key={d.name} className="flex items-center gap-2 text-[12px]"> <label key={d.name} className="flex items-center gap-2 text-label">
<span className="w-20 shrink-0 truncate text-muted" title={d.name}>{d.label || d.name}{d.required && <span className="text-bad">*</span>}</span> <span className="w-20 shrink-0 truncate text-muted" title={d.name}>{d.label || d.name}{d.required && <span className="text-bad">*</span>}</span>
{d.enum?.length ? ( {d.enum?.length ? (
<select className="input h-8 flex-1" value={params[d.name] ?? ""} onChange={(e) => { setParams({ ...params, [d.name]: e.target.value }); setDirty(true); }}> <select className="input h-8 flex-1" value={params[d.name] ?? ""} onChange={(e) => { setParams({ ...params, [d.name]: e.target.value }); setDirty(true); }}>
<option value="">请选择</option>{d.enum.map((x) => <option key={x}>{x}</option>)} <option value="">请选择</option>{d.enum.map((x) => <option key={x}>{x}</option>)}
</select> </select>
) : ( ) : (
<input className="input h-8 flex-1 text-[12.5px]" value={params[d.name] ?? ""} inputMode={d.type === "number" || d.type === "integer" ? "decimal" : undefined} <input className="input h-8 flex-1 text-label" value={params[d.name] ?? ""} inputMode={d.type === "number" || d.type === "integer" ? "decimal" : undefined}
onChange={(e) => { setParams({ ...params, [d.name]: e.target.value }); setDirty(true); }} /> onChange={(e) => { setParams({ ...params, [d.name]: e.target.value }); setDirty(true); }} />
)} )}
</label> </label>
...@@ -100,14 +100,14 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s ...@@ -100,14 +100,14 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s
</div> </div>
)} )}
{err ? ( {err ? (
<p className="mt-2 flex items-center gap-1.5 text-[12.5px] text-warn"> <p className="mt-2 flex items-center gap-1.5 text-label text-warn">
<AlertTriangle className="h-3.5 w-3.5" /> 暂不能提交:{err}{defs.length > 0 && "(改一下上面的参数再预览)"} <AlertTriangle className="h-3.5 w-3.5" /> 暂不能提交:{err}{defs.length > 0 && "(改一下上面的参数再预览)"}
</p> </p>
) : preview && ( ) : preview && (
<> <>
<div className="mt-2"><EffectList preview={preview} /></div> <div className="mt-2"><EffectList preview={preview} /></div>
<div className="mt-2 flex flex-wrap items-center gap-2"> <div className="mt-2 flex flex-wrap items-center gap-2">
<input className="input h-8 min-w-0 flex-1 text-[12.5px]" value={reason} <input className="input h-8 min-w-0 flex-1 text-label" value={reason}
onChange={(e) => setReason(e.target.value)} placeholder="提交理由(审批人会看到)" /> onChange={(e) => setReason(e.target.value)} placeholder="提交理由(审批人会看到)" />
{runId ? ( {runId ? (
<button className="btn btn-sm" onClick={() => go("inbox", { tab: "approvals", run: runId })}> <button className="btn btn-sm" onClick={() => go("inbox", { tab: "approvals", run: runId })}>
...@@ -119,7 +119,7 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s ...@@ -119,7 +119,7 @@ export function SuggestedActionCard({ card, turnId }: { card: AskCard; turnId: s
</button> </button>
)} )}
</div> </div>
<p className="mt-1.5 text-[11px] text-muted"> <p className="mt-1.5 text-caption text-muted">
AI 只能建议,不能执行。提交后由{preview.action?.approver_roles?.length AI 只能建议,不能执行。提交后由{preview.action?.approver_roles?.length
? `「${preview.action.approver_roles.join("、")}」` : "有审批权限的人"}审批,你本人不能审批自己提交的动作。 ? `「${preview.action.approver_roles.join("、")}」` : "有审批权限的人"}审批,你本人不能审批自己提交的动作。
</p> </p>
......
...@@ -25,7 +25,7 @@ export function AskAnswer({ text, citations, dataRefs, streaming }: { ...@@ -25,7 +25,7 @@ export function AskAnswer({ text, citations, dataRefs, streaming }: {
}, [text]); }, [text]);
return ( return (
<div className="prose-answer text-[13.5px] leading-relaxed"> <div className="prose-answer text-body leading-relaxed">
<ReactMarkdown <ReactMarkdown
remarkPlugins={[remarkGfm]} remarkPlugins={[remarkGfm]}
components={{ components={{
...@@ -37,8 +37,8 @@ export function AskAnswer({ text, citations, dataRefs, streaming }: { ...@@ -37,8 +37,8 @@ export function AskAnswer({ text, citations, dataRefs, streaming }: {
return ( return (
<button <button
className={isRun className={isRun
? "mx-0.5 rounded bg-brand2/15 px-1 align-super text-[10px] font-semibold text-brand2 hover:bg-brand2/25" ? "mx-0.5 rounded bg-brand2/15 px-1 align-super text-caption font-semibold text-brand2 hover:bg-brand2/25"
: "mx-0.5 rounded bg-brand/15 px-1 align-super text-[10px] font-semibold text-brand hover:bg-brand/25"} : "mx-0.5 rounded bg-brand/15 px-1 align-super text-caption font-semibold text-brand hover:bg-brand/25"}
title={isRun ? "查看数据来源" : "查看原文"} title={isRun ? "查看数据来源" : "查看原文"}
onClick={() => { onClick={() => {
if (!c) return; if (!c) return;
...@@ -51,16 +51,16 @@ export function AskAnswer({ text, citations, dataRefs, streaming }: { ...@@ -51,16 +51,16 @@ export function AskAnswer({ text, citations, dataRefs, streaming }: {
return <a href={href} target="_blank" rel="noreferrer" className="text-brand underline">{children}</a>; return <a href={href} target="_blank" rel="noreferrer" className="text-brand underline">{children}</a>;
}, },
table: ({ children }) => ( table: ({ children }) => (
<div className="my-2 overflow-x-auto"><table className="w-full border-collapse text-[12.5px]">{children}</table></div> <div className="my-2 overflow-x-auto"><table className="w-full border-collapse text-label">{children}</table></div>
), ),
th: ({ children }) => <th className="border border-line bg-ink/5 px-2 py-1 text-left font-medium">{children}</th>, th: ({ children }) => <th className="border border-line bg-ink/5 px-2 py-1 text-left font-medium">{children}</th>,
td: ({ children }) => <td className="border border-line px-2 py-1">{children}</td>, td: ({ children }) => <td className="border border-line px-2 py-1">{children}</td>,
p: ({ children }) => <p className="my-1.5">{children}</p>, p: ({ children }) => <p className="my-1.5">{children}</p>,
ul: ({ children }) => <ul className="my-1.5 list-disc pl-5">{children}</ul>, ul: ({ children }) => <ul className="my-1.5 list-disc pl-5">{children}</ul>,
ol: ({ children }) => <ol className="my-1.5 list-decimal pl-5">{children}</ol>, ol: ({ children }) => <ol className="my-1.5 list-decimal pl-5">{children}</ol>,
h3: ({ children }) => <h3 className="mt-3 mb-1 text-[14px] font-semibold">{children}</h3>, h3: ({ children }) => <h3 className="mt-3 mb-1 text-body font-semibold">{children}</h3>,
h2: ({ children }) => <h2 className="mt-3 mb-1 text-[15px] font-semibold">{children}</h2>, h2: ({ children }) => <h2 className="mt-3 mb-1 text-title font-semibold">{children}</h2>,
code: ({ children }) => <code className="rounded bg-ink/5 px-1 font-mono text-[12px]">{children}</code>, code: ({ children }) => <code className="rounded bg-ink/5 px-1 font-mono text-label">{children}</code>,
}}> }}>
{md || (streaming ? "…" : "")} {md || (streaming ? "…" : "")}
</ReactMarkdown> </ReactMarkdown>
...@@ -87,7 +87,7 @@ export function AskAnswer({ text, citations, dataRefs, streaming }: { ...@@ -87,7 +87,7 @@ export function AskAnswer({ text, citations, dataRefs, streaming }: {
<Modal open={!!openChunk} onClose={() => setOpenChunk(null)} title={openChunk?.heading || "原文"} <Modal open={!!openChunk} onClose={() => setOpenChunk(null)} title={openChunk?.heading || "原文"}
desc={openChunk ? `片段 ${openChunk.chunk_id} · 文档 #${openChunk.doc_id}` : ""} width="max-w-2xl"> desc={openChunk ? `片段 ${openChunk.chunk_id} · 文档 #${openChunk.doc_id}` : ""} width="max-w-2xl">
<pre className="whitespace-pre-wrap font-sans text-[13px] leading-relaxed">{openChunk?.text}</pre> <pre className="whitespace-pre-wrap font-sans text-body leading-relaxed">{openChunk?.text}</pre>
</Modal> </Modal>
<Modal open={!!openData} onClose={() => setOpenData(null)} width="max-w-3xl" <Modal open={!!openData} onClose={() => setOpenData(null)} width="max-w-3xl"
title={openData?.metric?.name ? `数据来源:${openData.metric.name}` : "数据来源"} title={openData?.metric?.name ? `数据来源:${openData.metric.name}` : "数据来源"}
...@@ -102,16 +102,16 @@ export function DataRefView({ d }: { d: DataRef }) { ...@@ -102,16 +102,16 @@ export function DataRefView({ d }: { d: DataRef }) {
return ( return (
<div className="space-y-3"> <div className="space-y-3">
{d.calibre && ( {d.calibre && (
<div className="rounded-lg border border-line bg-elevated p-2.5 text-[12.5px]"> <div className="rounded-lg border border-line bg-elevated p-2.5 text-label">
<span className="font-medium">口径:</span>{d.calibre.name}{d.calibre.text ? ` — ${d.calibre.text}` : ""} <span className="font-medium">口径:</span>{d.calibre.name}{d.calibre.text ? ` — ${d.calibre.text}` : ""}
</div> </div>
)} )}
<div> <div>
<div className="mb-1 flex items-center justify-between"> <div className="mb-1 flex items-center justify-between">
<span className="text-[12px] font-medium text-muted">执行的 SQL(经只读校验)</span> <span className="text-label font-medium text-muted">执行的 SQL(经只读校验)</span>
<CopyButton text={d.sql} /> <CopyButton text={d.sql} />
</div> </div>
<pre className="max-h-40 overflow-auto rounded-lg bg-ink/5 p-2.5 font-mono text-[11.5px]">{d.sql}</pre> <pre className="max-h-40 overflow-auto rounded-lg bg-ink/5 p-2.5 font-mono text-label">{d.sql}</pre>
</div> </div>
<DataTable columns={d.columns} rows={d.rows} /> <DataTable columns={d.columns} rows={d.rows} />
</div> </div>
...@@ -119,10 +119,10 @@ export function DataRefView({ d }: { d: DataRef }) { ...@@ -119,10 +119,10 @@ export function DataRefView({ d }: { d: DataRef }) {
} }
export function DataTable({ columns, rows, max = 50 }: { columns: string[]; rows: any[][]; max?: number }) { export function DataTable({ columns, rows, max = 50 }: { columns: string[]; rows: any[][]; max?: number }) {
if (!columns?.length) return <p className="text-[12px] text-muted">无数据</p>; if (!columns?.length) return <p className="text-label text-muted">无数据</p>;
return ( return (
<div className="max-h-80 overflow-auto rounded-lg border border-line"> <div className="max-h-80 overflow-auto rounded-lg border border-line">
<table className="w-full text-[12px]"> <table className="w-full text-label">
<thead className="sticky top-0 bg-elevated"> <thead className="sticky top-0 bg-elevated">
<tr>{columns.map((c) => <th key={c} className="border-b border-line px-2 py-1.5 text-left font-medium">{c}</th>)}</tr> <tr>{columns.map((c) => <th key={c} className="border-b border-line px-2 py-1.5 text-left font-medium">{c}</th>)}</tr>
</thead> </thead>
...@@ -134,8 +134,8 @@ export function DataTable({ columns, rows, max = 50 }: { columns: string[]; rows ...@@ -134,8 +134,8 @@ export function DataTable({ columns, rows, max = 50 }: { columns: string[]; rows
))} ))}
</tbody> </tbody>
</table> </table>
{rows.length > max && <p className="px-2 py-1 text-[11px] text-muted">仅显示前 {max} 行,共 {rows.length} 行</p>} {rows.length > max && <p className="px-2 py-1 text-caption text-muted">仅显示前 {max} 行,共 {rows.length} 行</p>}
{rows.length === 0 && <p className="px-2 py-2 text-[12px] text-muted">查询成功,但没有数据</p>} {rows.length === 0 && <p className="px-2 py-2 text-label text-muted">查询成功,但没有数据</p>}
</div> </div>
); );
} }
......
...@@ -280,15 +280,15 @@ export function AskPage() { ...@@ -280,15 +280,15 @@ export function AskPage() {
</button> </button>
</div> </div>
<div className="min-h-0 flex-1 space-y-0.5 overflow-auto p-1.5"> <div className="min-h-0 flex-1 space-y-0.5 overflow-auto p-1.5">
{convs.length === 0 && <p className="p-3 text-center text-[12px] text-muted">还没有对话</p>} {convs.length === 0 && <p className="p-3 text-center text-label text-muted">还没有对话</p>}
{convs.map((c) => ( {convs.map((c) => (
<div key={c.id} role="button" tabIndex={0} <div key={c.id} role="button" tabIndex={0}
className={cn("group flex cursor-pointer items-center gap-1 rounded-md px-2 py-1.5 text-[12.5px]", className={cn("group flex cursor-pointer items-center gap-1 rounded-md px-2 py-1.5 text-label",
c.id === convId ? "bg-brand/10 text-brand" : "hover:bg-ink/5")} c.id === convId ? "bg-brand/10 text-brand" : "hover:bg-ink/5")}
onClick={() => void openConv(c.id)} onClick={() => void openConv(c.id)}
onKeyDown={(e) => { if (e.key === "Enter") void openConv(c.id); }}> onKeyDown={(e) => { if (e.key === "Enter") void openConv(c.id); }}>
<span className="min-w-0 flex-1 truncate">{c.title || "未命名"}</span> <span className="min-w-0 flex-1 truncate">{c.title || "未命名"}</span>
<span className="shrink-0 text-[10.5px] text-muted group-hover:hidden">{c.turns}</span> <span className="shrink-0 text-caption text-muted group-hover:hidden">{c.turns}</span>
<button className="hidden shrink-0 text-muted hover:text-bad group-hover:block" title="删除对话" aria-label="删除对话" <button className="hidden shrink-0 text-muted hover:text-bad group-hover:block" title="删除对话" aria-label="删除对话"
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
...@@ -314,7 +314,7 @@ export function AskPage() { ...@@ -314,7 +314,7 @@ export function AskPage() {
</div> </div>
<div className="min-h-0 flex-1 overflow-auto pr-1"> <div className="min-h-0 flex-1 overflow-auto pr-1">
{loadingConv && !turns.length ? ( {loadingConv && !turns.length ? (
<p className="p-6 text-center text-[12.5px] text-muted">正在打开对话…</p> <p className="p-6 text-center text-label text-muted">正在打开对话…</p>
) : turns.length === 0 ? ( ) : turns.length === 0 ? (
<Welcome examples={examples} onAsk={ask} /> <Welcome examples={examples} onAsk={ask} />
) : ( ) : (
...@@ -352,7 +352,7 @@ export function AskPage() { ...@@ -352,7 +352,7 @@ export function AskPage() {
wide ? "w-[420px] shrink-0" : "fixed inset-y-2 right-2 z-50 w-[min(440px,94vw)] animate-fade-up")}> wide ? "w-[420px] shrink-0" : "fixed inset-y-2 right-2 z-50 w-[min(440px,94vw)] animate-fade-up")}>
<div className="flex items-center gap-2 border-b border-line px-3 py-2"> <div className="flex items-center gap-2 border-b border-line px-3 py-2">
<Brain className="h-4 w-4 text-brand" /> <Brain className="h-4 w-4 text-brand" />
<span className="text-[13px] font-semibold">推理过程</span> <span className="text-body font-semibold">推理过程</span>
{sel?.replaying && <Badge tone="bg-warn/10 text-warn">回放中</Badge>} {sel?.replaying && <Badge tone="bg-warn/10 text-warn">回放中</Badge>}
<div className="ml-auto flex items-center gap-1"> <div className="ml-auto flex items-center gap-1">
{sel && sel.status !== "running" && sel.events.length > 0 && ( {sel && sel.status !== "running" && sel.events.length > 0 && (
...@@ -364,7 +364,7 @@ export function AskPage() { ...@@ -364,7 +364,7 @@ export function AskPage() {
<button className="btn btn-ghost btn-sm" onClick={closePanel} aria-label="收起推理面板"><PanelRightClose className="h-4 w-4" /></button> <button className="btn btn-ghost btn-sm" onClick={closePanel} aria-label="收起推理面板"><PanelRightClose className="h-4 w-4" /></button>
</div> </div>
</div> </div>
{sel && <p className="truncate border-b border-line px-3 py-1.5 text-[12px] text-muted" title={sel.question}>问:{sel.question}</p>} {sel && <p className="truncate border-b border-line px-3 py-1.5 text-label text-muted" title={sel.question}>问:{sel.question}</p>}
<div className="border-b border-line px-3 py-1.5"> <div className="border-b border-line px-3 py-1.5">
<Segmented value={tab} onChange={setTab} options={[ <Segmented value={tab} onChange={setTab} options={[
{ key: "chain", label: <><GitBranch className="h-3.5 w-3.5" />推理链</> }, { key: "chain", label: <><GitBranch className="h-3.5 w-3.5" />推理链</> },
...@@ -381,7 +381,7 @@ export function AskPage() { ...@@ -381,7 +381,7 @@ export function AskPage() {
)} )}
<Modal open={!!chunk} onClose={() => setChunk(null)} width="max-w-2xl" title={chunk?.heading || "原文"} <Modal open={!!chunk} onClose={() => setChunk(null)} width="max-w-2xl" title={chunk?.heading || "原文"}
desc={chunk ? `${chunk.document?.filename || `文档 #${chunk.doc_id}`} · 片段 ${chunk.id}` : ""}> desc={chunk ? `${chunk.document?.filename || `文档 #${chunk.doc_id}`} · 片段 ${chunk.id}` : ""}>
<pre className="whitespace-pre-wrap font-sans text-[13px] leading-relaxed">{chunk?.text}</pre> <pre className="whitespace-pre-wrap font-sans text-body leading-relaxed">{chunk?.text}</pre>
</Modal> </Modal>
</div> </div>
); );
...@@ -400,8 +400,8 @@ function Welcome({ examples, onAsk }: { examples: string[]; onAsk: (q: string) = ...@@ -400,8 +400,8 @@ function Welcome({ examples, onAsk }: { examples: string[]; onAsk: (q: string) =
<div className="mt-1 grid gap-2 sm:grid-cols-3"> <div className="mt-1 grid gap-2 sm:grid-cols-3">
{cards.map((c) => ( {cards.map((c) => (
<div key={c.title} className="rounded-xl border border-line bg-surface p-3"> <div key={c.title} className="rounded-xl border border-line bg-surface p-3">
<p className="flex items-center gap-1.5 text-[12.5px] font-semibold" style={{ color: c.color }}>{c.icon}{c.title}</p> <p className="flex items-center gap-1.5 text-label font-semibold" style={{ color: c.color }}>{c.icon}{c.title}</p>
<p className="mt-1 text-[12px] leading-relaxed text-muted">{c.desc}</p> <p className="mt-1 text-label leading-relaxed text-muted">{c.desc}</p>
</div> </div>
))} ))}
</div> </div>
...@@ -426,7 +426,7 @@ function TurnView({ t, onAsk, active, onSelect, onReplay, disabled }: { ...@@ -426,7 +426,7 @@ function TurnView({ t, onAsk, active, onSelect, onReplay, disabled }: {
return ( return (
<div className="space-y-2"> <div className="space-y-2">
<div className="flex justify-end"> <div className="flex justify-end">
<div className="max-w-[80%] whitespace-pre-wrap break-words rounded-2xl rounded-br-sm bg-brand px-3.5 py-2 text-[13.5px] text-white">{t.question}</div> <div className="max-w-[80%] whitespace-pre-wrap break-words rounded-2xl rounded-br-sm bg-brand px-3.5 py-2 text-body text-white">{t.question}</div>
</div> </div>
<div className={cn(active && "rounded-xl ring-1 ring-brand/20")}> <div className={cn(active && "rounded-xl ring-1 ring-brand/20")}>
...@@ -437,14 +437,14 @@ function TurnView({ t, onAsk, active, onSelect, onReplay, disabled }: { ...@@ -437,14 +437,14 @@ function TurnView({ t, onAsk, active, onSelect, onReplay, disabled }: {
{showAnswer && ( {showAnswer && (
<div className="card p-4"> <div className="card p-4">
{t.status === "aborted" && ( {t.status === "aborted" && (
<div className="mb-2 flex items-center gap-2 rounded-lg border border-warn/30 bg-warn/5 px-3 py-2 text-[12.5px]"> <div className="mb-2 flex items-center gap-2 rounded-lg border border-warn/30 bg-warn/5 px-3 py-2 text-label">
<XCircle className="h-4 w-4 shrink-0 text-warn" /> <XCircle className="h-4 w-4 shrink-0 text-warn" />
<span className="flex-1">这次回答被中断了(点了停止、切换了对话或网络断开){t.answer ? ",下面是中断前的内容" : ""}。</span> <span className="flex-1">这次回答被中断了(点了停止、切换了对话或网络断开){t.answer ? ",下面是中断前的内容" : ""}。</span>
<button className="btn btn-sm" disabled={disabled} onClick={() => onAsk(t.question)}><RotateCcw className="h-3.5 w-3.5" /> 重新提问</button> <button className="btn btn-sm" disabled={disabled} onClick={() => onAsk(t.question)}><RotateCcw className="h-3.5 w-3.5" /> 重新提问</button>
</div> </div>
)} )}
{t.status === "error" && ( {t.status === "error" && (
<div className="mb-2 flex items-center gap-2 rounded-lg border border-bad/30 bg-bad/5 px-3 py-2 text-[12.5px]"> <div className="mb-2 flex items-center gap-2 rounded-lg border border-bad/30 bg-bad/5 px-3 py-2 text-label">
<XCircle className="h-4 w-4 shrink-0 text-bad" /> <XCircle className="h-4 w-4 shrink-0 text-bad" />
<span className="min-w-0 flex-1 break-words">没能完成回答:{t.error || "服务出错"}</span> <span className="min-w-0 flex-1 break-words">没能完成回答:{t.error || "服务出错"}</span>
<button className="btn btn-sm" disabled={disabled} onClick={() => onAsk(t.question)}><RotateCcw className="h-3.5 w-3.5" /> 重试</button> <button className="btn btn-sm" disabled={disabled} onClick={() => onAsk(t.question)}><RotateCcw className="h-3.5 w-3.5" /> 重试</button>
...@@ -456,7 +456,7 @@ function TurnView({ t, onAsk, active, onSelect, onReplay, disabled }: { ...@@ -456,7 +456,7 @@ function TurnView({ t, onAsk, active, onSelect, onReplay, disabled }: {
)} )}
{t.status !== "running" && memory && memory.cases.length > 0 && ( {t.status !== "running" && memory && memory.cases.length > 0 && (
<button className="mt-2 flex items-center gap-1.5 text-[11.5px] text-muted hover:text-brand" onClick={onSelect}> <button className="mt-2 flex items-center gap-1.5 text-label text-muted hover:text-brand" onClick={onSelect}>
<History className="h-3.5 w-3.5" /> <History className="h-3.5 w-3.5" />
{memory.fast ? "复用了已验证案例的分析路径" : `参考了 ${memory.cases.length} 个相似的历史问答`} {memory.fast ? "复用了已验证案例的分析路径" : `参考了 ${memory.cases.length} 个相似的历史问答`}
<ChevronRight className="h-3 w-3" /> <ChevronRight className="h-3 w-3" />
...@@ -470,7 +470,7 @@ function TurnView({ t, onAsk, active, onSelect, onReplay, disabled }: { ...@@ -470,7 +470,7 @@ function TurnView({ t, onAsk, active, onSelect, onReplay, disabled }: {
<div className="space-y-4"> <div className="space-y-4">
{t.data_refs.map((d) => ( {t.data_refs.map((d) => (
<div key={d.run_id}> <div key={d.run_id}>
<p className="mb-1 text-[12px] font-medium"> <p className="mb-1 text-label font-medium">
{d.metric?.name || "自由取数"} <span className="text-muted">· 取数记录 #{d.run_id}</span> {d.metric?.name || "自由取数"} <span className="text-muted">· 取数记录 #{d.run_id}</span>
</p> </p>
<DataRefView d={d} /> <DataRefView d={d} />
...@@ -488,7 +488,7 @@ function TurnView({ t, onAsk, active, onSelect, onReplay, disabled }: { ...@@ -488,7 +488,7 @@ function TurnView({ t, onAsk, active, onSelect, onReplay, disabled }: {
)} )}
{t.sops.length > 0 && t.status !== "running" && ( {t.sops.length > 0 && t.status !== "running" && (
<div className="mt-3 flex flex-wrap items-center gap-2 rounded-lg border border-line p-2.5 text-[12.5px]"> <div className="mt-3 flex flex-wrap items-center gap-2 rounded-lg border border-line p-2.5 text-label">
<ListChecks className="h-4 w-4 text-brand" /> 建议按流程处理: <ListChecks className="h-4 w-4 text-brand" /> 建议按流程处理:
{t.sops.map((s: any, i: number) => ( {t.sops.map((s: any, i: number) => (
<button key={i} className="chip hover:border-brand/40" title={s.reason} <button key={i} className="chip hover:border-brand/40" title={s.reason}
...@@ -501,9 +501,9 @@ function TurnView({ t, onAsk, active, onSelect, onReplay, disabled }: { ...@@ -501,9 +501,9 @@ function TurnView({ t, onAsk, active, onSelect, onReplay, disabled }: {
{t.status === "done" && t.follow_ups.length > 0 && ( {t.status === "done" && t.follow_ups.length > 0 && (
<div className="mt-3 flex flex-wrap items-center gap-1.5"> <div className="mt-3 flex flex-wrap items-center gap-1.5">
<span className="text-[11.5px] text-muted">接着问:</span> <span className="text-label text-muted">接着问:</span>
{t.follow_ups.map((q) => ( {t.follow_ups.map((q) => (
<button key={q} className="chip text-[12px] hover:border-brand/40" disabled={disabled} onClick={() => onAsk(q)}>{q}</button> <button key={q} className="chip text-label hover:border-brand/40" disabled={disabled} onClick={() => onAsk(q)}>{q}</button>
))} ))}
</div> </div>
)} )}
......
/**
* 多智能体推理轨迹:把后端事件折叠成「主 Agent → 子 Agent → 工具调用」的状态树。
*
* 实时流和历史回放用的是同一个 reducer:回放就是把落库的事件按原来的节奏重新喂一遍。
* 另外从事件里拼出「本体图谱」—— 链接到的概念、知识检索每一跳的路径、关系网遍历与影响分析的对象,
* 随推理进行一点点长出来。
*/
import type { GraphPayload } from "@/lib/types";
export type NodeStatus = "running" | "done" | "error";
export interface AgentNode {
span: string; agent: string; label: string; task: string; status: NodeStatus;
thought: string; summary: string; findings: string[]; insights: string[]; confidence?: number;
tools: string[]; startTs: number; ms?: number;
}
export interface ToolNode {
span: string; parent: string; agent: string; tool: string; label: string; args: any; why: string;
status: NodeStatus; summary: string; error: string; result: any; events: any[]; startTs: number; ms?: number;
}
export interface TraceState {
agents: Record<string, AgentNode>;
order: string[]; // agent span 顺序
tools: Record<string, ToolNode>;
links: { concepts: any[]; instances: any[]; time: any } | null;
memory: { cases: any[]; facts: any[]; fast: string } | null;
plan: any | null;
reflect: any[];
lastTs: number;
events: number;
}
export const emptyTrace = (): TraceState => ({
agents: {}, order: [], tools: {}, links: null, memory: null, plan: null, reflect: [], lastTs: 0, events: 0,
});
const arr = <T,>(v: unknown): T[] => (Array.isArray(v) ? (v as T[]) : []);
/** 纯函数:返回新状态(浅拷贝被改动的部分),React 里直接 setState。 */
export function applyEvent(s: TraceState, ev: any): TraceState {
if (!ev || typeof ev !== "object") return s;
const ts = typeof ev.ts === "number" ? ev.ts : s.lastTs;
const next: TraceState = { ...s, lastTs: Math.max(s.lastTs, ts), events: s.events + 1 };
switch (ev.type) {
case "link":
next.links = { concepts: arr(ev.concepts), instances: arr(ev.instances), time: ev.time ?? null };
return next;
case "memory":
next.memory = { cases: arr(ev.cases), facts: arr(ev.facts), fast: ev.fast || "" };
return next;
case "plan":
next.plan = ev;
return next;
case "reflect":
next.reflect = [...s.reflect, ev];
return next;
case "agent_start": {
const span = String(ev.span || "");
if (!span) return next;
const prev = s.agents[span];
next.agents = { ...s.agents, [span]: {
span, agent: ev.agent || "", label: ev.label || ev.agent || "", task: ev.task || "",
status: "running", thought: prev?.thought || "", summary: "", findings: [], insights: [],
tools: prev?.tools || [], startTs: ts } };
next.order = s.order.includes(span) ? s.order : [...s.order, span];
return next;
}
case "thought": {
const span = String(ev.span || "");
const a = s.agents[span] || {
span, agent: ev.agent || span, label: ev.agent || span, task: "", status: "running" as NodeStatus,
thought: "", summary: "", findings: [], insights: [], tools: [], startTs: ts };
next.agents = { ...s.agents, [span]: { ...a, thought: a.thought + (ev.text || "") } };
if (!s.order.includes(span)) next.order = [...s.order, span];
return next;
}
case "agent_done": {
const a = s.agents[ev.span];
if (!a) return next;
next.agents = { ...s.agents, [ev.span]: {
...a, status: ev.ok === false ? "error" : "done", summary: ev.summary || "",
findings: arr<string>(ev.findings), insights: arr<string>(ev.insights),
confidence: typeof ev.confidence === "number" ? ev.confidence : undefined, ms: ev.ms } };
return next;
}
case "tool_start": {
const span = String(ev.span || "");
next.tools = { ...s.tools, [span]: {
span, parent: ev.parent || "", agent: ev.agent || "", tool: ev.tool || "", label: ev.label || ev.tool || "",
args: ev.args ?? {}, why: ev.why || "", status: "running", summary: "", error: "", result: null,
events: [], startTs: ts } };
const a = s.agents[ev.parent];
if (a && !a.tools.includes(span)) next.agents = { ...s.agents, [ev.parent]: { ...a, tools: [...a.tools, span] } };
return next;
}
case "tool_event": {
const t = s.tools[ev.span];
if (!t) return next;
next.tools = { ...s.tools, [ev.span]: { ...t, events: [...t.events, ev.event] } };
return next;
}
case "tool_done": {
const t = s.tools[ev.span];
if (!t) return next;
next.tools = { ...s.tools, [ev.span]: {
...t, status: ev.ok ? "done" : "error", summary: ev.summary || "", error: ev.error || "",
result: ev.result ?? null, ms: ev.ms } };
return next;
}
default:
return next;
}
}
export function foldEvents(events: any[]): TraceState {
return arr<any>(events).reduce(applyEvent, emptyTrace());
}
/** 一句话摘要:给折叠后的思考卡用。 */
export function traceSummary(s: TraceState, durationMs?: number): string {
const subs = s.order.filter((sp) => s.agents[sp]?.agent !== "lead").length;
const tools = Object.values(s.tools);
const hops = tools.reduce((n, t) => n + t.events.filter((e) => e?.type === "hop").length, 0);
const sqls = tools.reduce((n, t) => n + t.events.filter((e) => e?.type === "sql").length, 0)
+ tools.filter((t) => t.result?.run_id && !t.events.some((e) => e?.type === "sql")).length;
const cases = s.memory?.cases?.length || 0;
return [
subs && `调度 ${subs} 个智能体`,
tools.length && `${tools.length} 次工具调用`,
hops && `图谱 ${hops} 轮扩展`,
sqls && `取数 ${sqls} 次`,
cases && `参考 ${cases} 个历史案例`,
s.memory?.fast && "复用已验证路径",
durationMs ? `${(durationMs / 1000).toFixed(1)}s` : "",
].filter(Boolean).join(" · ");
}
// ------------------------------------------------------------------ 图谱
export interface GraphBuild { payload: GraphPayload | null; emphasis: { nodes: Set<string>; edges: Set<string>; seeds: Set<string> } | null }
const KIND_TYPE: Record<string, string> = {
object_type: "对象", link_type: "关系", aggregate: "指标", rule: "规则", calendar: "周期",
decision: "决策表", ml: "模型", ai: "AI 分析", action: "动作", function: "函数",
};
/**
* 从轨迹拼出一张子图:
* - 本体概念(链接到的指标、对象、规则…)作为种子
* - 知识检索:link 命中的实体为种子、每一跳 hop 的路径逐条加进来
* - 关系网遍历 / 影响分析:对象实例与关系边
*/
export function buildGraph(s: TraceState): GraphBuild {
const nodes = new Map<string, { label: string; type: string; seed: boolean; degree: number }>();
const edges = new Map<string, { source: string; target: string; relation: string; occurrence: number }>();
const seeds = new Set<string>();
const add = (id: string, label?: string, type?: string, seed = false) => {
if (!id) return;
const cur = nodes.get(id);
nodes.set(id, { label: label || cur?.label || id, type: type || cur?.type || "其他",
seed: seed || cur?.seed || false, degree: (cur?.degree || 1) + 1 });
if (seed) seeds.add(id);
};
const edge = (id: string, source: string, target: string, relation: string, occurrence = 1) => {
if (!source || !target || source === target) return;
edges.set(id || `${source}|${relation}|${target}`, { source, target, relation, occurrence });
};
for (const c of s.links?.concepts || []) {
add(`c:${c.id}`, c.name, KIND_TYPE[c.type_key || c.kind] || "概念", true);
}
for (const i of s.links?.instances || []) {
add(`${i.concept_id}:${i.key}`, `${i.label}`, i.type_name || "对象", true);
}
for (const t of Object.values(s.tools)) {
for (const ev of t.events) {
if (ev?.type === "link") {
for (const l of arr<any>(ev.links)) for (const m of arr<any>(l.matches)) add(m.id, m.label, m.type, true);
} else if (ev?.type === "hop") {
for (const p of arr<any>(ev.paths)) {
add(p.source); add(p.target);
edge(p.id, p.source, p.target, p.relation, p.occurrence || 1);
}
}
}
const r = t.result;
if (!r || typeof r !== "object") continue;
if (r.subgraph && Array.isArray(r.subgraph.nodes)) {
for (const n of r.subgraph.nodes) add(n.id, n.label, n.type, !!n.seed);
for (const e of arr<any>(r.subgraph.edges)) edge(e.id, e.source, e.target, e.relation, e.occurrence || 1);
}
if (Array.isArray(r.nodes) && r.root) { // traverse_link / impact_analysis
for (const n of r.nodes) add(n.id, n.label, n.type_name, n.id === r.root.id);
for (const e of arr<any>(r.edges)) edge(`${e.from}|${e.link_id}|${e.to}`, e.from, e.to, e.link || "", 1);
}
}
if (!nodes.size) return { payload: null, emphasis: null };
// 本体概念和检索到的实体往往同名:同名的连一条虚线,图不会碎成两块
const byLabel = new Map<string, string>();
for (const [id, n] of nodes) {
const k = n.label.trim();
const other = byLabel.get(k);
if (other && other !== id) edge(`same:${other}:${id}`, other, id, "即", 1);
else byLabel.set(k, id);
}
const payload: GraphPayload = {
nodes: [...nodes].map(([key, v]) => ({
key, attributes: { label: v.label, type: v.type, degree: v.degree, size: v.seed ? 11 : 6 + Math.min(6, v.degree),
community: null, occurrence: 1, doc_ids: [], verified: false },
})),
edges: [...edges].filter(([, e]) => nodes.has(e.source) && nodes.has(e.target)).map(([key, e]) => ({
key, source: e.source, target: e.target,
attributes: { label: e.relation, relation: e.relation, occurrence: e.occurrence,
size: 1 + Math.min(2.5, e.occurrence * 0.25), verified: false },
})),
truncated: false, total_matched: nodes.size,
};
return { payload, emphasis: { nodes: new Set(nodes.keys()), edges: new Set(edges.keys()), seeds } };
}
...@@ -46,19 +46,19 @@ function AuditLog() { ...@@ -46,19 +46,19 @@ function AuditLog() {
{!data ? <div className="p-4"><Spinner /></div> : !data.items.length ? <Empty icon={<ScrollText className="h-10 w-10" />} title="没有记录" /> : ( {!data ? <div className="p-4"><Spinner /></div> : !data.items.length ? <Empty icon={<ScrollText className="h-10 w-10" />} title="没有记录" /> : (
<div className="divide-y divide-line"> <div className="divide-y divide-line">
{data.items.map((a) => ( {data.items.map((a) => (
<button key={a.id} className="flex w-full items-center gap-3 px-4 py-2 text-left text-[12.5px] hover:bg-ink/[0.03]" <button key={a.id} className="flex w-full items-center gap-3 px-4 py-2 text-left text-label hover:bg-ink/[0.03]"
onClick={() => void onto.auditOne(a.id).then(setOpen)}> onClick={() => void onto.auditOne(a.id).then(setOpen)}>
<span className="w-32 shrink-0 text-muted">{fmtTime(a.ts)}</span> <span className="w-32 shrink-0 text-muted">{fmtTime(a.ts)}</span>
<Badge tone={ACTOR_TONE[a.actor_kind]}>{a.actor_kind === "ai" ? "AI" : a.actor_kind === "system" ? "系统" : "人"}</Badge> <Badge tone={ACTOR_TONE[a.actor_kind]}>{a.actor_kind === "ai" ? "AI" : a.actor_kind === "system" ? "系统" : "人"}</Badge>
<span className="w-24 shrink-0 truncate">{a.actor_name || a.actor_id}</span> <span className="w-24 shrink-0 truncate">{a.actor_name || a.actor_id}</span>
<code className="w-36 shrink-0 truncate text-[11px] text-muted">{a.event}</code> <code className="w-36 shrink-0 truncate text-caption text-muted">{a.event}</code>
<span className="min-w-0 flex-1 truncate">{a.summary}</span> <span className="min-w-0 flex-1 truncate">{a.summary}</span>
</button> </button>
))} ))}
</div> </div>
)} )}
{data && data.total > 50 && ( {data && data.total > 50 && (
<div className="flex items-center justify-end gap-2 border-t border-line p-2 text-[12px]"> <div className="flex items-center justify-end gap-2 border-t border-line p-2 text-label">
<button className="btn btn-sm" disabled={page === 0} onClick={() => setPage(page - 1)}>上一页</button> <button className="btn btn-sm" disabled={page === 0} onClick={() => setPage(page - 1)}>上一页</button>
<span>{page + 1} / {Math.ceil(data.total / 50)}</span> <span>{page + 1} / {Math.ceil(data.total / 50)}</span>
<button className="btn btn-sm" disabled={(page + 1) * 50 >= data.total} onClick={() => setPage(page + 1)}>下一页</button> <button className="btn btn-sm" disabled={(page + 1) * 50 >= data.total} onClick={() => setPage(page + 1)}>下一页</button>
...@@ -68,8 +68,8 @@ function AuditLog() { ...@@ -68,8 +68,8 @@ function AuditLog() {
<Modal open onClose={() => setOpen(null)} width="max-w-3xl" title={open.summary} <Modal open onClose={() => setOpen(null)} width="max-w-3xl" title={open.summary}
desc={`${fmtTime(open.ts)} · ${open.actor_name}(${open.actor_kind})· ${open.event} · ${open.target_type}:${open.target_id}`}> desc={`${fmtTime(open.ts)} · ${open.actor_name}(${open.actor_kind})· ${open.event} · ${open.target_type}:${open.target_id}`}>
<div className="grid gap-3 md:grid-cols-2"> <div className="grid gap-3 md:grid-cols-2">
<div><p className="mb-1 text-[12px] text-muted">之前</p><pre className="max-h-96 overflow-auto rounded bg-ink/5 p-2 text-[11px]">{JSON.stringify(open.before, null, 2)}</pre></div> <div><p className="mb-1 text-label text-muted">之前</p><pre className="max-h-96 overflow-auto rounded bg-ink/5 p-2 text-caption">{JSON.stringify(open.before, null, 2)}</pre></div>
<div><p className="mb-1 text-[12px] text-muted">之后</p><pre className="max-h-96 overflow-auto rounded bg-ink/5 p-2 text-[11px]">{JSON.stringify(open.after, null, 2)}</pre></div> <div><p className="mb-1 text-label text-muted">之后</p><pre className="max-h-96 overflow-auto rounded bg-ink/5 p-2 text-caption">{JSON.stringify(open.after, null, 2)}</pre></div>
</div> </div>
</Modal> </Modal>
)} )}
...@@ -95,7 +95,7 @@ function LlmUsage() { ...@@ -95,7 +95,7 @@ function LlmUsage() {
<div className="grid gap-4 xl:grid-cols-2"> <div className="grid gap-4 xl:grid-cols-2">
<Card> <Card>
<CardHeader title="按功能" /> <CardHeader title="按功能" />
<table className="w-full text-[12.5px]"> <table className="w-full text-label">
<thead><tr className="text-left text-muted">{["功能", "调用", "输入 token", "输出 token", "平均耗时", "命中缓存", "失败"].map((h) => <th key={h} className="px-3 py-1.5 font-medium">{h}</th>)}</tr></thead> <thead><tr className="text-left text-muted">{["功能", "调用", "输入 token", "输出 token", "平均耗时", "命中缓存", "失败"].map((h) => <th key={h} className="px-3 py-1.5 font-medium">{h}</th>)}</tr></thead>
<tbody>{d.features.map((f: any) => ( <tbody>{d.features.map((f: any) => (
<tr key={f.feature} className="border-t border-line"> <tr key={f.feature} className="border-t border-line">
...@@ -111,7 +111,7 @@ function LlmUsage() { ...@@ -111,7 +111,7 @@ function LlmUsage() {
{d.daily.map((x: any) => ( {d.daily.map((x: any) => (
<div key={x.date} className="flex flex-1 flex-col items-center gap-1" title={`${x.date}:${x.calls} 次,${x.tokens} token`}> <div key={x.date} className="flex flex-1 flex-col items-center gap-1" title={`${x.date}:${x.calls} 次,${x.tokens} token`}>
<div className="w-full rounded-t bg-brand/70" style={{ height: `${(x.calls / max) * 140}px` }} /> <div className="w-full rounded-t bg-brand/70" style={{ height: `${(x.calls / max) * 140}px` }} />
<span className="text-[10px] text-muted">{x.date.slice(5)}</span> <span className="text-caption text-muted">{x.date.slice(5)}</span>
</div> </div>
))} ))}
{!d.daily.length && <Empty title="暂无数据" />} {!d.daily.length && <Empty title="暂无数据" />}
......
...@@ -39,10 +39,10 @@ export function CapabilityPage({ me }: { me: Me | null }) { ...@@ -39,10 +39,10 @@ export function CapabilityPage({ me }: { me: Me | null }) {
<button key={d.id} onClick={() => setSel(d.id)} <button key={d.id} onClick={() => setSel(d.id)}
className={cn("block w-full px-3 py-2 text-left hover:bg-ink/[0.03]", sel === d.id && "bg-brand/5")}> className={cn("block w-full px-3 py-2 text-left hover:bg-ink/[0.03]", sel === d.id && "bg-brand/5")}>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="min-w-0 flex-1 truncate text-[13px] font-medium">{d.display_name || d.name}</span> <span className="min-w-0 flex-1 truncate text-body font-medium">{d.display_name || d.name}</span>
<Badge tone={STATUS_TONE[d.status]}>{STATUS_LABEL[d.status]}</Badge> <Badge tone={STATUS_TONE[d.status]}>{STATUS_LABEL[d.status]}</Badge>
</div> </div>
<p className="truncate text-[11px] text-muted">{d.spec.url}</p> <p className="truncate text-caption text-muted">{d.spec.url}</p>
</button> </button>
))} ))}
</div> </div>
...@@ -71,18 +71,18 @@ function Builtins({ cat }: { cat: { functions: FunctionBrief[]; tools: ToolBrief ...@@ -71,18 +71,18 @@ function Builtins({ cat }: { cat: { functions: FunctionBrief[]; tools: ToolBrief
{cat.functions.map((f) => ( {cat.functions.map((f) => (
<div key={f.name} className="px-4 py-2.5"> <div key={f.name} className="px-4 py-2.5">
<button className="w-full text-left" onClick={() => { setOpen(open === f.name ? "" : f.name); setOut(null); setArgs("{}"); }}> <button className="w-full text-left" onClick={() => { setOpen(open === f.name ? "" : f.name); setOut(null); setArgs("{}"); }}>
<p className="text-[13px] font-medium">{f.title} <code className="ml-1 text-[11px] text-muted">{f.name}</code></p> <p className="text-body font-medium">{f.title} <code className="ml-1 text-caption text-muted">{f.name}</code></p>
<p className="text-[12px] text-muted">{f.description}</p> <p className="text-label text-muted">{f.description}</p>
</button> </button>
{open === f.name && ( {open === f.name && (
<div className="mt-2 space-y-2"> <div className="mt-2 space-y-2">
<p className="text-[11px] text-muted">参数:{Object.entries(f.input_schema.properties || {}).map(([k, v]: any) => <p className="text-caption text-muted">参数:{Object.entries(f.input_schema.properties || {}).map(([k, v]: any) =>
`${k}${(f.input_schema.required || []).includes(k) ? "*" : ""}(${v.description || v.type})`).join(";")}</p> `${k}${(f.input_schema.required || []).includes(k) ? "*" : ""}(${v.description || v.type})`).join(";")}</p>
<textarea className="input min-h-[60px] font-mono text-[12px]" value={args} onChange={(e) => setArgs(e.target.value)} /> <textarea className="input min-h-[60px] font-mono text-label" value={args} onChange={(e) => setArgs(e.target.value)} />
<button className="btn btn-sm" onClick={async () => { <button className="btn btn-sm" onClick={async () => {
try { setOut(await onto.callFunction(f.name, JSON.parse(args || "{}"))); } catch (e) { setOut({ error: errText(e) }); } try { setOut(await onto.callFunction(f.name, JSON.parse(args || "{}"))); } catch (e) { setOut({ error: errText(e) }); }
}}><Play className="h-3.5 w-3.5" />试调用</button> }}><Play className="h-3.5 w-3.5" />试调用</button>
{out && <pre className="max-h-64 overflow-auto rounded bg-ink/5 p-2 text-[11px]">{JSON.stringify(out, null, 2)}</pre>} {out && <pre className="max-h-64 overflow-auto rounded bg-ink/5 p-2 text-caption">{JSON.stringify(out, null, 2)}</pre>}
</div> </div>
)} )}
</div> </div>
...@@ -95,10 +95,10 @@ function Builtins({ cat }: { cat: { functions: FunctionBrief[]; tools: ToolBrief ...@@ -95,10 +95,10 @@ function Builtins({ cat }: { cat: { functions: FunctionBrief[]; tools: ToolBrief
<div className="divide-y divide-line"> <div className="divide-y divide-line">
{cat.tools.map((t) => ( {cat.tools.map((t) => (
<div key={t.name} className="px-4 py-2.5"> <div key={t.name} className="px-4 py-2.5">
<p className="flex items-center gap-2 text-[13px] font-medium">{t.title} <code className="text-[11px] text-muted">{t.name}</code> <p className="flex items-center gap-2 text-body font-medium">{t.title} <code className="text-caption text-muted">{t.name}</code>
<Badge tone={RISK_TONE[t.risk_level]}>{t.risk_level}</Badge> <Badge tone={RISK_TONE[t.risk_level]}>{t.risk_level}</Badge>
{t.reversible && <Badge>可撤销</Badge>}{t.external && <Badge tone="bg-bad/10 text-bad">外部</Badge>}</p> {t.reversible && <Badge>可撤销</Badge>}{t.external && <Badge tone="bg-bad/10 text-bad">外部</Badge>}</p>
<p className="text-[12px] text-muted">{t.description}</p> <p className="text-label text-muted">{t.description}</p>
</div> </div>
))} ))}
</div> </div>
...@@ -153,10 +153,10 @@ function EndpointEditor({ def, canEdit, onSaved, onDeleted }: { ...@@ -153,10 +153,10 @@ function EndpointEditor({ def, canEdit, onSaved, onDeleted }: {
{["POST", "PUT", "PATCH"].map((m) => <option key={m}>{m}</option>)}</select></Field> {["POST", "PUT", "PATCH"].map((m) => <option key={m}>{m}</option>)}</select></Field>
</div> </div>
<Field label="凭据请求头(JSON)" hint="加密保存、永不回显、AI 看不到。留空表示不修改"> <Field label="凭据请求头(JSON)" hint="加密保存、永不回显、AI 看不到。留空表示不修改">
<textarea className="input min-h-[60px] font-mono text-[12px]" value={secret} disabled={!canEdit} placeholder='{"Authorization": "Bearer ..."}' <textarea className="input min-h-[60px] font-mono text-label" value={secret} disabled={!canEdit} placeholder='{"Authorization": "Bearer ..."}'
onChange={(e) => setSecret(e.target.value)} /> onChange={(e) => setSecret(e.target.value)} />
</Field> </Field>
<p className="text-[12px] text-muted">外部端点只能被动作的「调用外部接口」效果使用,同样需要审批。</p> <p className="text-label text-muted">外部端点只能被动作的「调用外部接口」效果使用,同样需要审批。</p>
</div> </div>
</Card> </Card>
); );
......
...@@ -122,10 +122,10 @@ export function DocumentsPage({ onExtracted }: { onExtracted?: () => void }) { ...@@ -122,10 +122,10 @@ export function DocumentsPage({ onExtracted }: { onExtracted?: () => void }) {
<div className="flex flex-wrap items-center gap-2 border-b border-line px-4 py-2"> <div className="flex flex-wrap items-center gap-2 border-b border-line px-4 py-2">
<div className="relative w-full max-w-[16rem]"> <div className="relative w-full max-w-[16rem]">
<Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted" /> <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 pl-8 text-[12.5px]" placeholder="按文件名检索…" <input className="input h-8 pl-8 text-label" placeholder="按文件名检索…"
value={query} onChange={(e) => setQuery(e.target.value)} /> value={query} onChange={(e) => setQuery(e.target.value)} />
</div> </div>
<span className="ml-auto text-[11.5px] text-muted"> <span className="ml-auto text-label text-muted">
{filtered?.length ?? 0} 条结果 {filtered?.length ?? 0} 条结果
</span> </span>
</div> </div>
...@@ -148,7 +148,7 @@ export function DocumentsPage({ onExtracted }: { onExtracted?: () => void }) { ...@@ -148,7 +148,7 @@ export function DocumentsPage({ onExtracted }: { onExtracted?: () => void }) {
)} )}
{pageItems && pageItems.length > 0 && ( {pageItems && pageItems.length > 0 && (
<div className="overflow-x-auto"> <div className="overflow-x-auto">
<table className="w-full text-[13px]"> <table className="w-full text-body">
<thead> <thead>
<tr className="border-b border-line text-left text-xs text-muted"> <tr className="border-b border-line text-left text-xs text-muted">
<SortableTh label="文件名" sortKey="filename" active={sortKey} dir={sortDir} onSort={toggleSort} className="px-4 py-2" /> <SortableTh label="文件名" sortKey="filename" active={sortKey} dir={sortDir} onSort={toggleSort} className="px-4 py-2" />
...@@ -168,7 +168,7 @@ export function DocumentsPage({ onExtracted }: { onExtracted?: () => void }) { ...@@ -168,7 +168,7 @@ export function DocumentsPage({ onExtracted }: { onExtracted?: () => void }) {
onClick={() => setDetail(d)} title={d.filename}> onClick={() => setDetail(d)} title={d.filename}>
{d.filename} {d.filename}
</button> </button>
<span className="flex flex-wrap items-center gap-1.5 text-[11px] text-muted"> <span className="flex flex-wrap items-center gap-1.5 text-caption text-muted">
{formatBytes(d.size_bytes)} {formatBytes(d.size_bytes)}
{d.encoding && <Badge>{d.encoding}</Badge>} {d.encoding && <Badge>{d.encoding}</Badge>}
{d.parse_warning && ( {d.parse_warning && (
...@@ -181,13 +181,13 @@ export function DocumentsPage({ onExtracted }: { onExtracted?: () => void }) { ...@@ -181,13 +181,13 @@ export function DocumentsPage({ onExtracted }: { onExtracted?: () => void }) {
<td className="px-3 py-2"> <td className="px-3 py-2">
<Badge tone={STATUS_TONE[d.status]}>{STATUS_TEXT[d.status] ?? d.status}</Badge> <Badge tone={STATUS_TONE[d.status]}>{STATUS_TEXT[d.status] ?? d.status}</Badge>
{d.error && ( {d.error && (
<p className="mt-0.5 max-w-[16rem] truncate text-[11px] text-bad" title={d.error}>{d.error}</p> <p className="mt-0.5 max-w-[16rem] truncate text-caption text-bad" title={d.error}>{d.error}</p>
)} )}
</td> </td>
<td className="px-3 py-2 text-right tabular-nums">{d.chunk_count || "—"}</td> <td className="px-3 py-2 text-right tabular-nums">{d.chunk_count || "—"}</td>
<td className="px-3 py-2 text-right tabular-nums">{d.entity_count || "—"}</td> <td className="px-3 py-2 text-right tabular-nums">{d.entity_count || "—"}</td>
<td className="px-3 py-2 text-right tabular-nums">{d.relation_count || "—"}</td> <td className="px-3 py-2 text-right tabular-nums">{d.relation_count || "—"}</td>
<td className="px-3 py-2 text-[11.5px] text-muted">{formatTime(d.updated_at)}</td> <td className="px-3 py-2 text-label text-muted">{formatTime(d.updated_at)}</td>
<td className="px-4 py-2"> <td className="px-4 py-2">
<div className="flex items-center justify-end gap-1"> <div className="flex items-center justify-end gap-1">
{d.active_job ? ( {d.active_job ? (
...@@ -214,7 +214,7 @@ export function DocumentsPage({ onExtracted }: { onExtracted?: () => void }) { ...@@ -214,7 +214,7 @@ export function DocumentsPage({ onExtracted }: { onExtracted?: () => void }) {
)} )}
{filtered && filtered.length > PAGE_SIZE && ( {filtered && filtered.length > PAGE_SIZE && (
<div className="flex items-center justify-between border-t border-line px-4 py-2 text-[12.5px] text-muted"> <div className="flex items-center justify-between border-t border-line px-4 py-2 text-label text-muted">
<span>第 {pageSafe} / {pageCount} 页</span> <span>第 {pageSafe} / {pageCount} 页</span>
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<button className="btn btn-ghost btn-sm" disabled={pageSafe <= 1} onClick={() => setPage((p) => p - 1)}> <button className="btn btn-ghost btn-sm" disabled={pageSafe <= 1} onClick={() => setPage((p) => p - 1)}>
...@@ -304,7 +304,7 @@ function UploadZone({ onUploaded }: { onUploaded: (d: DocumentItem) => void }) { ...@@ -304,7 +304,7 @@ function UploadZone({ onUploaded }: { onUploaded: (d: DocumentItem) => void }) {
<div className="grid h-11 w-11 place-items-center rounded-xl bg-brand/10"> <div className="grid h-11 w-11 place-items-center rounded-xl bg-brand/10">
<Upload className="h-5 w-5 text-brand" /> <Upload className="h-5 w-5 text-brand" />
</div> </div>
<p className="text-[14px] font-medium">拖拽文件到此,或 <p className="text-body font-medium">拖拽文件到此,或
<button className="ml-1 text-brand underline underline-offset-2" <button className="ml-1 text-brand underline underline-offset-2"
onClick={() => inputRef.current?.click()}>选择文件</button> onClick={() => inputRef.current?.click()}>选择文件</button>
</p> </p>
...@@ -376,7 +376,7 @@ function JobCard({ doc, job, onClose }: { ...@@ -376,7 +376,7 @@ function JobCard({ doc, job, onClose }: {
)} )}
<div ref={logRef} <div ref={logRef}
className="max-h-56 overflow-auto rounded-lg bg-[#0f1420] p-2.5 font-mono text-[11.5px] leading-5 text-slate-300"> className="max-h-56 overflow-auto rounded-lg bg-[#0f1420] p-2.5 font-mono text-label leading-5 text-slate-300">
{job.events.map((e, i) => <LogLine key={i} ev={e} />)} {job.events.map((e, i) => <LogLine key={i} ev={e} />)}
{job.events.length === 0 && <p className="text-slate-500">等待任务开始…</p>} {job.events.length === 0 && <p className="text-slate-500">等待任务开始…</p>}
</div> </div>
...@@ -388,9 +388,9 @@ function JobCard({ doc, job, onClose }: { ...@@ -388,9 +388,9 @@ function JobCard({ doc, job, onClose }: {
function QualityStat({ label, value, hint }: { label: string; value: unknown; hint?: string }) { function QualityStat({ label, value, hint }: { label: string; value: unknown; hint?: string }) {
return ( return (
<div> <div>
<p className="text-[10.5px] uppercase tracking-wide text-muted">{label}</p> <p className="text-caption uppercase tracking-wide text-muted">{label}</p>
<p className="text-[15px] font-semibold tabular-nums">{String(value ?? "—")}</p> <p className="text-title font-semibold tabular-nums">{String(value ?? "—")}</p>
{hint && <p className="text-[10.5px] text-muted">{hint}</p>} {hint && <p className="text-caption text-muted">{hint}</p>}
</div> </div>
); );
} }
...@@ -446,7 +446,7 @@ function DocDetailModal({ doc, onClose }: { doc: DocumentItem | null; onClose: ( ...@@ -446,7 +446,7 @@ function DocDetailModal({ doc, onClose }: { doc: DocumentItem | null; onClose: (
["entities", `实体(${entities?.total ?? "…"})`], ["entities", `实体(${entities?.total ?? "…"})`],
] as const).map(([k, label]) => ( ] as const).map(([k, label]) => (
<button key={k} <button key={k}
className={cn("px-3 py-2 text-[13px]", className={cn("px-3 py-2 text-body",
tab === k ? "border-b-2 border-brand font-medium text-brand" : "text-muted")} tab === k ? "border-b-2 border-brand font-medium text-brand" : "text-muted")}
onClick={() => setTab(k)}>{label}</button> onClick={() => setTab(k)}>{label}</button>
))} ))}
...@@ -470,20 +470,20 @@ function DocDetailModal({ doc, onClose }: { doc: DocumentItem | null; onClose: ( ...@@ -470,20 +470,20 @@ function DocDetailModal({ doc, onClose }: { doc: DocumentItem | null; onClose: (
? chunks.map((c) => ( ? chunks.map((c) => (
<div key={c.id} className="rounded-lg border border-line p-2.5"> <div key={c.id} className="rounded-lg border border-line p-2.5">
<div className="mb-1 flex flex-wrap items-center gap-1.5"> <div className="mb-1 flex flex-wrap items-center gap-1.5">
<code className="rounded bg-ink/5 px-1.5 py-0.5 font-mono text-[10.5px] text-muted">{c.id}</code> <code className="rounded bg-ink/5 px-1.5 py-0.5 font-mono text-caption text-muted">{c.id}</code>
<Badge>{c.tokens} token</Badge> <Badge>{c.tokens} token</Badge>
<span className="min-w-0 truncate text-[11.5px] text-muted">{c.heading}</span> <span className="min-w-0 truncate text-label text-muted">{c.heading}</span>
</div> </div>
<p className="whitespace-pre-wrap text-[12.5px] leading-6 text-muted line-clamp-4">{c.text}</p> <p className="whitespace-pre-wrap text-label leading-6 text-muted line-clamp-4">{c.text}</p>
</div> </div>
)) ))
: <p className="py-8 text-center text-xs text-muted">尚未抽取,没有分块记录。</p>)} : <p className="py-8 text-center text-xs text-muted">尚未抽取,没有分块记录。</p>)}
{tab === "entities" && (entities?.items.length {tab === "entities" && (entities?.items.length
? entities.items.map((e) => ( ? entities.items.map((e) => (
<div key={e.id} className="flex items-center gap-2 rounded-lg border border-line px-2.5 py-1.5"> <div key={e.id} className="flex items-center gap-2 rounded-lg border border-line px-2.5 py-1.5">
<span className="min-w-0 flex-1 truncate text-[13px] font-medium">{e.label}</span> <span className="min-w-0 flex-1 truncate text-body font-medium">{e.label}</span>
<Badge>{e.type}</Badge> <Badge>{e.type}</Badge>
<span className="shrink-0 text-[11px] tabular-nums text-muted">{e.degree} 度</span> <span className="shrink-0 text-caption tabular-nums text-muted">{e.degree} 度</span>
</div> </div>
)) ))
: <p className="py-8 text-center text-xs text-muted">该文档还没有抽出实体。</p>)} : <p className="py-8 text-center text-xs text-muted">该文档还没有抽出实体。</p>)}
......
...@@ -66,7 +66,7 @@ function QaEval({ canEdit }: { canEdit: boolean }) { ...@@ -66,7 +66,7 @@ function QaEval({ canEdit }: { canEdit: boolean }) {
</>} </>}
</div> </div>
{job && job.status !== "done" && job.status !== "failed" && ( {job && job.status !== "done" && job.status !== "failed" && (
<div className="w-full"><Progress value={job.progress} /><p className="mt-1 text-[12px] text-muted">{job.message}</p></div> <div className="w-full"><Progress value={job.progress} /><p className="mt-1 text-label text-muted">{job.message}</p></div>
)} )}
</Card> </Card>
...@@ -78,11 +78,11 @@ function QaEval({ canEdit }: { canEdit: boolean }) { ...@@ -78,11 +78,11 @@ function QaEval({ canEdit }: { canEdit: boolean }) {
{runs.map((r) => ( {runs.map((r) => (
<button key={r.id} className="flex w-full items-center gap-3 px-4 py-2.5 text-left hover:bg-ink/[0.03]" <button key={r.id} className="flex w-full items-center gap-3 px-4 py-2.5 text-left hover:bg-ink/[0.03]"
onClick={() => void onto.evalRun(r.id).then(setRunSel)}> onClick={() => void onto.evalRun(r.id).then(setRunSel)}>
<span className={cn("w-14 text-[18px] font-semibold tabular-nums", r.pass_rate >= 0.7 ? "text-ok" : "text-warn")}> <span className={cn("w-14 text-section font-semibold tabular-nums", r.pass_rate >= 0.7 ? "text-ok" : "text-warn")}>
{r.status === "done" ? `${Math.round(r.pass_rate * 100)}%` : "…"}</span> {r.status === "done" ? `${Math.round(r.pass_rate * 100)}%` : "…"}</span>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="text-[13px]">{r.suite} · {r.target === "draft" ? "待发布版本" : "线上版本"}</p> <p className="text-body">{r.suite} · {r.target === "draft" ? "待发布版本" : "线上版本"}</p>
<p className="text-[11px] text-muted">{r.passed}/{r.total} 通过 · {fmtTime(r.created_at)}</p> <p className="text-caption text-muted">{r.passed}/{r.total} 通过 · {fmtTime(r.created_at)}</p>
</div> </div>
<div className="flex flex-wrap gap-1"> <div className="flex flex-wrap gap-1">
{Object.entries(r.summary?.by_kind || {}).map(([k, v]: any) => ( {Object.entries(r.summary?.by_kind || {}).map(([k, v]: any) => (
...@@ -98,8 +98,8 @@ function QaEval({ canEdit }: { canEdit: boolean }) { ...@@ -98,8 +98,8 @@ function QaEval({ canEdit }: { canEdit: boolean }) {
<div className="max-h-[520px] divide-y divide-line overflow-auto"> <div className="max-h-[520px] divide-y divide-line overflow-auto">
{cases.map((c) => ( {cases.map((c) => (
<button key={c.id} className="block w-full px-4 py-2 text-left hover:bg-ink/[0.03]" onClick={() => canEdit && setEdit(c)}> <button key={c.id} className="block w-full px-4 py-2 text-left hover:bg-ink/[0.03]" onClick={() => canEdit && setEdit(c)}>
<p className="text-[13px]"><Badge>{KIND_LABEL[c.kind]}</Badge> {c.question}</p> <p className="text-body"><Badge>{KIND_LABEL[c.kind]}</Badge> {c.question}</p>
<p className="truncate text-[11px] text-muted"> <p className="truncate text-caption text-muted">
{c.must_include.length ? `关键词:${c.must_include.join("、")} ` : ""}{c.expected_calls.length ? `期望调用:${c.expected_calls.join("、")} ` : ""} {c.must_include.length ? `关键词:${c.must_include.join("、")} ` : ""}{c.expected_calls.length ? `期望调用:${c.expected_calls.join("、")} ` : ""}
{c.expected_action ? `期望动作:${c.expected_action}` : ""}{c.source === "feedback" ? " · 来自用户纠错" : ""} {c.expected_action ? `期望动作:${c.expected_action}` : ""}{c.source === "feedback" ? " · 来自用户纠错" : ""}
</p> </p>
...@@ -114,7 +114,7 @@ function QaEval({ canEdit }: { canEdit: boolean }) { ...@@ -114,7 +114,7 @@ function QaEval({ canEdit }: { canEdit: boolean }) {
desc={`${runSel.suite} · ${runSel.target === "draft" ? "待发布版本" : "线上版本"} · 平均分 ${runSel.summary?.avg_score}`}> desc={`${runSel.suite} · ${runSel.target === "draft" ? "待发布版本" : "线上版本"} · 平均分 ${runSel.summary?.avg_score}`}>
<div className="space-y-2"> <div className="space-y-2">
{(runSel.results || []).map((r: any) => ( {(runSel.results || []).map((r: any) => (
<details key={r.case_id} className={cn("rounded-lg border p-2.5 text-[12.5px]", r.passed ? "border-line" : "border-bad/40 bg-bad/[0.03]")}> <details key={r.case_id} className={cn("rounded-lg border p-2.5 text-label", r.passed ? "border-line" : "border-bad/40 bg-bad/[0.03]")}>
<summary className="cursor-pointer"> <summary className="cursor-pointer">
<Badge tone={r.passed ? "bg-ok/10 text-ok" : "bg-bad/10 text-bad"}>{Math.round(r.score * 100)}</Badge>{" "} <Badge tone={r.passed ? "bg-ok/10 text-ok" : "bg-bad/10 text-bad"}>{Math.round(r.score * 100)}</Badge>{" "}
<Badge>{KIND_LABEL[r.kind]}</Badge> {r.question} <Badge>{KIND_LABEL[r.kind]}</Badge> {r.question}
...@@ -122,7 +122,7 @@ function QaEval({ canEdit }: { canEdit: boolean }) { ...@@ -122,7 +122,7 @@ function QaEval({ canEdit }: { canEdit: boolean }) {
<div className="mt-2 space-y-1"> <div className="mt-2 space-y-1">
<p className="text-muted">调用:{(r.calls || []).join(" → ") || "无"}</p> <p className="text-muted">调用:{(r.calls || []).join(" → ") || "无"}</p>
<pre className="max-h-48 overflow-auto whitespace-pre-wrap rounded bg-ink/5 p-2 font-sans">{r.answer || r.error}</pre> <pre className="max-h-48 overflow-auto whitespace-pre-wrap rounded bg-ink/5 p-2 font-sans">{r.answer || r.error}</pre>
<pre className="text-[11px] text-muted">{JSON.stringify(r.checks, null, 1)}</pre> <pre className="text-caption text-muted">{JSON.stringify(r.checks, null, 1)}</pre>
</div> </div>
</details> </details>
))} ))}
...@@ -174,7 +174,7 @@ function OntoEval() { ...@@ -174,7 +174,7 @@ function OntoEval() {
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<Card className="flex flex-wrap items-center gap-2 p-3"> <Card className="flex flex-wrap items-center gap-2 p-3">
<p className="text-[12.5px] text-muted">把本体(含审核队列里还没处理的提议)与人工标注的金标概念清单比对,衡量「从文档自动建本体」的效果。</p> <p className="text-label text-muted">把本体(含审核队列里还没处理的提议)与人工标注的金标概念清单比对,衡量「从文档自动建本体」的效果。</p>
{gold.map((g) => ( {gold.map((g) => (
<button key={g} className="btn btn-primary btn-sm ml-auto" disabled={busy} onClick={async () => { <button key={g} className="btn btn-primary btn-sm ml-auto" disabled={busy} onClick={async () => {
setBusy(true); setBusy(true);
...@@ -196,7 +196,7 @@ function OntoEval() { ...@@ -196,7 +196,7 @@ function OntoEval() {
<CardHeader title="按类别" /> <CardHeader title="按类别" />
<div className="space-y-1.5 p-4"> <div className="space-y-1.5 p-4">
{Object.entries(r.by_kind).map(([k, v]: any) => ( {Object.entries(r.by_kind).map(([k, v]: any) => (
<div key={k} className="flex items-center gap-2 text-[12.5px]"> <div key={k} className="flex items-center gap-2 text-label">
<span className="w-24">{k}</span><Progress value={(v.found / v.total) * 100} className="flex-1" /> <span className="w-24">{k}</span><Progress value={(v.found / v.total) * 100} className="flex-1" />
<span className="w-14 text-right tabular-nums">{v.found}/{v.total}</span> <span className="w-14 text-right tabular-nums">{v.found}/{v.total}</span>
</div> </div>
...@@ -207,7 +207,7 @@ function OntoEval() { ...@@ -207,7 +207,7 @@ function OntoEval() {
<CardHeader title="遗漏的概念" /> <CardHeader title="遗漏的概念" />
<div className="flex flex-wrap gap-1.5 p-4">{r.missing.map((m: string) => <Badge key={m} tone="bg-bad/10 text-bad">{m}</Badge>)}</div> <div className="flex flex-wrap gap-1.5 p-4">{r.missing.map((m: string) => <Badge key={m} tone="bg-bad/10 text-bad">{m}</Badge>)}</div>
<CardHeader title="匹配明细" /> <CardHeader title="匹配明细" />
<div className="max-h-72 overflow-auto p-4 text-[12px]"> <div className="max-h-72 overflow-auto p-4 text-label">
{r.details.map((d: any) => ( {r.details.map((d: any) => (
<p key={d.gold}>{d.gold} ← {d.matched} <span className={d.kind_ok ? "text-ok" : "text-warn"}>({d.kind}{d.kind_ok ? "" : `,应为 ${d.gold_kind}`})</span> <p key={d.gold}>{d.gold} ← {d.matched} <span className={d.kind_ok ? "text-ok" : "text-warn"}>({d.kind}{d.kind_ok ? "" : `,应为 ${d.gold_kind}`})</span>
<span className="text-muted"> {d.from === "review" ? "待审核" : "已入库"}</span></p> <span className="text-muted"> {d.from === "review" ? "待审核" : "已入库"}</span></p>
......
...@@ -81,7 +81,7 @@ export function DuplicatesPanel({ onMerged }: { onMerged: () => void }) { ...@@ -81,7 +81,7 @@ export function DuplicatesPanel({ onMerged }: { onMerged: () => void }) {
const [keep, drop] = p.a_degree >= p.b_degree ? [p.a, p.b] : [p.b, p.a]; const [keep, drop] = p.a_degree >= p.b_degree ? [p.a, p.b] : [p.b, p.a];
return ( return (
<div key={key} className="rounded-lg border border-line bg-elevated p-2.5"> <div key={key} className="rounded-lg border border-line bg-elevated p-2.5">
<div className="flex flex-wrap items-center gap-1.5 text-[13px]"> <div className="flex flex-wrap items-center gap-1.5 text-body">
<span className="rounded-md bg-ok/10 px-2 py-0.5 font-medium text-ok">{keep}</span> <span className="rounded-md bg-ok/10 px-2 py-0.5 font-medium text-ok">{keep}</span>
<ArrowRight className="h-3.5 w-3.5 shrink-0 text-muted" /> <ArrowRight className="h-3.5 w-3.5 shrink-0 text-muted" />
<span className="rounded-md bg-ink/5 px-2 py-0.5 text-muted line-through">{drop}</span> <span className="rounded-md bg-ink/5 px-2 py-0.5 text-muted line-through">{drop}</span>
......
...@@ -44,7 +44,7 @@ export function FilterPanel({ stats, documents, filters, onChange, communities, ...@@ -44,7 +44,7 @@ export function FilterPanel({ stats, documents, filters, onChange, communities,
const on = (set: Set<string> | null, key: string) => (set ? set.has(key) : true); const on = (set: Set<string> | null, key: string) => (set ? set.has(key) : true);
return ( return (
<div className="flex h-full flex-col gap-3 overflow-auto p-3 text-[13px]"> <div className="flex h-full flex-col gap-3 overflow-auto p-3 text-body">
<div> <div>
<div className="mb-1.5 flex items-center justify-between"> <div className="mb-1.5 flex items-center justify-between">
<span className="label mb-0">显示上限</span> <span className="label mb-0">显示上限</span>
...@@ -53,7 +53,7 @@ export function FilterPanel({ stats, documents, filters, onChange, communities, ...@@ -53,7 +53,7 @@ export function FilterPanel({ stats, documents, filters, onChange, communities,
<input type="range" min={50} max={3000} step={50} value={filters.limit} <input type="range" min={50} max={3000} step={50} value={filters.limit}
className="w-full accent-[rgb(var(--brand))]" className="w-full accent-[rgb(var(--brand))]"
onChange={(e) => onChange({ ...filters, limit: Number(e.target.value) })} /> onChange={(e) => onChange({ ...filters, limit: Number(e.target.value) })} />
<p className="mt-1 text-[11px] leading-relaxed text-muted"> <p className="mt-1 text-caption leading-relaxed text-muted">
按度数取最核心的节点。想看更外围的实体,可提高上限或用搜索直接定位后双击展开邻域。 按度数取最核心的节点。想看更外围的实体,可提高上限或用搜索直接定位后双击展开邻域。
</p> </p>
</div> </div>
...@@ -67,7 +67,7 @@ export function FilterPanel({ stats, documents, filters, onChange, communities, ...@@ -67,7 +67,7 @@ export function FilterPanel({ stats, documents, filters, onChange, communities,
className="w-full accent-[rgb(var(--brand))]" className="w-full accent-[rgb(var(--brand))]"
onChange={(e) => onChange({ ...filters, minDegree: Number(e.target.value) })} /> onChange={(e) => onChange({ ...filters, minDegree: Number(e.target.value) })} />
{stats && stats.leaf > 0 && ( {stats && stats.leaf > 0 && (
<p className="mt-1 text-[11px] text-muted"> <p className="mt-1 text-caption text-muted">
当前图里有 <b className="tabular-nums">{stats.leaf}</b> 个度=1 的叶子节点 当前图里有 <b className="tabular-nums">{stats.leaf}</b> 个度=1 的叶子节点
({(stats.leaf_ratio * 100).toFixed(0)}%),调到 ≥2 可以先看骨架。 ({(stats.leaf_ratio * 100).toFixed(0)}%),调到 ≥2 可以先看骨架。
</p> </p>
...@@ -120,14 +120,14 @@ export function FilterPanel({ stats, documents, filters, onChange, communities, ...@@ -120,14 +120,14 @@ export function FilterPanel({ stats, documents, filters, onChange, communities,
<div className="flex items-center gap-1.5"> <div className="flex items-center gap-1.5">
<i className="h-2.5 w-2.5 shrink-0 rounded-full" <i className="h-2.5 w-2.5 shrink-0 rounded-full"
style={{ background: communityColor(c.id) }} /> style={{ background: communityColor(c.id) }} />
<span className="min-w-0 flex-1 truncate text-[12.5px] font-medium">{c.title}</span> <span className="min-w-0 flex-1 truncate text-label font-medium">{c.title}</span>
<span className="shrink-0 text-[11px] tabular-nums text-muted">{c.size}</span> <span className="shrink-0 text-caption tabular-nums text-muted">{c.size}</span>
</div> </div>
{c.summary && <p className="mt-1 text-[11.5px] leading-relaxed text-muted line-clamp-3">{c.summary}</p>} {c.summary && <p className="mt-1 text-label leading-relaxed text-muted line-clamp-3">{c.summary}</p>}
</div> </div>
))} ))}
{colorBy !== "community" && ( {colorBy !== "community" && (
<p className="text-[11px] text-muted">提示:把着色切到「社区」可以在图上看出这些分组。</p> <p className="text-caption text-muted">提示:把着色切到「社区」可以在图上看出这些分组。</p>
)} )}
</div> </div>
</Section> </Section>
...@@ -142,7 +142,7 @@ function Section({ title, open, onToggle, onReset, children }: { ...@@ -142,7 +142,7 @@ function Section({ title, open, onToggle, onReset, children }: {
return ( return (
<div className="rounded-lg border border-line"> <div className="rounded-lg border border-line">
<div className="flex items-center gap-1 px-2 py-1.5"> <div className="flex items-center gap-1 px-2 py-1.5">
<button className="flex min-w-0 flex-1 items-center gap-1 text-left text-[12.5px] font-medium" <button className="flex min-w-0 flex-1 items-center gap-1 text-left text-label font-medium"
onClick={onToggle}> onClick={onToggle}>
<ChevronDown className={cn("h-3.5 w-3.5 shrink-0 transition-transform", !open && "-rotate-90")} /> <ChevronDown className={cn("h-3.5 w-3.5 shrink-0 transition-transform", !open && "-rotate-90")} />
<span className="truncate">{title}</span> <span className="truncate">{title}</span>
......
...@@ -61,7 +61,7 @@ function EndpointField({ label, value, onChange }: { ...@@ -61,7 +61,7 @@ function EndpointField({ label, value, onChange }: {
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left hover:bg-ink/5" className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left hover:bg-ink/5"
onClick={() => { onChange(h.id); setOpen(false); }}> onClick={() => { onChange(h.id); setOpen(false); }}>
<span className="h-2 w-2 shrink-0 rounded-full" style={{ background: typeColor(h.type) }} /> <span className="h-2 w-2 shrink-0 rounded-full" style={{ background: typeColor(h.type) }} />
<span className="min-w-0 flex-1 truncate text-[13px]">{h.label}</span> <span className="min-w-0 flex-1 truncate text-body">{h.label}</span>
<Pill color={typeColor(h.type)}>{h.type}</Pill> <Pill color={typeColor(h.type)}>{h.type}</Pill>
</button> </button>
))} ))}
......
...@@ -239,7 +239,7 @@ export function GraphPage() { ...@@ -239,7 +239,7 @@ export function GraphPage() {
{empty && ( {empty && (
<div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center"> <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
<Sparkles className="h-8 w-8 text-muted/50" /> <Sparkles className="h-8 w-8 text-muted/50" />
<p className="text-[14px] font-medium">当前筛选条件下没有节点</p> <p className="text-body font-medium">当前筛选条件下没有节点</p>
<p className="max-w-sm text-xs text-muted"> <p className="max-w-sm text-xs text-muted">
放宽筛选,或先到「文档」页上传并抽取一份业务文档。 放宽筛选,或先到「文档」页上传并抽取一份业务文档。
</p> </p>
...@@ -273,7 +273,7 @@ export function GraphPage() { ...@@ -273,7 +273,7 @@ export function GraphPage() {
{ key: "duplicates", label: "消歧", icon: <Merge className="h-3.5 w-3.5" /> }, { key: "duplicates", label: "消歧", icon: <Merge className="h-3.5 w-3.5" /> },
] as const).map((t) => ( ] as const).map((t) => (
<button key={t.key} <button key={t.key}
className={cn("flex flex-1 items-center justify-center gap-1.5 px-3 py-2 text-[13px] transition-colors", className={cn("flex flex-1 items-center justify-center gap-1.5 px-3 py-2 text-body transition-colors",
rightTab === t.key rightTab === t.key
? "border-b-2 border-brand font-medium text-brand" ? "border-b-2 border-brand font-medium text-brand"
: "border-b-2 border-transparent text-muted hover:text-ink")} : "border-b-2 border-transparent text-muted hover:text-ink")}
......
...@@ -88,9 +88,9 @@ export function NodeSearch({ onPick }: { onPick: (id: string) => void }) { ...@@ -88,9 +88,9 @@ export function NodeSearch({ onPick }: { onPick: (id: string) => void }) {
i === active ? "bg-brand/10" : "hover:bg-ink/5"}`} i === active ? "bg-brand/10" : "hover:bg-ink/5"}`}
> >
<span className="h-2 w-2 shrink-0 rounded-full" style={{ background: typeColor(h.type) }} /> <span className="h-2 w-2 shrink-0 rounded-full" style={{ background: typeColor(h.type) }} />
<span className="min-w-0 flex-1 truncate text-[13px]">{h.label}</span> <span className="min-w-0 flex-1 truncate text-body">{h.label}</span>
<Pill color={typeColor(h.type)}>{h.type}</Pill> <Pill color={typeColor(h.type)}>{h.type}</Pill>
<span className="shrink-0 text-[11px] tabular-nums text-muted">{h.degree} 度</span> <span className="shrink-0 text-caption tabular-nums text-muted">{h.degree} 度</span>
</button> </button>
))} ))}
</div> </div>
......
...@@ -98,7 +98,7 @@ export function PropertyPanel({ selection, entityTypes, onSelect, onExpand, onCh ...@@ -98,7 +98,7 @@ export function PropertyPanel({ selection, entityTypes, onSelect, onExpand, onCh
<div className="flex h-full flex-col overflow-auto"> <div className="flex h-full flex-col overflow-auto">
<div className="sticky top-0 z-10 border-b border-line bg-surface/95 px-3 py-2.5 backdrop-blur"> <div className="sticky top-0 z-10 border-b border-line bg-surface/95 px-3 py-2.5 backdrop-blur">
<div className="flex items-start gap-2"> <div className="flex items-start gap-2">
<h3 className="min-w-0 flex-1 break-words text-[15px] font-semibold leading-snug">{node.label}</h3> <h3 className="min-w-0 flex-1 break-words text-title font-semibold leading-snug">{node.label}</h3>
<button className="btn btn-ghost btn-sm shrink-0" onClick={() => setEditing(!editing)} <button className="btn btn-ghost btn-sm shrink-0" onClick={() => setEditing(!editing)}
title={editing ? "取消编辑" : "编辑"}> title={editing ? "取消编辑" : "编辑"}>
{editing ? <X className="h-3.5 w-3.5" /> : <Pencil className="h-3.5 w-3.5" />} {editing ? <X className="h-3.5 w-3.5" /> : <Pencil className="h-3.5 w-3.5" />}
...@@ -141,7 +141,7 @@ export function PropertyPanel({ selection, entityTypes, onSelect, onExpand, onCh ...@@ -141,7 +141,7 @@ export function PropertyPanel({ selection, entityTypes, onSelect, onExpand, onCh
</div> </div>
</div> </div>
) : ( ) : (
<p className="text-[13px] leading-relaxed"> <p className="text-body leading-relaxed">
{node.description || <span className="text-muted">(无描述)</span>} {node.description || <span className="text-muted">(无描述)</span>}
</p> </p>
)} )}
...@@ -182,12 +182,12 @@ export function PropertyPanel({ selection, entityTypes, onSelect, onExpand, onCh ...@@ -182,12 +182,12 @@ export function PropertyPanel({ selection, entityTypes, onSelect, onExpand, onCh
<div className="flex h-full flex-col overflow-auto"> <div className="flex h-full flex-col overflow-auto">
<div className="sticky top-0 z-10 border-b border-line bg-surface/95 px-3 py-2.5 backdrop-blur"> <div className="sticky top-0 z-10 border-b border-line bg-surface/95 px-3 py-2.5 backdrop-blur">
<div className="flex items-start gap-2"> <div className="flex items-start gap-2">
<h3 className="min-w-0 flex-1 text-[15px] font-semibold">关系:{edge.relation}</h3> <h3 className="min-w-0 flex-1 text-title font-semibold">关系:{edge.relation}</h3>
<button className="btn btn-ghost btn-sm shrink-0" onClick={() => setEditing(!editing)}> <button className="btn btn-ghost btn-sm shrink-0" onClick={() => setEditing(!editing)}>
{editing ? <X className="h-3.5 w-3.5" /> : <Pencil className="h-3.5 w-3.5" />} {editing ? <X className="h-3.5 w-3.5" /> : <Pencil className="h-3.5 w-3.5" />}
</button> </button>
</div> </div>
<div className="mt-1.5 flex flex-wrap items-center gap-1.5 text-[13px]"> <div className="mt-1.5 flex flex-wrap items-center gap-1.5 text-body">
<button className="rounded-md bg-brand/10 px-2 py-0.5 font-medium text-brand hover:bg-brand/20" <button className="rounded-md bg-brand/10 px-2 py-0.5 font-medium text-brand hover:bg-brand/20"
onClick={() => onSelect({ kind: "node", id: edge.source })}>{edge.source}</button> onClick={() => onSelect({ kind: "node", id: edge.source })}>{edge.source}</button>
<span className="text-warn">→</span> <span className="text-warn">→</span>
...@@ -211,7 +211,7 @@ export function PropertyPanel({ selection, entityTypes, onSelect, onExpand, onCh ...@@ -211,7 +211,7 @@ export function PropertyPanel({ selection, entityTypes, onSelect, onExpand, onCh
</div> </div>
</div> </div>
) : ( ) : (
<p className="text-[13px] leading-relaxed"> <p className="text-body leading-relaxed">
{edge.description || <span className="text-muted">(无描述)</span>} {edge.description || <span className="text-muted">(无描述)</span>}
</p> </p>
)} )}
...@@ -247,7 +247,7 @@ function EdgeList({ title, items, dir, onPick, onNode }: { ...@@ -247,7 +247,7 @@ function EdgeList({ title, items, dir, onPick, onNode }: {
return ( return (
<div key={`${other}-${e.relation}-${i}`} <div key={`${other}-${e.relation}-${i}`}
className="rounded-lg border border-line bg-elevated px-2 py-1.5"> className="rounded-lg border border-line bg-elevated px-2 py-1.5">
<div className="flex flex-wrap items-center gap-1.5 text-[12.5px]"> <div className="flex flex-wrap items-center gap-1.5 text-label">
<button className="text-muted hover:text-brand" <button className="text-muted hover:text-brand"
onClick={() => onPick(other, e.relation)}> onClick={() => onPick(other, e.relation)}>
{dir === "out" ? `—[${e.relation}]→` : `←[${e.relation}]—`} {dir === "out" ? `—[${e.relation}]→` : `←[${e.relation}]—`}
...@@ -259,7 +259,7 @@ function EdgeList({ title, items, dir, onPick, onNode }: { ...@@ -259,7 +259,7 @@ function EdgeList({ title, items, dir, onPick, onNode }: {
{e.occurrence > 1 && <Badge>{e.occurrence}×</Badge>} {e.occurrence > 1 && <Badge>{e.occurrence}×</Badge>}
</div> </div>
{e.description && ( {e.description && (
<p className="mt-0.5 text-[11.5px] leading-relaxed text-muted">{truncate(e.description, 120)}</p> <p className="mt-0.5 text-label leading-relaxed text-muted">{truncate(e.description, 120)}</p>
)} )}
</div> </div>
); );
...@@ -277,12 +277,12 @@ function EdgeList({ title, items, dir, onPick, onNode }: { ...@@ -277,12 +277,12 @@ function EdgeList({ title, items, dir, onPick, onNode }: {
function SourceCard({ s }: { s: { chunk_id: string; heading: string; snippet: string } }) { function SourceCard({ s }: { s: { chunk_id: string; heading: string; snippet: string } }) {
return ( return (
<div className="rounded-lg border border-line bg-elevated p-2"> <div className="rounded-lg border border-line bg-elevated p-2">
<p className="flex items-center gap-1 text-[11px] font-medium text-brand2"> <p className="flex items-center gap-1 text-caption font-medium text-brand2">
<FileText className="h-3 w-3 shrink-0" /> <FileText className="h-3 w-3 shrink-0" />
<span className="truncate">{shortHeading(s.heading)}</span> <span className="truncate">{shortHeading(s.heading)}</span>
<code className="ml-auto shrink-0 rounded bg-ink/5 px-1 font-mono text-[10px] text-muted">{s.chunk_id}</code> <code className="ml-auto shrink-0 rounded bg-ink/5 px-1 font-mono text-caption text-muted">{s.chunk_id}</code>
</p> </p>
<p className="mt-1 text-[11.5px] leading-relaxed text-muted">{s.snippet}</p> <p className="mt-1 text-label leading-relaxed text-muted">{s.snippet}</p>
</div> </div>
); );
} }
...@@ -46,11 +46,11 @@ export function HomePage({ me }: { me: Me | null }) { ...@@ -46,11 +46,11 @@ export function HomePage({ me }: { me: Me | null }) {
<div className="mx-auto max-w-6xl space-y-5"> <div className="mx-auto max-w-6xl space-y-5">
<Card className="overflow-hidden"> <Card className="overflow-hidden">
<div className="flex flex-wrap items-center gap-4 p-5" style={{ background: "linear-gradient(120deg, rgb(var(--brand) / 0.12), rgb(var(--brand2) / 0.05) 55%, transparent)" }}> <div className="flex flex-wrap items-center gap-4 p-5" style={{ background: "linear-gradient(120deg, rgb(var(--brand) / 0.12), rgb(var(--brand2) / 0.05) 55%, transparent)" }}>
<span className="grid h-12 w-12 place-items-center rounded-xl bg-brand text-[18px] font-bold text-white">{(cur?.display_name || "本")[0]}</span> <span className="grid h-12 w-12 place-items-center rounded-xl bg-brand text-section font-bold text-white">{(cur?.display_name || "本")[0]}</span>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="text-[11px] text-muted">当前本体</p> <p className="text-caption text-muted">当前本体</p>
<p className="text-[20px] font-semibold leading-tight">{cur?.display_name || "…"}</p> <p className="text-page font-semibold leading-tight">{cur?.display_name || "…"}</p>
<p className="mt-0.5 text-[12px] text-muted">在统一本体上完成数据集成、建模与运行时治理。<span className="font-mono">{cur?.id}</span> <p className="mt-0.5 text-label text-muted">在统一本体上完成数据集成、建模与运行时治理。<span className="font-mono">{cur?.id}</span>
{home && <> · 线上 v{home.revision}{home.dirty ? ` · ${home.dirty} 处未发布` : ""}</>}</p> {home && <> · 线上 v{home.revision}{home.dirty ? ` · ${home.dirty} 处未发布` : ""}</>}</p>
</div> </div>
{home && ( {home && (
...@@ -69,10 +69,10 @@ export function HomePage({ me }: { me: Me | null }) { ...@@ -69,10 +69,10 @@ export function HomePage({ me }: { me: Me | null }) {
<div className="grid grid-cols-2 gap-3 p-4 sm:grid-cols-5"> <div className="grid grid-cols-2 gap-3 p-4 sm:grid-cols-5">
{ASSETS.map((a) => ( {ASSETS.map((a) => (
<button key={a.key} className="rounded-xl border border-line p-3 text-left hover:border-brand/40" onClick={() => go(a.page)}> <button key={a.key} className="rounded-xl border border-line p-3 text-left hover:border-brand/40" onClick={() => go(a.page)}>
<p className="flex items-center gap-1.5 text-[12px] text-muted"><span style={{ color: a.color }}>{a.icon}</span>{a.label}</p> <p className="flex items-center gap-1.5 text-label text-muted"><span style={{ color: a.color }}>{a.icon}</span>{a.label}</p>
<p className="mt-1 text-[26px] font-semibold leading-none tabular-nums">{home ? home.counts[a.key] : "-"}</p> <p className="mt-1 text-[26px] font-semibold leading-none tabular-nums">{home ? home.counts[a.key] : "-"}</p>
{a.key === "object_type" && home && home.mapped.object_unmapped > 0 && ( {a.key === "object_type" && home && home.mapped.object_unmapped > 0 && (
<p className="mt-1 text-[11px] text-warn">{home.mapped.object_unmapped} 个未映射</p>)} <p className="mt-1 text-caption text-warn">{home.mapped.object_unmapped} 个未映射</p>)}
</button> </button>
))} ))}
</div> </div>
...@@ -83,8 +83,8 @@ export function HomePage({ me }: { me: Me | null }) { ...@@ -83,8 +83,8 @@ export function HomePage({ me }: { me: Me | null }) {
{CAPS.map((c) => ( {CAPS.map((c) => (
<button key={c.page + c.title} className="flex items-start gap-2.5 rounded-xl border border-line p-3 text-left hover:border-brand/40" onClick={() => go(c.page)}> <button key={c.page + c.title} className="flex items-start gap-2.5 rounded-xl border border-line p-3 text-left hover:border-brand/40" onClick={() => go(c.page)}>
<span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-brand/10 text-brand">{c.icon}</span> <span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-brand/10 text-brand">{c.icon}</span>
<span className="min-w-0"><span className="flex items-center gap-1.5 text-[13px] font-semibold">{c.title}<Badge>{c.tag}</Badge></span> <span className="min-w-0"><span className="flex items-center gap-1.5 text-body font-semibold">{c.title}<Badge>{c.tag}</Badge></span>
<span className="text-[11.5px] text-muted">{c.desc}</span></span> <span className="text-label text-muted">{c.desc}</span></span>
</button> </button>
))} ))}
</div> </div>
...@@ -96,7 +96,7 @@ export function HomePage({ me }: { me: Me | null }) { ...@@ -96,7 +96,7 @@ export function HomePage({ me }: { me: Me | null }) {
<div className="grid grid-cols-3 gap-2 p-4"> <div className="grid grid-cols-3 gap-2 p-4">
{[{ p: "data", l: "数据连接", i: <Database className="h-5 w-5" /> }, { p: "modeling", l: "业务建模", i: <Wand2 className="h-5 w-5" /> }, {[{ p: "data", l: "数据连接", i: <Database className="h-5 w-5" /> }, { p: "modeling", l: "业务建模", i: <Wand2 className="h-5 w-5" /> },
{ p: "documents", l: "知识库", i: <FileText className="h-5 w-5" /> }].map((x) => ( { p: "documents", l: "知识库", i: <FileText className="h-5 w-5" /> }].map((x) => (
<button key={x.p} className="flex flex-col items-center gap-1.5 rounded-xl p-2 text-[12px] hover:bg-ink/[0.03]" onClick={() => go(x.p)}> <button key={x.p} className="flex flex-col items-center gap-1.5 rounded-xl p-2 text-label hover:bg-ink/[0.03]" onClick={() => go(x.p)}>
<span className="grid h-10 w-10 place-items-center rounded-xl bg-brand text-white">{x.i}</span>{x.l}</button> <span className="grid h-10 w-10 place-items-center rounded-xl bg-brand text-white">{x.i}</span>{x.l}</button>
))} ))}
</div> </div>
...@@ -106,18 +106,18 @@ export function HomePage({ me }: { me: Me | null }) { ...@@ -106,18 +106,18 @@ export function HomePage({ me }: { me: Me | null }) {
<div className="space-y-1 p-3"> <div className="space-y-1 p-3">
{!home ? <Spinner /> : home.next_steps.length ? home.next_steps.map((s, i) => ( {!home ? <Spinner /> : home.next_steps.length ? home.next_steps.map((s, i) => (
<button key={i} className="flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left hover:bg-ink/[0.03]" onClick={() => go(s.key)}> <button key={i} className="flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left hover:bg-ink/[0.03]" onClick={() => go(s.key)}>
<span className="mt-0.5 grid h-5 w-5 shrink-0 place-items-center rounded-full bg-brand/10 text-[11px] font-semibold text-brand">{i + 1}</span> <span className="mt-0.5 grid h-5 w-5 shrink-0 place-items-center rounded-full bg-brand/10 text-caption font-semibold text-brand">{i + 1}</span>
<span className="min-w-0"><span className="block text-[12.5px] font-medium">{s.title}</span><span className="block text-[11px] text-muted">{s.hint}</span></span> <span className="min-w-0"><span className="block text-label font-medium">{s.title}</span><span className="block text-caption text-muted">{s.hint}</span></span>
</button> </button>
)) : <p className="px-2 py-3 text-[12px] text-muted">一切就绪。可以去「提问」,或在「运行监控 → MCP 接入」把本体接给你的 AI 助手。</p>} )) : <p className="px-2 py-3 text-label text-muted">一切就绪。可以去「提问」,或在「运行监控 → MCP 接入」把本体接给你的 AI 助手。</p>}
</div> </div>
</Card> </Card>
<Card className="grid grid-cols-2 gap-3 p-4 text-[12px]"> <Card className="grid grid-cols-2 gap-3 p-4 text-label">
<button className="text-left" onClick={() => go("inbox")}><p className="text-muted">待审批动作</p><p className="text-[20px] font-semibold">{home?.pending_approvals ?? "-"}</p></button> <button className="text-left" onClick={() => go("inbox")}><p className="text-muted">待审批动作</p><p className="text-page font-semibold">{home?.pending_approvals ?? "-"}</p></button>
<button className="text-left" onClick={() => go("modeling")}><p className="text-muted">待审核草案</p><p className="text-[20px] font-semibold">{home?.pending_reviews ?? "-"}</p></button> <button className="text-left" onClick={() => go("modeling")}><p className="text-muted">待审核草案</p><p className="text-page font-semibold">{home?.pending_reviews ?? "-"}</p></button>
<button className="text-left" onClick={() => go("data")}><p className="text-muted">数据连接</p><p className="text-[20px] font-semibold">{home?.datasources ?? "-"}</p></button> <button className="text-left" onClick={() => go("data")}><p className="text-muted">数据连接</p><p className="text-page font-semibold">{home?.datasources ?? "-"}</p></button>
<button className="text-left" onClick={() => go("pipeline")}><p className="text-muted">数据管道</p><p className="text-[20px] font-semibold">{home?.pipelines.total ?? "-"}</p> <button className="text-left" onClick={() => go("pipeline")}><p className="text-muted">数据管道</p><p className="text-page font-semibold">{home?.pipelines.total ?? "-"}</p>
<p className="text-[10.5px] text-muted">{home?.pipelines.last_run_at ? `同步于 ${fmtTime(home.pipelines.last_run_at)}` : "未同步"}</p></button> <p className="text-caption text-muted">{home?.pipelines.last_run_at ? `同步于 ${fmtTime(home.pipelines.last_run_at)}` : "未同步"}</p></button>
</Card> </Card>
</div> </div>
</div> </div>
...@@ -131,15 +131,15 @@ export function HomePage({ me }: { me: Me | null }) { ...@@ -131,15 +131,15 @@ export function HomePage({ me }: { me: Me | null }) {
<button key={w.id} onClick={() => { if (!w.current) { setCurrentWorkspace(w.id); toast("ok", `已切换到「${w.display_name}」`); } }} <button key={w.id} onClick={() => { if (!w.current) { setCurrentWorkspace(w.id); toast("ok", `已切换到「${w.display_name}」`); } }}
className={cn("rounded-xl border p-3 text-left transition-colors", w.current ? "border-brand bg-brand/5" : "border-line hover:border-brand/40")}> className={cn("rounded-xl border p-3 text-left transition-colors", w.current ? "border-brand bg-brand/5" : "border-line hover:border-brand/40")}>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="grid h-7 w-7 place-items-center rounded-lg bg-brand/15 text-[12px] font-bold text-brand">{w.display_name[0]}</span> <span className="grid h-7 w-7 place-items-center rounded-lg bg-brand/15 text-label font-bold text-brand">{w.display_name[0]}</span>
<span className="min-w-0 flex-1 truncate text-[13.5px] font-semibold">{w.display_name}</span> <span className="min-w-0 flex-1 truncate text-body font-semibold">{w.display_name}</span>
{w.current ? <Badge tone="bg-brand/10 text-brand">当前</Badge> : <Badge tone="bg-ok/10 text-ok">可切换</Badge>} {w.current ? <Badge tone="bg-brand/10 text-brand">当前</Badge> : <Badge tone="bg-ok/10 text-ok">可切换</Badge>}
</div> </div>
<p className="mt-1 line-clamp-1 min-h-[1.4em] text-[11.5px] text-muted">{w.description || w.industry || "(无描述)"}</p> <p className="mt-1 line-clamp-1 min-h-[1.4em] text-label text-muted">{w.description || w.industry || "(无描述)"}</p>
<div className="mt-3 grid grid-cols-5 text-center"> <div className="mt-3 grid grid-cols-5 text-center">
{ASSETS.map((a) => <div key={a.key}><p className="text-[16px] font-semibold tabular-nums">{w.counts[a.key]}</p><p className="text-[10.5px] text-muted">{a.label.replace("类型", "")}</p></div>)} {ASSETS.map((a) => <div key={a.key}><p className="text-section font-semibold tabular-nums">{w.counts[a.key]}</p><p className="text-caption text-muted">{a.label.replace("类型", "")}</p></div>)}
</div> </div>
<p className="mt-2 font-mono text-[10.5px] text-muted">{w.id}</p> <p className="mt-2 font-mono text-caption text-muted">{w.id}</p>
</button> </button>
))} ))}
</div> </div>
......
...@@ -102,7 +102,7 @@ export function BindingEditor({ concept, canEdit, onChanged }: { concept: Concep ...@@ -102,7 +102,7 @@ export function BindingEditor({ concept, canEdit, onChanged }: { concept: Concep
<div className="grid gap-1.5 sm:grid-cols-2"> <div className="grid gap-1.5 sm:grid-cols-2">
{props.map((p) => ( {props.map((p) => (
<div key={p} className="flex items-center gap-2"> <div key={p} className="flex items-center gap-2">
<span className="w-24 shrink-0 truncate text-[12.5px]">{p}</span> <span className="w-24 shrink-0 truncate text-label">{p}</span>
<select className="input h-8" value={ref.columns?.[p] || ""} disabled={!canEdit} <select className="input h-8" value={ref.columns?.[p] || ""} disabled={!canEdit}
onChange={(e) => setRef({ ...ref, columns: { ...(ref.columns || {}), [p]: e.target.value } })}> onChange={(e) => setRef({ ...ref, columns: { ...(ref.columns || {}), [p]: e.target.value } })}>
<option value="">(不映射)</option> <option value="">(不映射)</option>
...@@ -110,7 +110,7 @@ export function BindingEditor({ concept, canEdit, onChanged }: { concept: Concep ...@@ -110,7 +110,7 @@ export function BindingEditor({ concept, canEdit, onChanged }: { concept: Concep
</select> </select>
</div> </div>
))} ))}
{!props.length && <p className="text-[12px] text-muted">先在上方定义属性</p>} {!props.length && <p className="text-label text-muted">先在上方定义属性</p>}
</div> </div>
</Field> </Field>
</> </>
...@@ -127,7 +127,7 @@ export function BindingEditor({ concept, canEdit, onChanged }: { concept: Concep ...@@ -127,7 +127,7 @@ export function BindingEditor({ concept, canEdit, onChanged }: { concept: Concep
{colSelect("object_key_column", "对象键列", "按单个对象取值用")} {colSelect("object_key_column", "对象键列", "按单个对象取值用")}
</div> </div>
<Field label="固定过滤条件(每行一条 SQL 条件)"> <Field label="固定过滤条件(每行一条 SQL 条件)">
<textarea className="input min-h-[48px] font-mono text-[12px]" value={(ref.filters || []).join("\n")} disabled={!canEdit} <textarea className="input min-h-[48px] font-mono text-label" value={(ref.filters || []).join("\n")} disabled={!canEdit}
onChange={(e) => setRef({ ...ref, filters: e.target.value.split("\n").filter((x) => x.trim()) })} /> onChange={(e) => setRef({ ...ref, filters: e.target.value.split("\n").filter((x) => x.trim()) })} />
</Field> </Field>
<Field label="可拆分维度(维度名 → 列)"> <Field label="可拆分维度(维度名 → 列)">
...@@ -174,7 +174,7 @@ export function BindingEditor({ concept, canEdit, onChanged }: { concept: Concep ...@@ -174,7 +174,7 @@ export function BindingEditor({ concept, canEdit, onChanged }: { concept: Concep
</div> </div>
{test && ( {test && (
<div className="space-y-2"> <div className="space-y-2">
{test.sql && <pre className="rounded bg-ink/5 p-2 font-mono text-[11px]">{test.sql}</pre>} {test.sql && <pre className="rounded bg-ink/5 p-2 font-mono text-caption">{test.sql}</pre>}
<DataTable columns={test.columns} rows={test.rows} max={20} /> <DataTable columns={test.columns} rows={test.rows} max={20} />
</div> </div>
)} )}
......
...@@ -4,7 +4,7 @@ import { Badge, Card, CardHeader, CopyButton, Empty, Spinner } from "@/component ...@@ -4,7 +4,7 @@ import { Badge, Card, CardHeader, CopyButton, Empty, Spinner } from "@/component
import { go } from "@/lib/nav"; import { go } from "@/lib/nav";
import { errText, fmtTime, onto, type AuditRec, type McpTool } from "@/lib/onto"; import { errText, fmtTime, onto, type AuditRec, type McpTool } from "@/lib/onto";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { ResultView, SchemaForm } from "./common"; import { ResultView, SchemaForm } from "@/features/ontology/common";
/** /**
* MCP 服务:已发布的本体以 MCP 工具暴露给外部 Agent。 * MCP 服务:已发布的本体以 MCP 工具暴露给外部 Agent。
...@@ -40,12 +40,12 @@ export function McpPage() { ...@@ -40,12 +40,12 @@ export function McpPage() {
<Card className="flex flex-wrap items-center gap-3 p-4" style={{ background: "linear-gradient(120deg, rgb(var(--brand) / 0.07), transparent 60%)" }}> <Card className="flex flex-wrap items-center gap-3 p-4" style={{ background: "linear-gradient(120deg, rgb(var(--brand) / 0.07), transparent 60%)" }}>
<Bot className="h-8 w-8 text-brand" /> <Bot className="h-8 w-8 text-brand" />
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="text-[15px] font-semibold">MCP 服务 · {info.tools.length} 个工具</p> <p className="text-title font-semibold">MCP 服务 · {info.tools.length} 个工具</p>
<p className="text-[12px] text-muted">工具目录 · 在线调用 · 调用日志。协议 {info.protocol},外部 Agent 按 <code>X-User-Id</code> 代表的用户身份与数据范围调用;动作只能提议、不能审批。</p> <p className="text-label text-muted">工具目录 · 在线调用 · 调用日志。协议 {info.protocol},外部 Agent 按 <code>X-User-Id</code> 代表的用户身份与数据范围调用;动作只能提议、不能审批。</p>
</div> </div>
{info.enabled ? <Badge tone="bg-ok/10 text-ok"><ShieldCheck className="h-3 w-3" />已开启</Badge> {info.enabled ? <Badge tone="bg-ok/10 text-ok"><ShieldCheck className="h-3 w-3" />已开启</Badge>
: <button className="btn btn-sm" onClick={() => go("settings")}>未开启:在设置页配置 MCP_TOKEN</button>} : <button className="btn btn-sm" onClick={() => go("settings")}>未开启:在设置页配置 MCP_TOKEN</button>}
<div className="flex items-center gap-1 rounded-md border border-line bg-surface px-2 py-1 text-[12px]"> <div className="flex items-center gap-1 rounded-md border border-line bg-surface px-2 py-1 text-label">
<code>{url}</code><CopyButton text={url} label="" /> <code>{url}</code><CopyButton text={url} label="" />
</div> </div>
</Card> </Card>
...@@ -60,12 +60,12 @@ export function McpPage() { ...@@ -60,12 +60,12 @@ export function McpPage() {
{tools.map((t, i) => ( {tools.map((t, i) => (
<div key={t.name}> <div key={t.name}>
{(i === 0 || tools[i - 1].annotations?.group !== t.annotations?.group) && ( {(i === 0 || tools[i - 1].annotations?.group !== t.annotations?.group) && (
<p className="bg-ink/[0.03] px-3 py-1 text-[11px] font-medium text-muted">{t.annotations?.group || "其他"}</p> <p className="bg-ink/[0.03] px-3 py-1 text-caption font-medium text-muted">{t.annotations?.group || "其他"}</p>
)} )}
<button onClick={() => { setSel(t.name); setArgs({}); setOut(null); }} <button onClick={() => { setSel(t.name); setArgs({}); setOut(null); }}
className={cn("block w-full border-b border-line/60 px-3 py-2 text-left hover:bg-ink/[0.03]", sel === t.name && "bg-brand/5")}> className={cn("block w-full border-b border-line/60 px-3 py-2 text-left hover:bg-ink/[0.03]", sel === t.name && "bg-brand/5")}>
<p className="font-mono text-[12.5px] font-medium">{t.name}</p> <p className="font-mono text-label font-medium">{t.name}</p>
<p className="line-clamp-2 text-[11.5px] text-muted">{t.description}</p> <p className="line-clamp-2 text-label text-muted">{t.description}</p>
</button> </button>
</div> </div>
))} ))}
...@@ -79,11 +79,11 @@ export function McpPage() { ...@@ -79,11 +79,11 @@ export function McpPage() {
{busy ? <Spinner className="h-3.5 w-3.5" /> : <Play className="h-3.5 w-3.5" />}在线调用</button>} /> {busy ? <Spinner className="h-3.5 w-3.5" /> : <Play className="h-3.5 w-3.5" />}在线调用</button>} />
<div className="min-h-0 flex-1 space-y-3 overflow-auto p-4"> <div className="min-h-0 flex-1 space-y-3 overflow-auto p-4">
<SchemaForm key={tool.name} schema={tool.inputSchema} value={args} onChange={setArgs} compact /> <SchemaForm key={tool.name} schema={tool.inputSchema} value={args} onChange={setArgs} compact />
{tool.name === "propose_action" && <p className="rounded bg-warn/10 px-2 py-1.5 text-[12px] text-warn">提议只会生成一张待审批单,不会执行。</p>} {tool.name === "propose_action" && <p className="rounded bg-warn/10 px-2 py-1.5 text-label text-warn">提议只会生成一张待审批单,不会执行。</p>}
{out && <div className="border-t border-line pt-3"><ResultView data={out} /></div>} {out && <div className="border-t border-line pt-3"><ResultView data={out} /></div>}
<details> <details>
<summary className="cursor-pointer text-[11.5px] text-muted">inputSchema</summary> <summary className="cursor-pointer text-label text-muted">inputSchema</summary>
<pre className="mt-1 max-h-56 overflow-auto rounded bg-ink/5 p-2 text-[11px]">{JSON.stringify(tool.inputSchema, null, 2)}</pre> <pre className="mt-1 max-h-56 overflow-auto rounded bg-ink/5 p-2 text-caption">{JSON.stringify(tool.inputSchema, null, 2)}</pre>
</details> </details>
</div> </div>
</>} </>}
...@@ -92,15 +92,15 @@ export function McpPage() { ...@@ -92,15 +92,15 @@ export function McpPage() {
<Card className="flex min-h-0 flex-col"> <Card className="flex min-h-0 flex-col">
<CardHeader title={`调用日志(最近 ${logs.length})`} right={<button className="btn btn-ghost btn-sm" onClick={loadLogs}><RefreshCw className="h-3.5 w-3.5" /></button>} /> <CardHeader title={`调用日志(最近 ${logs.length})`} right={<button className="btn btn-ghost btn-sm" onClick={loadLogs}><RefreshCw className="h-3.5 w-3.5" /></button>} />
<div className="min-h-0 flex-1 overflow-auto"> <div className="min-h-0 flex-1 overflow-auto">
{!logs.length && <p className="p-3 text-[12px] text-muted">暂无调用</p>} {!logs.length && <p className="p-3 text-label text-muted">暂无调用</p>}
{logs.map((l) => ( {logs.map((l) => (
<div key={l.id} className="border-b border-line/60 px-3 py-2 text-[12px]"> <div key={l.id} className="border-b border-line/60 px-3 py-2 text-label">
<p className="flex items-center gap-1.5"> <p className="flex items-center gap-1.5">
<i className={cn("h-1.5 w-1.5 rounded-full", l.summary.includes("失败") ? "bg-bad" : "bg-ok")} /> <i className={cn("h-1.5 w-1.5 rounded-full", l.summary.includes("失败") ? "bg-bad" : "bg-ok")} />
<code className="font-medium">{l.target_id}</code> <code className="font-medium">{l.target_id}</code>
<span className="ml-auto text-[11px] text-muted">{fmtTime(l.ts)}</span> <span className="ml-auto text-caption text-muted">{fmtTime(l.ts)}</span>
</p> </p>
<p className="truncate text-[11px] text-muted">{l.actor_name || l.actor_id} · {l.summary.replace(/^MCP (调用失败|调用) \S+/, "").trim()}</p> <p className="truncate text-caption text-muted">{l.actor_name || l.actor_id} · {l.summary.replace(/^MCP (调用失败|调用) \S+/, "").trim()}</p>
</div> </div>
))} ))}
</div> </div>
......
...@@ -36,7 +36,7 @@ export function MembersPage({ me }: { me: Me | null }) { ...@@ -36,7 +36,7 @@ export function MembersPage({ me }: { me: Me | null }) {
<div className="divide-y divide-line"> <div className="divide-y divide-line">
{users.map((u) => ( {users.map((u) => (
<button key={u.id} className="flex w-full flex-wrap items-center gap-2 px-4 py-2.5 text-left hover:bg-ink/[0.03]" disabled={!isAdmin} onClick={() => setEdit(u)}> <button key={u.id} className="flex w-full flex-wrap items-center gap-2 px-4 py-2.5 text-left hover:bg-ink/[0.03]" disabled={!isAdmin} onClick={() => setEdit(u)}>
<span className="w-28 font-medium">{u.name}</span><code className="w-24 text-[11px] text-muted">{u.id}</code> <span className="w-28 font-medium">{u.name}</span><code className="w-24 text-caption text-muted">{u.id}</code>
{u.roles.map((r) => <Badge key={r} tone="bg-brand/10 text-brand">{ROLE_LABEL[r] || r}</Badge>)} {u.roles.map((r) => <Badge key={r} tone="bg-brand/10 text-brand">{ROLE_LABEL[r] || r}</Badge>)}
{u.biz_roles.map((r) => <Badge key={r} tone="bg-ok/10 text-ok">{r}</Badge>)} {u.biz_roles.map((r) => <Badge key={r} tone="bg-ok/10 text-ok">{r}</Badge>)}
{Object.keys(u.scope || {}).length > 0 && <Badge tone="bg-warn/10 text-warn">有数据范围</Badge>} {Object.keys(u.scope || {}).length > 0 && <Badge tone="bg-warn/10 text-warn">有数据范围</Badge>}
...@@ -54,9 +54,9 @@ export function MembersPage({ me }: { me: Me | null }) { ...@@ -54,9 +54,9 @@ export function MembersPage({ me }: { me: Me | null }) {
{roles.map((r) => ( {roles.map((r) => (
<div key={r.id} className="flex items-start gap-2 px-4 py-2.5"> <div key={r.id} className="flex items-start gap-2 px-4 py-2.5">
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="text-[13px] font-medium">{r.name}</p> <p className="text-body font-medium">{r.name}</p>
{r.description && <p className="text-[12px] text-muted">{r.description}</p>} {r.description && <p className="text-label text-muted">{r.description}</p>}
<p className="text-[11px] text-muted">{r.members.length ? `成员:${r.members.join("、")}` : "还没有成员"}</p> <p className="text-caption text-muted">{r.members.length ? `成员:${r.members.join("、")}` : "还没有成员"}</p>
</div> </div>
{isAdmin && <button className="btn btn-ghost btn-sm" onClick={async () => { {isAdmin && <button className="btn btn-ghost btn-sm" onClick={async () => {
if (!(await confirmDialog(`删除业务角色「${r.name}」?`, { desc: "已引用它的动作与流程卡需要改成别的角色", danger: true }))) return; if (!(await confirmDialog(`删除业务角色「${r.name}」?`, { desc: "已引用它的动作与流程卡需要改成别的角色", danger: true }))) return;
...@@ -111,13 +111,13 @@ function UserModal({ u, roles: bizRoles, onClose, onDone }: { u: UserRec; roles: ...@@ -111,13 +111,13 @@ function UserModal({ u, roles: bizRoles, onClose, onDone }: { u: UserRec; roles:
{bizRoles.map((r) => ( {bizRoles.map((r) => (
<label key={r.id} className="chip cursor-pointer"><input type="checkbox" checked={v.biz_roles.includes(r.name)} onChange={() => setV({ ...v, biz_roles: toggle(v.biz_roles, r.name) })} />{r.name}</label> <label key={r.id} className="chip cursor-pointer"><input type="checkbox" checked={v.biz_roles.includes(r.name)} onChange={() => setV({ ...v, biz_roles: toggle(v.biz_roles, r.name) })} />{r.name}</label>
))} ))}
{!bizRoles.length && <span className="text-[12px] text-muted">还没有业务角色,在右侧添加</span>} {!bizRoles.length && <span className="text-label text-muted">还没有业务角色,在右侧添加</span>}
</div> </div>
</Field> </Field>
<Field label="数据范围(JSON)" hint={`格式:{"对象id": {"属性": ["允许的值"]}}。对象:${types.map((t) => `${t.name}=${t.id}`).join(",")}`}> <Field label="数据范围(JSON)" hint={`格式:{"对象id": {"属性": ["允许的值"]}}。对象:${types.map((t) => `${t.name}=${t.id}`).join(",")}`}>
<textarea className="input min-h-[70px] font-mono text-[12px]" value={scope} onChange={(e) => setScope(e.target.value)} /> <textarea className="input min-h-[70px] font-mono text-label" value={scope} onChange={(e) => setScope(e.target.value)} />
</Field> </Field>
<label className="flex items-center gap-2 text-[13px]"><input type="checkbox" checked={v.enabled} onChange={(e) => setV({ ...v, enabled: e.target.checked })} />启用</label> <label className="flex items-center gap-2 text-body"><input type="checkbox" checked={v.enabled} onChange={(e) => setV({ ...v, enabled: e.target.checked })} />启用</label>
</div> </div>
</Modal> </Modal>
); );
......
import { Activity, ScrollText } from "lucide-react";
import { Segmented } from "@/components/ui";
import { AuditPage } from "@/features/audit/AuditPage";
import { OverviewPage } from "@/features/runtime/OverviewPage";
import { go, useHashParams } from "@/lib/nav";
type Tab = "overview" | "audit";
/**
* 运行监控:本体上线后「跑得怎么样」都在这一页。
* MCP 服务是独立的一级菜单(外部 Agent 接入是一件独立的事,不该埋在监控的页签里)。
*/
export function MonitorPage() {
const hp = useHashParams();
const raw = hp.get("tab");
const tab: Tab = raw === "audit" ? "audit" : "overview";
return (
<div className="flex h-full min-h-0 flex-col gap-3">
<Segmented value={tab} onChange={(t) => go("monitor", { tab: t })} options={[
{ key: "overview", label: <><Activity className="h-3.5 w-3.5" />运行总览</> },
{ key: "audit", label: <><ScrollText className="h-3.5 w-3.5" />审计与成本</> },
]} />
<div className="min-h-0 flex-1 overflow-auto">
{tab === "overview" && <OverviewPage />}
{tab === "audit" && <AuditPage />}
</div>
</div>
);
}
...@@ -40,9 +40,12 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null } ...@@ -40,9 +40,12 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null }
const [sel, setSel] = useState(params.get("id") || ""); const [sel, setSel] = useState(params.get("id") || "");
const [modal, setModal] = useState<"" | "new" | "draft">(""); const [modal, setModal] = useState<"" | "new" | "draft">("");
// 选「已废弃」时单独去拉:后端默认把废弃的排除在外,前端以前又没这个筛选,
// 废弃一块积木之后就彻底找不到了(其实一直都在库里)。
const load = useCallback(() => { const load = useCallback(() => {
void onto.concepts({}).then(setAll).catch((e) => toast("error", "加载失败", errText(e))); void onto.concepts(status === "deprecated" ? { status: "deprecated" } : {})
}, []); .then(setAll).catch((e) => toast("error", "加载失败", errText(e)));
}, [status]);
useEffect(() => { void onto.kernelMeta().then(setMeta); }, []); useEffect(() => { void onto.kernelMeta().then(setMeta); }, []);
useEffect(load, [load]); useEffect(load, [load]);
useEffect(() => { setSel(params.get("id") || ""); }, [params]); useEffect(() => { setSel(params.get("id") || ""); }, [params]);
...@@ -55,7 +58,7 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null } ...@@ -55,7 +58,7 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null }
&& (!domain || (domain === "-" ? !c.domain : c.domain === domain)) && (!domain || (domain === "-" ? !c.domain : c.domain === domain))
&& (!mapped || (mapped === "yes" ? c.mapped === true : c.mapped === false)) && (!mapped || (mapped === "yes" ? c.mapped === true : c.mapped === false))
&& (!obj || c.object_type === obj || objName[c.object_type] === objName[obj]) && (!obj || c.object_type === obj || objName[c.object_type] === objName[obj])
&& (!status || (status === "dirty" ? c.dirty && c.published : c.status === status)) && (!status || status === "deprecated" || (status === "dirty" ? c.dirty && c.published : c.status === status))
&& (!q || [c.name, c.display_name, c.description, ...c.synonyms].some((s) => s?.includes(q)))), && (!q || [c.name, c.display_name, c.description, ...c.synonyms].some((s) => s?.includes(q)))),
[mine, cat, domain, mapped, obj, status, q, objName]); [mine, cat, domain, mapped, obj, status, q, objName]);
const mappedCount = mine.filter((c) => c.mapped === true).length; const mappedCount = mine.filter((c) => c.mapped === true).length;
...@@ -70,14 +73,14 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null } ...@@ -70,14 +73,14 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null }
<Card className="p-4" style={{ background: "linear-gradient(120deg, rgb(var(--brand) / 0.07), transparent 60%)" }}> <Card className="p-4" style={{ background: "linear-gradient(120deg, rgb(var(--brand) / 0.07), transparent 60%)" }}>
<div className="flex flex-wrap items-center gap-3"> <div className="flex flex-wrap items-center gap-3">
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="text-[16px] font-semibold">{info.title} · {items.length}/{mine.length}</p> <p className="text-section font-semibold">{info.title} · {items.length}/{mine.length}</p>
<p className="mt-0.5 max-w-3xl text-[12px] text-muted">{info.desc}</p> <p className="mt-0.5 max-w-3xl text-label text-muted">{info.desc}</p>
</div> </div>
{mappable && ( {mappable && (
<div className="flex gap-4 text-[12px]"> <div className="flex gap-4 text-label">
<button onClick={() => setMapped("")}><b className="text-[18px] tabular-nums">{mine.length}</b> 全部</button> <button onClick={() => setMapped("")}><b className="text-section tabular-nums">{mine.length}</b> 全部</button>
<button onClick={() => setMapped("yes")} className="text-ok"><b className="text-[18px] tabular-nums">{mappedCount}</b> 已映射</button> <button onClick={() => setMapped("yes")} className="text-ok"><b className="text-section tabular-nums">{mappedCount}</b> 已映射</button>
<button onClick={() => setMapped("no")} className={unmappedCount ? "text-warn" : "text-muted"}><b className="text-[18px] tabular-nums">{unmappedCount}</b> 未映射</button> <button onClick={() => setMapped("no")} className={unmappedCount ? "text-warn" : "text-muted"}><b className="text-section tabular-nums">{unmappedCount}</b> 未映射</button>
</div> </div>
)} )}
{canEdit && (kind === "function" || kind === "action") && ( {canEdit && (kind === "function" || kind === "action") && (
...@@ -116,7 +119,7 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null } ...@@ -116,7 +119,7 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null }
)} )}
<select className="input h-8 w-32" value={status} onChange={(e) => setStatus(e.target.value)}> <select className="input h-8 w-32" value={status} onChange={(e) => setStatus(e.target.value)}>
<option value="">全部状态</option><option value="draft">草稿</option><option value="published">已发布</option> <option value="">全部状态</option><option value="draft">草稿</option><option value="published">已发布</option>
<option value="dirty">有未发布修改</option> <option value="dirty">有未发布修改</option><option value="deprecated">已废弃</option>
</select> </select>
{kind === "object_type" && ( {kind === "object_type" && (
<Segmented className="ml-auto" value={view} onChange={setView} options={[ <Segmented className="ml-auto" value={view} onChange={setView} options={[
...@@ -129,8 +132,8 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null } ...@@ -129,8 +132,8 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null }
<Card className="min-h-0 flex-1 overflow-auto"> <Card className="min-h-0 flex-1 overflow-auto">
{!items.length ? <Empty icon={<Sparkles className="h-10 w-10" />} title={`还没有${info.title}`} desc={info.empty} /> {!items.length ? <Empty icon={<Sparkles className="h-10 w-10" />} title={`还没有${info.title}`} desc={info.empty} />
: view === "cards" ? <ObjectCards items={items} sel={sel} onOpen={open} /> : ( : view === "cards" ? <ObjectCards items={items} sel={sel} onOpen={open} /> : (
<table className="w-full text-[12.5px]"> <table className="w-full text-label">
<thead className="sticky top-0 z-10 bg-surface text-[11.5px] text-muted"> <thead className="sticky top-0 z-10 bg-surface text-label text-muted">
<tr className="border-b border-line"> <tr className="border-b border-line">
<th className="px-3 py-2 text-left">名称</th> <th className="px-3 py-2 text-left">名称</th>
{kind === "function" && <th className="px-2 text-left">类别</th>} {kind === "function" && <th className="px-2 text-left">类别</th>}
...@@ -150,9 +153,9 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null } ...@@ -150,9 +153,9 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null }
<td className="px-3 py-2"> <td className="px-3 py-2">
<p className="flex items-center gap-1.5 font-medium"> <p className="flex items-center gap-1.5 font-medium">
<i className="h-2 w-2 shrink-0 rounded-full" style={{ background: KIND_COLOR[typeKey(c)] }} /> <i className="h-2 w-2 shrink-0 rounded-full" style={{ background: KIND_COLOR[typeKey(c)] }} />
<span className="whitespace-nowrap font-mono text-[12px]">{c.display_name || c.name}</span> <span className="whitespace-nowrap font-mono text-label">{c.display_name || c.name}</span>
</p> </p>
{c.synonyms.length > 0 && <p className="truncate pl-3.5 text-[11px] text-muted">{c.synonyms.slice(0, 4).join("、")}</p>} {c.synonyms.length > 0 && <p className="truncate pl-3.5 text-caption text-muted">{c.synonyms.slice(0, 4).join("、")}</p>}
</td> </td>
{kind === "function" && <td className="px-2"><TypeBadge t={typeKey(c)} /></td>} {kind === "function" && <td className="px-2"><TypeBadge t={typeKey(c)} /></td>}
{(kind === "function" || kind === "action") && <td className="px-2 text-muted">{objName[c.object_type] || c.object_type || "-"}</td>} {(kind === "function" || kind === "action") && <td className="px-2 text-muted">{objName[c.object_type] || c.object_type || "-"}</td>}
...@@ -165,7 +168,7 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null } ...@@ -165,7 +168,7 @@ export function BlockListPage({ kind, me }: { kind: ConceptKind; me: Me | null }
</td> </td>
{/* 右侧打开编辑器时收起描述和时间列,否则名称会被挤成一字一行 */} {/* 右侧打开编辑器时收起描述和时间列,否则名称会被挤成一字一行 */}
{!sel && <td className="max-w-[420px] truncate px-2 text-muted">{c.description || "-"}</td>} {!sel && <td className="max-w-[420px] truncate px-2 text-muted">{c.description || "-"}</td>}
{!sel && <td className="whitespace-nowrap px-2 text-[11px] text-muted">{fmtTime(c.updated_at)}</td>} {!sel && <td className="whitespace-nowrap px-2 text-caption text-muted">{fmtTime(c.updated_at)}</td>}
</tr> </tr>
))} ))}
</tbody> </tbody>
...@@ -205,7 +208,7 @@ function ObjectCards({ items, sel, onOpen }: { items: ConceptBrief[]; sel: strin ...@@ -205,7 +208,7 @@ function ObjectCards({ items, sel, onOpen }: { items: ConceptBrief[]; sel: strin
<div className="space-y-4 p-4"> <div className="space-y-4 p-4">
{groups.map(([g, xs]) => ( {groups.map(([g, xs]) => (
<div key={g}> <div key={g}>
<p className="mb-2 text-[12px] font-semibold text-muted">{g} <span className="font-normal">{xs.length}</span></p> <p className="mb-2 text-label font-semibold text-muted">{g} <span className="font-normal">{xs.length}</span></p>
<div className="grid gap-2.5 sm:grid-cols-2 xl:grid-cols-4"> <div className="grid gap-2.5 sm:grid-cols-2 xl:grid-cols-4">
{xs.map((c) => ( {xs.map((c) => (
<button key={c.id} onClick={() => onOpen(c.id)} <button key={c.id} onClick={() => onOpen(c.id)}
...@@ -213,11 +216,11 @@ function ObjectCards({ items, sel, onOpen }: { items: ConceptBrief[]; sel: strin ...@@ -213,11 +216,11 @@ function ObjectCards({ items, sel, onOpen }: { items: ConceptBrief[]; sel: strin
sel === c.id && "border-brand bg-brand/5")} sel === c.id && "border-brand bg-brand/5")}
style={{ borderTop: `3px solid ${KIND_COLOR.object_type}` }}> style={{ borderTop: `3px solid ${KIND_COLOR.object_type}` }}>
<div className="flex items-center gap-1.5"> <div className="flex items-center gap-1.5">
<span className="truncate font-mono text-[13px] font-semibold">{c.display_name || c.name}</span> <span className="truncate font-mono text-body font-semibold">{c.display_name || c.name}</span>
<span className="ml-auto"><MappedBadge v={c.mapped} /></span> <span className="ml-auto"><MappedBadge v={c.mapped} /></span>
</div> </div>
<p className="mt-1 line-clamp-2 min-h-[2.2em] text-[11.5px] text-muted">{c.description || c.synonyms.join("、") || "(无描述)"}</p> <p className="mt-1 line-clamp-2 min-h-[2.2em] text-label text-muted">{c.description || c.synonyms.join("、") || "(无描述)"}</p>
<div className="mt-2 flex items-center gap-1.5 text-[11px]"> <div className="mt-2 flex items-center gap-1.5 text-caption">
<Badge tone={STATUS_TONE[c.status]}>{STATUS_LABEL[c.status]}</Badge> <Badge tone={STATUS_TONE[c.status]}>{STATUS_LABEL[c.status]}</Badge>
{c.dirty && c.published && <Badge tone="bg-warn/10 text-warn">改</Badge>} {c.dirty && c.published && <Badge tone="bg-warn/10 text-warn">改</Badge>}
<span className="ml-auto text-muted">{fmtTime(c.updated_at)}</span> <span className="ml-auto text-muted">{fmtTime(c.updated_at)}</span>
...@@ -235,7 +238,7 @@ function LinkEnds({ c, objName }: { c: ConceptBrief; objName: Record<string, str ...@@ -235,7 +238,7 @@ function LinkEnds({ c, objName }: { c: ConceptBrief; objName: Record<string, str
const [spec, setSpec] = useState<any>(null); const [spec, setSpec] = useState<any>(null);
useEffect(() => { void onto.concept(c.id).then((x) => setSpec(x.spec)).catch(() => undefined); }, [c.id, c.updated_at]); useEffect(() => { void onto.concept(c.id).then((x) => setSpec(x.spec)).catch(() => undefined); }, [c.id, c.updated_at]);
if (!spec) return <span>…</span>; if (!spec) return <span>…</span>;
return <span>{objName[spec.from_type] || spec.from_type || "?"} → {objName[spec.to_type] || spec.to_type || "?"} <span className="text-[11px]">({spec.cardinality})</span></span>; return <span>{objName[spec.from_type] || spec.from_type || "?"} → {objName[spec.to_type] || spec.to_type || "?"} <span className="text-caption">({spec.cardinality})</span></span>;
} }
const EMPTY_ACTION = { target_type: "", params: [{ name: "reason", label: "原因", type: "text", required: true, enum: [] }], const EMPTY_ACTION = { target_type: "", params: [{ name: "reason", label: "原因", type: "text", required: true, enum: [] }],
...@@ -273,10 +276,10 @@ export function NewBlockModal({ kind, meta, objects, onClose, onCreated, initial ...@@ -273,10 +276,10 @@ export function NewBlockModal({ kind, meta, objects, onClose, onCreated, initial
<div className="grid grid-cols-2 gap-1.5 sm:grid-cols-3"> <div className="grid grid-cols-2 gap-1.5 sm:grid-cols-3">
{meta.categories.map((k) => ( {meta.categories.map((k) => (
<button key={k.category} onClick={() => setCat(k.category)} <button key={k.category} onClick={() => setCat(k.category)}
className={cn("rounded-lg border p-2 text-left text-[12.5px]", cat === k.category ? "border-brand bg-brand/5" : "border-line")}> className={cn("rounded-lg border p-2 text-left text-label", cat === k.category ? "border-brand bg-brand/5" : "border-line")}>
<span className="flex items-center gap-1.5 font-medium"><i className="h-2 w-2 rounded-full" style={{ background: KIND_COLOR[k.category] }} />{k.label}</span> <span className="flex items-center gap-1.5 font-medium"><i className="h-2 w-2 rounded-full" style={{ background: KIND_COLOR[k.category] }} />{k.label}</span>
<p className="line-clamp-2 text-[11px] text-muted">{k.desc}</p> <p className="line-clamp-2 text-caption text-muted">{k.desc}</p>
<p className="text-[10.5px] text-muted/80">引擎:{k.engine}</p> <p className="text-caption text-muted/80">引擎:{k.engine}</p>
</button> </button>
))} ))}
</div> </div>
......
...@@ -80,7 +80,7 @@ export function DraftModal({ kind, onClose, onSaved }: { ...@@ -80,7 +80,7 @@ export function DraftModal({ kind, onClose, onSaved }: {
: state === "bad" ? <XCircle className="mt-0.5 h-4 w-4 shrink-0 text-bad" /> : state === "bad" ? <XCircle className="mt-0.5 h-4 w-4 shrink-0 text-bad" />
: state === "run" ? <Loader2 className="mt-0.5 h-4 w-4 shrink-0 animate-spin text-brand" /> : state === "run" ? <Loader2 className="mt-0.5 h-4 w-4 shrink-0 animate-spin text-brand" />
: <Circle className="mt-0.5 h-4 w-4 shrink-0 text-muted/40" />} : <Circle className="mt-0.5 h-4 w-4 shrink-0 text-muted/40" />}
<div className="min-w-0 flex-1 text-[12.5px]"><p className="font-medium">{label}</p>{detail && <div className="text-muted">{detail}</div>}</div> <div className="min-w-0 flex-1 text-label"><p className="font-medium">{label}</p>{detail && <div className="text-muted">{detail}</div>}</div>
</li> </li>
); );
...@@ -127,14 +127,14 @@ export function DraftModal({ kind, onClose, onSaved }: { ...@@ -127,14 +127,14 @@ export function DraftModal({ kind, onClose, onSaved }: {
<TypeBadge t={draft.kind === "action" ? "action" : cat} /> <TypeBadge t={draft.kind === "action" ? "action" : cat} />
{!done?.ok && <Badge tone="bg-bad/10 text-bad">校验没通过,保存前需要修正</Badge>} {!done?.ok && <Badge tone="bg-bad/10 text-bad">校验没通过,保存前需要修正</Badge>}
</div> </div>
{draft.description && <p className="text-[12.5px] text-muted">{draft.description}</p>} {draft.description && <p className="text-label text-muted">{draft.description}</p>}
<SpecPreview kind={draft.kind} spec={draft.spec} onChange={(s) => setDraft({ ...draft, spec: s })} /> <SpecPreview kind={draft.kind} spec={draft.spec} onChange={(s) => setDraft({ ...draft, spec: s })} />
{samples.length > 0 && ( {samples.length > 0 && (
<div className="space-y-1.5"> <div className="space-y-1.5">
<p className="text-[12px] font-medium">试跑样例</p> <p className="text-label font-medium">试跑样例</p>
{samples.map((s, i) => ( {samples.map((s, i) => (
<div key={i} className="rounded-md border border-line bg-surface p-2"> <div key={i} className="rounded-md border border-line bg-surface p-2">
<div className="flex flex-wrap items-center gap-2 text-[12px]"> <div className="flex flex-wrap items-center gap-2 text-label">
<code className="min-w-0 flex-1 truncate">{JSON.stringify(s.input)}</code> <code className="min-w-0 flex-1 truncate">{JSON.stringify(s.input)}</code>
{s.expect !== undefined && s.expect !== "" && <span className="text-muted">期望:{String(s.expect)}</span>} {s.expect !== undefined && s.expect !== "" && <span className="text-muted">期望:{String(s.expect)}</span>}
<button className="btn btn-sm" onClick={() => void trySample(i)}><Play className="h-3 w-3" />试跑</button> <button className="btn btn-sm" onClick={() => void trySample(i)}><Play className="h-3 w-3" />试跑</button>
...@@ -157,13 +157,13 @@ function SpecPreview({ kind, spec, onChange }: { kind: string; spec: any; onChan ...@@ -157,13 +157,13 @@ function SpecPreview({ kind, spec, onChange }: { kind: string; spec: any; onChan
return ( return (
<div className="space-y-1"> <div className="space-y-1">
<input className="input font-mono" value={spec.expression || ""} onChange={(e) => onChange({ ...spec, expression: e.target.value })} /> <input className="input font-mono" value={spec.expression || ""} onChange={(e) => onChange({ ...spec, expression: e.target.value })} />
{spec.text && <p className="text-[12px] text-muted">{spec.text}</p>} {spec.text && <p className="text-label text-muted">{spec.text}</p>}
</div> </div>
); );
} }
if (kind === "action") { if (kind === "action") {
return ( return (
<div className="space-y-1 text-[12.5px]"> <div className="space-y-1 text-label">
<p>参数:{(spec.params || []).map((p: any) => `${p.label || p.name}${p.required ? "*" : ""}`).join("、") || "无"}</p> <p>参数:{(spec.params || []).map((p: any) => `${p.label || p.name}${p.required ? "*" : ""}`).join("、") || "无"}</p>
{(spec.criteria || []).map((c: any, i: number) => <p key={i}>前置条件:<code>{c.expression}</code>({c.message})</p>)} {(spec.criteria || []).map((c: any, i: number) => <p key={i}>前置条件:<code>{c.expression}</code>({c.message})</p>)}
{(spec.effects || []).map((e: any, i: number) => <p key={i}>效果 {i + 1}:<code>{e.tool}</code> {JSON.stringify(e.args)}</p>)} {(spec.effects || []).map((e: any, i: number) => <p key={i}>效果 {i + 1}:<code>{e.tool}</code> {JSON.stringify(e.args)}</p>)}
...@@ -171,5 +171,5 @@ function SpecPreview({ kind, spec, onChange }: { kind: string; spec: any; onChan ...@@ -171,5 +171,5 @@ function SpecPreview({ kind, spec, onChange }: { kind: string; spec: any; onChan
</div> </div>
); );
} }
return <pre className={cn("max-h-56 overflow-auto rounded bg-surface p-2 text-[11.5px]")}>{JSON.stringify(spec, null, 2)}</pre>; return <pre className={cn("max-h-56 overflow-auto rounded bg-surface p-2 text-label")}>{JSON.stringify(spec, null, 2)}</pre>;
} }
...@@ -86,7 +86,7 @@ export function PublishPage({ me }: { me: Me | null }) { ...@@ -86,7 +86,7 @@ export function PublishPage({ me }: { me: Me | null }) {
</>} </>}
{!it.can_decide && it.created_by !== me?.id && <Badge>{it.cannot_reason}</Badge>} {!it.can_decide && it.created_by !== me?.id && <Badge>{it.cannot_reason}</Badge>}
</>} /> </>} />
<div className="p-4">{it.payload?.diff ? <DiffView diff={it.payload.diff} /> : <p className="text-[12.5px] text-muted">回滚到 v{it.payload?.rev}</p>}</div> <div className="p-4">{it.payload?.diff ? <DiffView diff={it.payload.diff} /> : <p className="text-label text-muted">回滚到 v{it.payload?.rev}</p>}</div>
</Card> </Card>
))} ))}
...@@ -103,7 +103,7 @@ export function PublishPage({ me }: { me: Me | null }) { ...@@ -103,7 +103,7 @@ export function PublishPage({ me }: { me: Me | null }) {
<div className="space-y-3 p-4"> <div className="space-y-3 p-4">
{!diff ? <Spinner /> : <DiffView diff={diff} />} {!diff ? <Spinner /> : <DiffView diff={diff} />}
{diff && total > 0 && ( {diff && total > 0 && (
<div className="flex flex-wrap gap-1.5 text-[11.5px]"> <div className="flex flex-wrap gap-1.5 text-label">
{[...diff.added, ...diff.changed].map((x) => ( {[...diff.added, ...diff.changed].map((x) => (
<button key={x.id} className="chip" onClick={() => go(pageOfKind(x.kind), { id: x.id })}>打开 {x.name}</button> <button key={x.id} className="chip" onClick={() => go(pageOfKind(x.kind), { id: x.id })}>打开 {x.name}</button>
))} ))}
...@@ -128,7 +128,7 @@ export function PublishPage({ me }: { me: Me | null }) { ...@@ -128,7 +128,7 @@ export function PublishPage({ me }: { me: Me | null }) {
{!items ? <div className="p-4"><Spinner /></div> : (tab === "pending" ? pending : history).length === 0 {!items ? <div className="p-4"><Spinner /></div> : (tab === "pending" ? pending : history).length === 0
? <Empty title={tab === "pending" ? "没有待审批的提案" : "还没有提案记录"} /> ? <Empty title={tab === "pending" ? "没有待审批的提案" : "还没有提案记录"} />
: (tab === "pending" ? pending : history).map((it) => ( : (tab === "pending" ? pending : history).map((it) => (
<div key={it.id} className="flex items-center gap-3 px-4 py-2 text-[12.5px]"> <div key={it.id} className="flex items-center gap-3 px-4 py-2 text-label">
<Badge tone={STATUS_TONE[it.status]}>{STATUS_LABEL[it.status] || it.status}</Badge> <Badge tone={STATUS_TONE[it.status]}>{STATUS_LABEL[it.status] || it.status}</Badge>
<span className="min-w-0 flex-1 truncate">{it.title}{it.payload?.note ? ` · ${it.payload.note}` : ""}</span> <span className="min-w-0 flex-1 truncate">{it.title}{it.payload?.note ? ` · ${it.payload.note}` : ""}</span>
<span className="text-muted">{it.created_by}{it.decided_by ? ` → ${it.decided_by}` : ""}</span> <span className="text-muted">{it.created_by}{it.decided_by ? ` → ${it.decided_by}` : ""}</span>
...@@ -178,11 +178,11 @@ export function VersionsPage({ me }: { me: Me | null }) { ...@@ -178,11 +178,11 @@ export function VersionsPage({ me }: { me: Me | null }) {
{shown.map((r) => ( {shown.map((r) => (
<button key={r.revision} onClick={() => { setTo(r.revision); setFrom(revs.find((x) => x.revision < r.revision)?.revision ?? 0); }} <button key={r.revision} onClick={() => { setTo(r.revision); setFrom(revs.find((x) => x.revision < r.revision)?.revision ?? 0); }}
className={cn("block w-full border-b border-line/60 px-3 py-2 text-left hover:bg-ink/[0.03]", to === r.revision && "bg-brand/5")}> className={cn("block w-full border-b border-line/60 px-3 py-2 text-left hover:bg-ink/[0.03]", to === r.revision && "bg-brand/5")}>
<p className="flex items-center gap-2 text-[13px] font-semibold">v{r.revision} <p className="flex items-center gap-2 text-body font-semibold">v{r.revision}
{r.revision === revs[0].revision && <Badge tone="bg-ok/10 text-ok">线上</Badge>} {r.revision === revs[0].revision && <Badge tone="bg-ok/10 text-ok">线上</Badge>}
<span className="ml-auto text-[11px] font-normal text-muted">+{r.diff.added?.length || 0} ~{r.diff.changed?.length || 0} -{r.diff.removed?.length || 0}</span></p> <span className="ml-auto text-caption font-normal text-muted">+{r.diff.added?.length || 0} ~{r.diff.changed?.length || 0} -{r.diff.removed?.length || 0}</span></p>
<p className="truncate text-[11.5px] text-muted">{r.note || "(无说明)"}</p> <p className="truncate text-label text-muted">{r.note || "(无说明)"}</p>
<p className="text-[11px] text-muted">{fmtTime(r.created_at)} · {r.published_by} · {r.concepts} 块积木</p> <p className="text-caption text-muted">{fmtTime(r.created_at)} · {r.published_by} · {r.concepts} 块积木</p>
</button> </button>
))} ))}
</div> </div>
...@@ -206,7 +206,7 @@ export function VersionsPage({ me }: { me: Me | null }) { ...@@ -206,7 +206,7 @@ export function VersionsPage({ me }: { me: Me | null }) {
}}><RotateCcw className="h-3.5 w-3.5" />回滚到 v{to}</button> }}><RotateCcw className="h-3.5 w-3.5" />回滚到 v{to}</button>
)} )}
</>} /> </>} />
<div className="min-h-0 flex-1 space-y-3 overflow-auto p-4 text-[12.5px]"> <div className="min-h-0 flex-1 space-y-3 overflow-auto p-4 text-label">
{busy || !cmp ? <Spinner /> : ( {busy || !cmp ? <Spinner /> : (
<> <>
{!cmp.added.length && !cmp.removed.length && !cmp.changed.length && <p className="text-muted">两个版本完全一样</p>} {!cmp.added.length && !cmp.removed.length && !cmp.changed.length && <p className="text-muted">两个版本完全一样</p>}
...@@ -218,7 +218,7 @@ export function VersionsPage({ me }: { me: Me | null }) { ...@@ -218,7 +218,7 @@ export function VersionsPage({ me }: { me: Me | null }) {
{cmp.changed.map((x) => ( {cmp.changed.map((x) => (
<div key={x.id} className="rounded-lg border border-line"> <div key={x.id} className="rounded-lg border border-line">
<p className="flex items-center gap-1.5 border-b border-line bg-ink/[0.02] px-2 py-1 font-medium"><TypeBadge t={x.kind} />{x.name}</p> <p className="flex items-center gap-1.5 border-b border-line bg-ink/[0.02] px-2 py-1 font-medium"><TypeBadge t={x.kind} />{x.name}</p>
<table className="w-full text-[12px]"> <table className="w-full text-label">
<tbody>{(x.changes || []).map((ch) => ( <tbody>{(x.changes || []).map((ch) => (
<tr key={ch.field} className="border-b border-line/50 align-top last:border-0"> <tr key={ch.field} className="border-b border-line/50 align-top last:border-0">
<td className="w-32 px-2 py-1 text-muted">{FIELD_LABEL[ch.field] || ch.field.replace("spec.", "")}</td> <td className="w-32 px-2 py-1 text-muted">{FIELD_LABEL[ch.field] || ch.field.replace("spec.", "")}</td>
...@@ -239,7 +239,7 @@ export function VersionsPage({ me }: { me: Me | null }) { ...@@ -239,7 +239,7 @@ export function VersionsPage({ me }: { me: Me | null }) {
} }
function Section({ title, tone, children }: { title: string; tone: string; children: React.ReactNode }) { function Section({ title, tone, children }: { title: string; tone: string; children: React.ReactNode }) {
return <div className="space-y-1.5"><p className={cn("text-[12px] font-semibold", tone)}>{title}</p>{children}</div>; return <div className="space-y-1.5"><p className={cn("text-label font-semibold", tone)}>{title}</p>{children}</div>;
} }
function Val({ v, tone }: { v: any; tone: string }) { function Val({ v, tone }: { v: any; tone: string }) {
......
...@@ -12,7 +12,7 @@ import { KIND_COLOR, TYPE_LABEL, type TypeKey } from "@/lib/onto"; ...@@ -12,7 +12,7 @@ import { KIND_COLOR, TYPE_LABEL, type TypeKey } from "@/lib/onto";
export function TypeBadge({ t, className }: { t: TypeKey | string; className?: string }) { export function TypeBadge({ t, className }: { t: TypeKey | string; className?: string }) {
const color = KIND_COLOR[t] || "#64748b"; const color = KIND_COLOR[t] || "#64748b";
return ( return (
<span className={cn("inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[11px] font-medium", className)} <span className={cn("inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-caption font-medium", className)}
style={{ background: `${color}18`, color }}> style={{ background: `${color}18`, color }}>
<i className="h-1.5 w-1.5 rounded-full" style={{ background: color }} /> <i className="h-1.5 w-1.5 rounded-full" style={{ background: color }} />
{TYPE_LABEL[t] || t} {TYPE_LABEL[t] || t}
...@@ -38,7 +38,7 @@ export function SchemaForm({ schema, value, onChange, disabled, hints, compact } ...@@ -38,7 +38,7 @@ export function SchemaForm({ schema, value, onChange, disabled, hints, compact }
if (v === "" || v === undefined) delete next[k]; else next[k] = v; if (v === "" || v === undefined) delete next[k]; else next[k] = v;
onChange(next); onChange(next);
}; };
if (!props.length) return <p className="text-[12px] text-muted">不需要参数</p>; if (!props.length) return <p className="text-label text-muted">不需要参数</p>;
return ( return (
<div className={cn("grid gap-2", compact ? "sm:grid-cols-2" : "sm:grid-cols-2 lg:grid-cols-3")}> <div className={cn("grid gap-2", compact ? "sm:grid-cols-2" : "sm:grid-cols-2 lg:grid-cols-3")}>
{props.map(([k, p]) => { {props.map(([k, p]) => {
...@@ -49,7 +49,7 @@ export function SchemaForm({ schema, value, onChange, disabled, hints, compact } ...@@ -49,7 +49,7 @@ export function SchemaForm({ schema, value, onChange, disabled, hints, compact }
const label = ( const label = (
<span className="flex items-center gap-1" title={p.description || k}> <span className="flex items-center gap-1" title={p.description || k}>
<span className="truncate text-ink">{desc || k}</span>{req.has(k) && <span className="text-bad">*</span>} <span className="truncate text-ink">{desc || k}</span>{req.has(k) && <span className="text-bad">*</span>}
{desc && <code className="shrink-0 text-[10px] font-normal text-muted/70">{k}</code>} {desc && <code className="shrink-0 text-caption font-normal text-muted/70">{k}</code>}
</span> </span>
); );
let input: ReactNode; let input: ReactNode;
...@@ -71,7 +71,7 @@ export function SchemaForm({ schema, value, onChange, disabled, hints, compact } ...@@ -71,7 +71,7 @@ export function SchemaForm({ schema, value, onChange, disabled, hints, compact }
input = <JsonBox key={k} value={v ?? (t === "array" ? [] : {})} disabled={disabled} onChange={(x) => set(k, x)} small />; input = <JsonBox key={k} value={v ?? (t === "array" ? [] : {})} disabled={disabled} onChange={(x) => set(k, x)} small />;
} else { } else {
input = ( input = (
<input className="input h-8 font-mono text-[12px]" value={v ?? ""} disabled={disabled} <input className="input h-8 font-mono text-label" value={v ?? ""} disabled={disabled}
placeholder={t === "integer" || t === "number" ? "数字,或 $参数" : "值,或 $参数 / $obj.属性"} placeholder={t === "integer" || t === "number" ? "数字,或 $参数" : "值,或 $参数 / $obj.属性"}
onChange={(e) => { onChange={(e) => {
const raw = e.target.value; const raw = e.target.value;
...@@ -84,7 +84,7 @@ export function SchemaForm({ schema, value, onChange, disabled, hints, compact } ...@@ -84,7 +84,7 @@ export function SchemaForm({ schema, value, onChange, disabled, hints, compact }
<div key={k} className={cn("min-w-0", (t === "object" || t === "array") && "sm:col-span-2")}> <div key={k} className={cn("min-w-0", (t === "object" || t === "array") && "sm:col-span-2")}>
<label className="label">{label}</label> <label className="label">{label}</label>
{input} {input}
{hints?.[k] && <p className="mt-0.5 text-[11px] text-muted">{hints[k]}</p>} {hints?.[k] && <p className="mt-0.5 text-caption text-muted">{hints[k]}</p>}
</div> </div>
); );
})} })}
...@@ -125,7 +125,7 @@ export function JsonBox({ value, onChange, disabled, placeholder, small }: { ...@@ -125,7 +125,7 @@ export function JsonBox({ value, onChange, disabled, placeholder, small }: {
const [text, setText] = useState(() => JSON.stringify(value ?? {}, null, small ? 0 : 2)); const [text, setText] = useState(() => JSON.stringify(value ?? {}, null, small ? 0 : 2));
const [bad, setBad] = useState(false); const [bad, setBad] = useState(false);
return ( return (
<textarea className={cn("input font-mono text-[12px]", small ? "min-h-[34px]" : "min-h-[64px]", bad && "border-bad")} <textarea className={cn("input font-mono text-label", small ? "min-h-[34px]" : "min-h-[64px]", bad && "border-bad")}
value={text} disabled={disabled} placeholder={placeholder} value={text} disabled={disabled} placeholder={placeholder}
onChange={(e) => { onChange={(e) => {
setText(e.target.value); setText(e.target.value);
...@@ -137,14 +137,14 @@ export function JsonBox({ value, onChange, disabled, placeholder, small }: { ...@@ -137,14 +137,14 @@ export function JsonBox({ value, onChange, disabled, placeholder, small }: {
/** 结果展示:表格数据渲染成表,其余缩进 JSON。 */ /** 结果展示:表格数据渲染成表,其余缩进 JSON。 */
export function ResultView({ data }: { data: any }) { export function ResultView({ data }: { data: any }) {
if (data == null) return null; if (data == null) return null;
if (data.error) return <p className="rounded bg-bad/5 px-2 py-1.5 text-[12px] text-bad">{String(data.error)}</p>; if (data.error) return <p className="rounded bg-bad/5 px-2 py-1.5 text-label text-bad">{String(data.error)}</p>;
const rows: any[][] | undefined = data.rows; const rows: any[][] | undefined = data.rows;
return ( return (
<div className="space-y-1.5"> <div className="space-y-1.5">
{data.summary && <p className="text-[12.5px] font-medium text-ok">{data.summary}</p>} {data.summary && <p className="text-label font-medium text-ok">{data.summary}</p>}
{Array.isArray(rows) && data.columns && ( {Array.isArray(rows) && data.columns && (
<div className="max-h-56 overflow-auto rounded border border-line"> <div className="max-h-56 overflow-auto rounded border border-line">
<table className="w-full text-[12px]"> <table className="w-full text-label">
<thead className="bg-ink/[0.03]"><tr>{data.columns.map((c: string) => <th key={c} className="px-2 py-1 text-left">{c}</th>)}</tr></thead> <thead className="bg-ink/[0.03]"><tr>{data.columns.map((c: string) => <th key={c} className="px-2 py-1 text-left">{c}</th>)}</tr></thead>
<tbody>{rows.slice(0, 50).map((r, i) => ( <tbody>{rows.slice(0, 50).map((r, i) => (
<tr key={i} className="border-t border-line/60">{r.map((v, j) => <td key={j} className="px-2 py-1">{v == null ? "∅" : String(v)}</td>)}</tr> <tr key={i} className="border-t border-line/60">{r.map((v, j) => <td key={j} className="px-2 py-1">{v == null ? "∅" : String(v)}</td>)}</tr>
...@@ -153,8 +153,8 @@ export function ResultView({ data }: { data: any }) { ...@@ -153,8 +153,8 @@ export function ResultView({ data }: { data: any }) {
</div> </div>
)} )}
<details> <details>
<summary className="cursor-pointer text-[11px] text-muted">完整结果</summary> <summary className="cursor-pointer text-caption text-muted">完整结果</summary>
<pre className="max-h-64 overflow-auto rounded bg-ink/5 p-2 text-[11px]">{JSON.stringify(data, null, 2)}</pre> <pre className="max-h-64 overflow-auto rounded bg-ink/5 p-2 text-caption">{JSON.stringify(data, null, 2)}</pre>
</details> </details>
</div> </div>
); );
......
...@@ -16,7 +16,7 @@ export const FIELD_LABEL: Record<string, string> = { ...@@ -16,7 +16,7 @@ export const FIELD_LABEL: Record<string, string> = {
export function DiffView({ diff }: { diff: Diff }) { export function DiffView({ diff }: { diff: Diff }) {
return ( return (
<div className="space-y-1.5 text-[12.5px]"> <div className="space-y-1.5 text-label">
{diff.added.map((x) => <p key={x.id} className="flex items-center gap-1.5"><Badge tone="bg-ok/10 text-ok">新增</Badge><TypeBadge t={x.type_key || x.kind} />{x.name}</p>)} {diff.added.map((x) => <p key={x.id} className="flex items-center gap-1.5"><Badge tone="bg-ok/10 text-ok">新增</Badge><TypeBadge t={x.type_key || x.kind} />{x.name}</p>)}
{diff.changed.map((x) => <p key={x.id} className="flex flex-wrap items-center gap-1.5"><Badge tone="bg-warn/10 text-warn">修改</Badge><TypeBadge t={x.type_key || x.kind} />{x.name} {diff.changed.map((x) => <p key={x.id} className="flex flex-wrap items-center gap-1.5"><Badge tone="bg-warn/10 text-warn">修改</Badge><TypeBadge t={x.type_key || x.kind} />{x.name}
<span className="text-muted">({x.fields.map((f) => FIELD_LABEL[f] || f).join("、")})</span></p>)} <span className="text-muted">({x.fields.map((f) => FIELD_LABEL[f] || f).join("、")})</span></p>)}
...@@ -36,13 +36,13 @@ export function ImportExport({ onClose, onDone }: { onClose: () => void; onDone: ...@@ -36,13 +36,13 @@ export function ImportExport({ onClose, onDone }: { onClose: () => void; onDone:
desc="本体即代码:对象、关系、函数、动作、业务角色、流程卡都可以导出成 YAML,在客户之间复用。模板导入后是草稿,审阅后发布。"> desc="本体即代码:对象、关系、函数、动作、业务角色、流程卡都可以导出成 YAML,在客户之间复用。模板导入后是草稿,审阅后发布。">
<div className="space-y-4"> <div className="space-y-4">
<div> <div>
<p className="mb-1.5 text-[12px] font-medium text-muted">行业模板</p> <p className="mb-1.5 text-label font-medium text-muted">行业模板</p>
<div className="grid gap-2 sm:grid-cols-2"> <div className="grid gap-2 sm:grid-cols-2">
{tpls.map((t) => ( {tpls.map((t) => (
<div key={t.id} className="rounded-lg border border-line p-3"> <div key={t.id} className="rounded-lg border border-line p-3">
<p className="text-[13px] font-medium">{t.name}</p> <p className="text-body font-medium">{t.name}</p>
<p className="mt-0.5 line-clamp-3 text-[12px] text-muted">{t.description}</p> <p className="mt-0.5 line-clamp-3 text-label text-muted">{t.description}</p>
<p className="mt-1 text-[11px] text-muted">对象 {t.counts?.object_type || 0} · 关系 {t.counts?.link_type || 0} · 函数 {t.counts?.function || 0} · 动作 {t.counts?.action || 0} · 角色 {t.roles} · 流程卡 {t.sops}</p> <p className="mt-1 text-caption text-muted">对象 {t.counts?.object_type || 0} · 关系 {t.counts?.link_type || 0} · 函数 {t.counts?.function || 0} · 动作 {t.counts?.action || 0} · 角色 {t.roles} · 流程卡 {t.sops}</p>
<button className="btn btn-sm mt-2" onClick={async () => { <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)); } try { const r = await onto.applyTemplate(t.id); setResult(r); onDone(); } catch (e) { toast("error", errText(e)); }
}}>导入</button> }}>导入</button>
...@@ -52,10 +52,10 @@ export function ImportExport({ onClose, onDone }: { onClose: () => void; onDone: ...@@ -52,10 +52,10 @@ export function ImportExport({ onClose, onDone }: { onClose: () => void; onDone:
</div> </div>
<div> <div>
<div className="mb-1.5 flex items-center justify-between"> <div className="mb-1.5 flex items-center justify-between">
<p className="text-[12px] font-medium text-muted">YAML 导入</p> <p className="text-label 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> <a className="btn btn-sm" href={onto.exportYamlUrl} download="ontology.yaml"><Download className="h-3.5 w-3.5" />导出当前本体</a>
</div> </div>
<textarea className="input min-h-[140px] font-mono text-[12px]" value={yaml} onChange={(e) => setYaml(e.target.value)} <textarea className="input min-h-[140px] font-mono text-label" value={yaml} onChange={(e) => setYaml(e.target.value)}
placeholder={"concepts:\n - kind: function\n name: 销售额\n spec: {category: aggregate, unit: 元}"} /> placeholder={"concepts:\n - kind: function\n name: 销售额\n spec: {category: aggregate, unit: 元}"} />
<div className="mt-2 flex gap-2"> <div className="mt-2 flex gap-2">
<label className="btn btn-sm cursor-pointer"><Upload className="h-3.5 w-3.5" />选文件 <label className="btn btn-sm cursor-pointer"><Upload className="h-3.5 w-3.5" />选文件
...@@ -68,7 +68,7 @@ export function ImportExport({ onClose, onDone }: { onClose: () => void; onDone: ...@@ -68,7 +68,7 @@ export function ImportExport({ onClose, onDone }: { onClose: () => void; onDone:
</div> </div>
</div> </div>
{result && ( {result && (
<div className="rounded-lg bg-ink/[0.03] p-3 text-[12.5px]"> <div className="rounded-lg bg-ink/[0.03] p-3 text-label">
新增 {result.created.length},更新 {result.updated.length},跳过 {result.skipped.length}{result.roles ? `,业务角色 ${result.roles}` : ""} 新增 {result.created.length},更新 {result.updated.length},跳过 {result.skipped.length}{result.roles ? `,业务角色 ${result.roles}` : ""}
{(result.notes || []).map((x: string) => <p key={x} className="text-muted">{x}</p>)} {(result.notes || []).map((x: string) => <p key={x} className="text-muted">{x}</p>)}
{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.errors.length > 0 && <ul className="mt-1 list-disc pl-5 text-bad">{result.errors.map((x: string) => <li key={x}>{x}</li>)}</ul>}
...@@ -93,12 +93,12 @@ export function ProposeModal({ onClose }: { onClose: () => void }) { ...@@ -93,12 +93,12 @@ export function ProposeModal({ onClose }: { onClose: () => void }) {
desc="AI 按四元组从文档或数据源里找出对象、关系、函数、动作,全部进入审核队列 —— 人采纳后才会成为积木。"> desc="AI 按四元组从文档或数据源里找出对象、关系、函数、动作,全部进入审核队列 —— 人采纳后才会成为积木。">
<div className="space-y-4"> <div className="space-y-4">
<div className="rounded-lg border border-line p-3"> <div className="rounded-lg border border-line p-3">
<p className="text-[13px] font-medium">从已抽取的文档提议</p> <p className="text-body font-medium">从已抽取的文档提议</p>
<p className="mt-0.5 text-[12px] text-muted">每条提议都带原文出处;与已有积木说法冲突的会单独标为「知识冲突」;文中的岗位会登记为业务角色。</p> <p className="mt-0.5 text-label text-muted">每条提议都带原文出处;与已有积木说法冲突的会单独标为「知识冲突」;文中的岗位会登记为业务角色。</p>
{job ? ( {job ? (
<div className="mt-2 space-y-1"> <div className="mt-2 space-y-1">
<Progress value={job.progress} /> <Progress value={job.progress} />
<p className="text-[12px] text-muted">{job.message || job.stage}</p> <p className="text-label text-muted">{job.message || job.stage}</p>
{job.status === "done" && <button className="btn btn-sm" onClick={() => go("inbox", { tab: "reviews" })}>去审核</button>} {job.status === "done" && <button className="btn btn-sm" onClick={() => go("inbox", { tab: "reviews" })}>去审核</button>}
</div> </div>
) : ( ) : (
...@@ -109,8 +109,8 @@ export function ProposeModal({ onClose }: { onClose: () => void }) { ...@@ -109,8 +109,8 @@ export function ProposeModal({ onClose }: { onClose: () => void }) {
)} )}
</div> </div>
<div className="rounded-lg border border-line p-3"> <div className="rounded-lg border border-line p-3">
<p className="text-[13px] font-medium">从数据源提议</p> <p className="text-body font-medium">从数据源提议</p>
<p className="mt-0.5 text-[12px] text-muted">已启用的表 → 对象(带表绑定),表间关联 → 关系(带关联列)。</p> <p className="mt-0.5 text-label text-muted">已启用的表 → 对象(带表绑定),表间关联 → 关系(带关联列)。</p>
<div className="mt-2 flex flex-wrap gap-2"> <div className="mt-2 flex flex-wrap gap-2">
{dss.map((d) => ( {dss.map((d) => (
<button key={d.id} className="btn btn-sm" onClick={async () => { <button key={d.id} className="btn btn-sm" onClick={async () => {
...@@ -118,9 +118,9 @@ export function ProposeModal({ onClose }: { onClose: () => void }) { ...@@ -118,9 +118,9 @@ export function ProposeModal({ onClose }: { onClose: () => void }) {
catch (e) { toast("error", errText(e)); } catch (e) { toast("error", errText(e)); }
}}>{d.name}</button> }}>{d.name}</button>
))} ))}
{!dss.length && <span className="text-[12px] text-muted">还没有接入数据源</span>} {!dss.length && <span className="text-label text-muted">还没有接入数据源</span>}
</div> </div>
{dsResult && <p className="mt-2 text-[12px]">{dsResult} <button className="text-brand underline" onClick={() => go("inbox", { tab: "reviews" })}>去审核</button></p>} {dsResult && <p className="mt-2 text-label">{dsResult} <button className="text-brand underline" onClick={() => go("inbox", { tab: "reviews" })}>去审核</button></p>}
</div> </div>
</div> </div>
</Modal> </Modal>
...@@ -143,7 +143,7 @@ export function LinkTester({ onClose }: { onClose: () => void }) { ...@@ -143,7 +143,7 @@ export function LinkTester({ onClose }: { onClose: () => void }) {
{r.concepts.map((c: any) => <Pill key={c.id} color={KIND_COLOR[c.type_key || c.kind]}>{c.name} ← {c.matched.join("、")}</Pill>)} {r.concepts.map((c: any) => <Pill key={c.id} color={KIND_COLOR[c.type_key || 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.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.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>} {!r.concepts.length && !r.instances.length && !r.time && <p className="text-label text-muted">没有识别到(只看已发布的积木)</p>}
</div> </div>
)} )}
</div> </div>
......
...@@ -21,7 +21,7 @@ export function OverviewPage() { ...@@ -21,7 +21,7 @@ export function OverviewPage() {
return ( return (
<div className="mx-auto max-w-6xl space-y-4"> <div className="mx-auto max-w-6xl space-y-4">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<p className="flex-1 text-[12px] text-muted">本体经 MCP 暴露给 Agent(含系统自带的「提问」):所有调用都可追溯,写操作一律先成审批单。</p> <p className="flex-1 text-label text-muted">本体经 MCP 暴露给 Agent(含系统自带的「提问」):所有调用都可追溯,写操作一律先成审批单。</p>
<button className="btn btn-sm" onClick={load}><RefreshCw className="h-3.5 w-3.5" />刷新</button> <button className="btn btn-sm" onClick={load}><RefreshCw className="h-3.5 w-3.5" />刷新</button>
</div> </div>
<Card className="grid gap-4 p-4 sm:grid-cols-5"> <Card className="grid gap-4 p-4 sm:grid-cols-5">
...@@ -35,10 +35,10 @@ export function OverviewPage() { ...@@ -35,10 +35,10 @@ export function OverviewPage() {
<div className="grid gap-4 lg:grid-cols-2"> <div className="grid gap-4 lg:grid-cols-2">
<Card> <Card>
<CardHeader title={<span className="flex items-center gap-2"><Bot className="h-4 w-4" />最常用的工具(24h)</span>} <CardHeader title={<span className="flex items-center gap-2"><Bot className="h-4 w-4" />最常用的工具(24h)</span>}
right={<button className="btn btn-ghost btn-sm" onClick={() => go("monitor", { tab: "mcp" })}>MCP 接入</button>} /> right={<button className="btn btn-ghost btn-sm" onClick={() => go("mcp")}>MCP 接入</button>} />
{!d.mcp.top_tools.length ? <Empty title="还没有调用" desc="在「MCP 服务」里在线调用,或把 MCP 地址接给你的 Agent。" /> : ( {!d.mcp.top_tools.length ? <Empty title="还没有调用" desc="在「MCP 服务」里在线调用,或把 MCP 地址接给你的 Agent。" /> : (
<table className="w-full text-[12.5px]"> <table className="w-full text-label">
<thead className="text-[11.5px] text-muted"><tr className="border-b border-line"> <thead className="text-label text-muted"><tr className="border-b border-line">
<th className="px-4 py-2 text-left">工具</th><th className="px-2 text-right">调用</th><th className="px-2 text-right">失败</th><th className="px-4 text-right">平均耗时</th></tr></thead> <th className="px-4 py-2 text-left">工具</th><th className="px-2 text-right">调用</th><th className="px-2 text-right">失败</th><th className="px-4 text-right">平均耗时</th></tr></thead>
<tbody>{d.mcp.top_tools.map((t) => ( <tbody>{d.mcp.top_tools.map((t) => (
<tr key={t.tool} className="border-b border-line/60"> <tr key={t.tool} className="border-b border-line/60">
...@@ -55,11 +55,11 @@ export function OverviewPage() { ...@@ -55,11 +55,11 @@ export function OverviewPage() {
<div className="divide-y divide-line"> <div className="divide-y divide-line">
{!d.approvals.top.length && <Empty title="没有待审批的动作" />} {!d.approvals.top.length && <Empty title="没有待审批的动作" />}
{d.approvals.top.map((r) => ( {d.approvals.top.map((r) => (
<button key={r.id} className="flex w-full items-center gap-2 px-4 py-2 text-left text-[12.5px] hover:bg-ink/[0.03]" onClick={() => go("inbox", { run: r.id })}> <button key={r.id} className="flex w-full items-center gap-2 px-4 py-2 text-left text-label hover:bg-ink/[0.03]" onClick={() => go("inbox", { run: r.id })}>
<Badge tone={PRIORITY_TONE[r.priority]}>{r.priority}</Badge> <Badge tone={PRIORITY_TONE[r.priority]}>{r.priority}</Badge>
<span className="font-medium">{r.action_name}</span> <span className="font-medium">{r.action_name}</span>
<span className="min-w-0 flex-1 truncate text-muted">{r.reason}</span> <span className="min-w-0 flex-1 truncate text-muted">{r.reason}</span>
<span className="text-[11px] text-muted">{fmtTime(r.created_at)}</span> <span className="text-caption text-muted">{fmtTime(r.created_at)}</span>
</button> </button>
))} ))}
</div> </div>
...@@ -70,11 +70,11 @@ export function OverviewPage() { ...@@ -70,11 +70,11 @@ export function OverviewPage() {
<div className="divide-y divide-line"> <div className="divide-y divide-line">
{!d.pipelines.items.length && <Empty title="还没有数据管道" />} {!d.pipelines.items.length && <Empty title="还没有数据管道" />}
{d.pipelines.items.map((p) => ( {d.pipelines.items.map((p) => (
<div key={p.id} className="flex items-center gap-2 px-4 py-2 text-[12.5px]"> <div key={p.id} className="flex items-center gap-2 px-4 py-2 text-label">
<Activity className={`h-3.5 w-3.5 ${p.status === "failed" ? "text-bad" : p.status === "ok" ? "text-ok" : "text-muted"}`} /> <Activity className={`h-3.5 w-3.5 ${p.status === "failed" ? "text-bad" : p.status === "ok" ? "text-ok" : "text-muted"}`} />
<span className="font-medium">{p.object_type}</span> <span className="font-medium">{p.object_type}</span>
<span className="text-muted">{p.last_rows} 个 · {p.last_edges} 边</span> <span className="text-muted">{p.last_rows} 个 · {p.last_edges} 边</span>
<span className="ml-auto text-[11px] text-muted">{fmtTime(p.last_run_at)}</span> <span className="ml-auto text-caption text-muted">{fmtTime(p.last_run_at)}</span>
</div> </div>
))} ))}
</div> </div>
...@@ -83,7 +83,7 @@ export function OverviewPage() { ...@@ -83,7 +83,7 @@ export function OverviewPage() {
<CardHeader title={<span className="flex items-center gap-2"><ListChecks className="h-4 w-4" />动作执行</span>} /> <CardHeader title={<span className="flex items-center gap-2"><ListChecks className="h-4 w-4" />动作执行</span>} />
<div className="flex flex-wrap gap-2 p-4"> <div className="flex flex-wrap gap-2 p-4">
{Object.entries(d.actions).map(([k, v]) => <Badge key={k}>{STATUS_LABEL[k] || k} {v}</Badge>)} {Object.entries(d.actions).map(([k, v]) => <Badge key={k}>{STATUS_LABEL[k] || k} {v}</Badge>)}
{!Object.keys(d.actions).length && <p className="text-[12px] text-muted">还没有动作</p>} {!Object.keys(d.actions).length && <p className="text-label text-muted">还没有动作</p>}
</div> </div>
</Card> </Card>
</div> </div>
......
...@@ -94,7 +94,7 @@ export function SettingsPage({ onChanged }: { onChanged?: () => void }) { ...@@ -94,7 +94,7 @@ export function SettingsPage({ onChanged }: { onChanged?: () => void }) {
{dirty && ( {dirty && (
<div className="fixed bottom-4 left-1/2 z-40 flex -translate-x-1/2 items-center gap-3 <div className="fixed bottom-4 left-1/2 z-40 flex -translate-x-1/2 items-center gap-3
rounded-xl border border-line bg-surface px-4 py-2.5 shadow-lg"> rounded-xl border border-line bg-surface px-4 py-2.5 shadow-lg">
<span className="text-[13px]"> <span className="text-body">
有 <b className="tabular-nums">{Object.keys(draft).length}</b> 项修改未保存 有 <b className="tabular-nums">{Object.keys(draft).length}</b> 项修改未保存
</span> </span>
<button className="btn btn-sm" onClick={() => setDraft({})}> <button className="btn btn-sm" onClick={() => setDraft({})}>
...@@ -160,15 +160,15 @@ function Field({ field, value, changed, onChange }: { ...@@ -160,15 +160,15 @@ function Field({ field, value, changed, onChange }: {
min={field.min} max={field.max} step={field.type === "float" ? 0.01 : 1} min={field.min} max={field.max} step={field.type === "float" ? 0.01 : 1}
onChange={(e) => onChange(e.target.value)} /> onChange={(e) => onChange(e.target.value)} />
{field.min != null && field.max != null && ( {field.min != null && field.max != null && (
<span className="shrink-0 text-[10.5px] tabular-nums text-muted">{field.min}~{field.max}</span> <span className="shrink-0 text-caption tabular-nums text-muted">{field.min}~{field.max}</span>
)} )}
</div> </div>
) : ( ) : (
<input id={id} className="input" value={value} onChange={(e) => onChange(e.target.value)} /> <input id={id} className="input" value={value} onChange={(e) => onChange(e.target.value)} />
)} )}
{field.help && <p className="mt-1 text-[11px] leading-relaxed text-muted">{field.help}</p>} {field.help && <p className="mt-1 text-caption leading-relaxed text-muted">{field.help}</p>}
<code className="mt-1 block font-mono text-[10px] text-muted/60">{field.key}</code> <code className="mt-1 block font-mono text-caption text-muted/60">{field.key}</code>
</div> </div>
); );
} }
...@@ -220,7 +220,7 @@ function OntologyCard({ onto, onSaved }: { onto: OntologyResponse; onSaved: () = ...@@ -220,7 +220,7 @@ function OntologyCard({ onto, onSaved }: { onto: OntologyResponse; onSaved: () =
</button> </button>
))} ))}
</div> </div>
<p className="mt-1.5 text-[11px] text-muted">「其他」是兜底类目,不可取消 —— 否则模型会自造类型。</p> <p className="mt-1.5 text-caption text-muted">「其他」是兜底类目,不可取消 —— 否则模型会自造类型。</p>
</div> </div>
<div> <div>
<p className="label">关系类型(已选 {rel.length} / {onto.available_relation_types.length})</p> <p className="label">关系类型(已选 {rel.length} / {onto.available_relation_types.length})</p>
......
...@@ -154,7 +154,7 @@ export function AskPanel({ dsId, dsName }: { dsId: number; dsName: string }) { ...@@ -154,7 +154,7 @@ export function AskPanel({ dsId, dsName }: { dsId: number; dsName: string }) {
</button> </button>
)} )}
</div> </div>
<p className="mt-1.5 text-[11.5px] text-muted"> <p className="mt-1.5 text-label text-muted">
Enter 提交,Shift + Enter 换行。所有查询都经过只读校验,并强制加上行数与超时限制。 Enter 提交,Shift + Enter 换行。所有查询都经过只读校验,并强制加上行数与超时限制。
</p> </p>
</Card> </Card>
...@@ -216,7 +216,7 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: { ...@@ -216,7 +216,7 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: {
return ( return (
<Card className="overflow-hidden"> <Card className="overflow-hidden">
<div className="flex items-start gap-2 border-b border-line bg-elevated/60 px-3.5 py-2.5"> <div className="flex items-start gap-2 border-b border-line bg-elevated/60 px-3.5 py-2.5">
<p className="min-w-0 flex-1 text-[14px] font-medium leading-snug">{turn.question}</p> <p className="min-w-0 flex-1 text-body font-medium leading-snug">{turn.question}</p>
{turn.running ? ( {turn.running ? (
<Badge tone="bg-brand/10 text-brand" className="shrink-0 tabular-nums"> <Badge tone="bg-brand/10 text-brand" className="shrink-0 tabular-nums">
<Loader2 className="h-3 w-3 animate-spin" /> <Loader2 className="h-3 w-3 animate-spin" />
...@@ -229,7 +229,7 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: { ...@@ -229,7 +229,7 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: {
<div className="space-y-2.5 p-3.5"> <div className="space-y-2.5 p-3.5">
{turn.running && ( {turn.running && (
<p className="flex items-center gap-2 text-[12.5px] text-muted"> <p className="flex items-center gap-2 text-label text-muted">
<span className="relative flex h-1.5 w-1.5 shrink-0"> <span className="relative flex h-1.5 w-1.5 shrink-0">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-brand opacity-70" /> <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-brand opacity-70" />
<span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-brand" /> <span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-brand" />
...@@ -240,16 +240,16 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: { ...@@ -240,16 +240,16 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: {
{turn.clarify && ( {turn.clarify && (
<div className="rounded-lg border border-warn/40 bg-warn/5 p-3"> <div className="rounded-lg border border-warn/40 bg-warn/5 p-3">
<p className="text-[13px] font-medium text-warn">需要你确认一下</p> <p className="text-body font-medium text-warn">需要你确认一下</p>
<p className="mt-1 text-[13px]">{turn.clarify}</p> <p className="mt-1 text-body">{turn.clarify}</p>
<ClarifyReply question={turn.question} onAsk={onAsk} /> <ClarifyReply question={turn.question} onAsk={onAsk} />
</div> </div>
)} )}
{awaitingPlan && turn.plan && ( {awaitingPlan && turn.plan && (
<div className="rounded-lg border border-brand/40 bg-brand/5 p-3"> <div className="rounded-lg border border-brand/40 bg-brand/5 p-3">
<p className="text-[13px] font-medium">确认查询计划后再生成 SQL</p> <p className="text-body font-medium">确认查询计划后再生成 SQL</p>
<p className="mt-1 text-[12.5px] text-muted">{turn.plan.summary}</p> <p className="mt-1 text-label text-muted">{turn.plan.summary}</p>
<button className="btn btn-primary btn-sm mt-2" <button className="btn btn-primary btn-sm mt-2"
onClick={() => ask({ question: turn.question, plan: turn.plan ?? undefined })}> onClick={() => ask({ question: turn.question, plan: turn.plan ?? undefined })}>
计划没问题,生成 SQL 计划没问题,生成 SQL
...@@ -260,7 +260,7 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: { ...@@ -260,7 +260,7 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: {
{/* 元数据问题(「有哪些表」「这个字段什么意思」)不会产出 SQL。 {/* 元数据问题(「有哪些表」「这个字段什么意思」)不会产出 SQL。
以前这类回答被整条丢掉,用户看到的是一张空卡片 —— 那正是"一大片空白"的来源。 */} 以前这类回答被整条丢掉,用户看到的是一张空卡片 —— 那正是"一大片空白"的来源。 */}
{turn.answer && ( {turn.answer && (
<div className="prose-answer text-[13.5px]"> <div className="prose-answer text-body">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{turn.answer}</ReactMarkdown> <ReactMarkdown remarkPlugins={[remarkGfm]}>{turn.answer}</ReactMarkdown>
</div> </div>
)} )}
...@@ -269,8 +269,8 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: { ...@@ -269,8 +269,8 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: {
<div className="flex items-start gap-2 rounded-lg border border-bad/40 bg-bad/5 px-3 py-2.5"> <div className="flex items-start gap-2 rounded-lg border border-bad/40 bg-bad/5 px-3 py-2.5">
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-bad" /> <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-bad" />
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="text-[13px] leading-relaxed text-bad">{turn.error}</p> <p className="text-body leading-relaxed text-bad">{turn.error}</p>
<p className="mt-1 text-[11.5px] text-muted"> <p className="mt-1 text-label text-muted">
可以换个说法再问一次,或展开下面的 SQL 自己改完重跑。 可以换个说法再问一次,或展开下面的 SQL 自己改完重跑。
</p> </p>
</div> </div>
...@@ -283,16 +283,16 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: { ...@@ -283,16 +283,16 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: {
{/* 结论放在最前面。用户问的是业务问题,SQL 和轨迹是给他验算用的 */} {/* 结论放在最前面。用户问的是业务问题,SQL 和轨迹是给他验算用的 */}
{(turn.summary || turn.summarizing) && ( {(turn.summary || turn.summarizing) && (
<div className="rounded-lg border border-brand/20 bg-brand/[0.04] p-3"> <div className="rounded-lg border border-brand/20 bg-brand/[0.04] p-3">
<p className="mb-1 flex items-center gap-1.5 text-[11.5px] font-medium uppercase tracking-wide text-brand"> <p className="mb-1 flex items-center gap-1.5 text-label font-medium uppercase tracking-wide text-brand">
结论 结论
{turn.summarizing && <Loader2 className="h-3 w-3 animate-spin" />} {turn.summarizing && <Loader2 className="h-3 w-3 animate-spin" />}
</p> </p>
{turn.summary ? ( {turn.summary ? (
<div className="prose-answer text-[13.5px]"> <div className="prose-answer text-body">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{turn.summary}</ReactMarkdown> <ReactMarkdown remarkPlugins={[remarkGfm]}>{turn.summary}</ReactMarkdown>
</div> </div>
) : ( ) : (
<p className="text-[12.5px] text-muted">数据已经换了,正在重新给结论…</p> <p className="text-label text-muted">数据已经换了,正在重新给结论…</p>
)} )}
</div> </div>
)} )}
...@@ -302,7 +302,7 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: { ...@@ -302,7 +302,7 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: {
truncated={turn.truncated} question={turn.question} /> truncated={turn.truncated} question={turn.question} />
)} )}
{!hasResult && turn.outcome === "ok" && !turn.running && ( {!hasResult && turn.outcome === "ok" && !turn.running && (
<p className="rounded-lg border border-line px-3 py-4 text-center text-[13px] text-muted"> <p className="rounded-lg border border-line px-3 py-4 text-center text-body text-muted">
查询成功,但没有符合条件的数据。多半是过滤条件太严或时间范围不对。 查询成功,但没有符合条件的数据。多半是过滤条件太严或时间范围不对。
</p> </p>
)} )}
...@@ -326,7 +326,7 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: { ...@@ -326,7 +326,7 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: {
{turn.draftSql ? ( {turn.draftSql ? (
// 流式阶段用 pre:CodeMirror 每个 token 重建编辑器状态,几十次/秒会明显卡 // 流式阶段用 pre:CodeMirror 每个 token 重建编辑器状态,几十次/秒会明显卡
<pre className="max-h-[260px] overflow-auto rounded-md bg-ink/[0.05] p-2.5 <pre className="max-h-[260px] overflow-auto rounded-md bg-ink/[0.05] p-2.5
font-mono text-[12px] leading-relaxed"> font-mono text-label leading-relaxed">
{turn.draftSql} {turn.draftSql}
<span className="ml-0.5 inline-block h-3.5 w-1.5 animate-pulse bg-brand align-middle" /> <span className="ml-0.5 inline-block h-3.5 w-1.5 animate-pulse bg-brand align-middle" />
</pre> </pre>
...@@ -345,7 +345,7 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: { ...@@ -345,7 +345,7 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: {
{turn.issues.length > 0 && ( {turn.issues.length > 0 && (
<ul className="mt-1.5 space-y-0.5"> <ul className="mt-1.5 space-y-0.5">
{turn.issues.map((it, i) => ( {turn.issues.map((it, i) => (
<li key={i} className={cn("text-[11.5px]", <li key={i} className={cn("text-label",
it.level === "error" ? "text-bad" : "text-warn")}> it.level === "error" ? "text-bad" : "text-warn")}>
{it.msg}{it.fix && <span className="text-muted"> — {it.fix}</span>} {it.msg}{it.fix && <span className="text-muted"> — {it.fix}</span>}
</li> </li>
...@@ -377,11 +377,11 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: { ...@@ -377,11 +377,11 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: {
title="这条 SQL 在做什么" title="这条 SQL 在做什么"
summary="用业务语言说一遍,不用懂 SQL 也能核对"> summary="用业务语言说一遍,不用懂 SQL 也能核对">
{turn.explain ? ( {turn.explain ? (
<div className="prose-answer text-[13px]"> <div className="prose-answer text-body">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{turn.explain}</ReactMarkdown> <ReactMarkdown remarkPlugins={[remarkGfm]}>{turn.explain}</ReactMarkdown>
</div> </div>
) : ( ) : (
<p className="flex items-center gap-2 text-[12.5px] text-muted"> <p className="flex items-center gap-2 text-label text-muted">
<Loader2 className="h-3.5 w-3.5 animate-spin" /> 正在翻译成业务语言… <Loader2 className="h-3.5 w-3.5 animate-spin" /> 正在翻译成业务语言…
</p> </p>
)} )}
...@@ -400,9 +400,9 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: { ...@@ -400,9 +400,9 @@ const TurnCard = memo(function TurnCard({ turn, onAsk }: {
{suggestions.length > 0 && !turn.running && ( {suggestions.length > 0 && !turn.running && (
<div className="flex flex-wrap items-center gap-1.5 pt-0.5"> <div className="flex flex-wrap items-center gap-1.5 pt-0.5">
<span className="text-[11.5px] text-muted">接着问:</span> <span className="text-label text-muted">接着问:</span>
{suggestions.map((s) => ( {suggestions.map((s) => (
<button key={s} className="chip text-[11.5px]" onClick={() => onAsk(s)}> <button key={s} className="chip text-label" onClick={() => onAsk(s)}>
<Send className="h-3 w-3 text-muted" />{s} <Send className="h-3 w-3 text-muted" />{s}
</button> </button>
))} ))}
...@@ -423,7 +423,7 @@ function ClarifyReply({ question, onAsk }: { question: string; onAsk: (q: string ...@@ -423,7 +423,7 @@ function ClarifyReply({ question, onAsk }: { question: string; onAsk: (q: string
}; };
return ( return (
<div className="mt-2 flex items-center gap-1.5"> <div className="mt-2 flex items-center gap-1.5">
<input className="input py-1 text-[12.5px]" placeholder="在这儿补一句,比如「按自然月,只看问界」" <input className="input py-1 text-label" placeholder="在这儿补一句,比如「按自然月,只看问界」"
value={text} onChange={(e) => setText(e.target.value)} value={text} onChange={(e) => setText(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter" && !e.nativeEvent.isComposing) send(); }} /> onKeyDown={(e) => { if (e.key === "Enter" && !e.nativeEvent.isComposing) send(); }} />
<button className="btn btn-sm shrink-0" disabled={!text.trim()} onClick={send}> <button className="btn btn-sm shrink-0" disabled={!text.trim()} onClick={send}>
...@@ -511,7 +511,7 @@ function ResultTable({ columns, rows, truncated, question }: { ...@@ -511,7 +511,7 @@ function ResultTable({ columns, rows, truncated, question }: {
return ( return (
<div> <div>
<div className="mb-1.5 flex flex-wrap items-center gap-1.5 text-[12px] text-muted"> <div className="mb-1.5 flex flex-wrap items-center gap-1.5 text-label text-muted">
<span className="font-medium">结果</span> <span className="font-medium">结果</span>
<Badge tone="bg-ok/10 text-ok">{rows.length} 行 × {columns.length} 列</Badge> <Badge tone="bg-ok/10 text-ok">{rows.length} 行 × {columns.length} 列</Badge>
{truncated && <Badge tone="bg-warn/10 text-warn">已达行数上限,结果被截断</Badge>} {truncated && <Badge tone="bg-warn/10 text-warn">已达行数上限,结果被截断</Badge>}
...@@ -523,7 +523,7 @@ function ResultTable({ columns, rows, truncated, question }: { ...@@ -523,7 +523,7 @@ function ResultTable({ columns, rows, truncated, question }: {
</div> </div>
{/* 宽表一律横向滚动,别把整页撑出横向滚动条 */} {/* 宽表一律横向滚动,别把整页撑出横向滚动条 */}
<div className="max-h-[420px] overflow-auto rounded-lg border border-line"> <div className="max-h-[420px] overflow-auto rounded-lg border border-line">
<table className="w-full border-collapse text-[12.5px]"> <table className="w-full border-collapse text-label">
<thead className="sticky top-0 z-10"> <thead className="sticky top-0 z-10">
<tr className="bg-elevated"> <tr className="bg-elevated">
{columns.map((c) => ( {columns.map((c) => (
......
...@@ -119,7 +119,7 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged, onOpenApi }: ...@@ -119,7 +119,7 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged, onOpenApi }:
{!cryptoReady && ( {!cryptoReady && (
<div className="card flex items-start gap-2.5 border-warn/40 bg-warn/5 p-3"> <div className="card flex items-start gap-2.5 border-warn/40 bg-warn/5 p-3">
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-warn" /> <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-warn" />
<div className="text-[13px] leading-relaxed"> <div className="text-body leading-relaxed">
<p className="font-medium">未配置 SECRET_KEY,暂时不能添加数据源。</p> <p className="font-medium">未配置 SECRET_KEY,暂时不能添加数据源。</p>
<p className="mt-0.5 text-muted"> <p className="mt-0.5 text-muted">
业务库口令必须加密存储。请在 <code className="rounded bg-ink/[0.07] px-1">.env</code> 里加一行 业务库口令必须加密存储。请在 <code className="rounded bg-ink/[0.07] px-1">.env</code> 里加一行
...@@ -152,7 +152,7 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged, onOpenApi }: ...@@ -152,7 +152,7 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged, onOpenApi }:
<div className="flex flex-col gap-2 sm:flex-row sm:items-start"> <div className="flex flex-col gap-2 sm:flex-row sm:items-start">
<button className="min-w-0 flex-1 text-left" onClick={() => onSelect(ds.id)}> <button className="min-w-0 flex-1 text-left" onClick={() => onSelect(ds.id)}>
<span className="flex flex-wrap items-center gap-1.5"> <span className="flex flex-wrap items-center gap-1.5">
<span className="truncate text-[13.5px] font-medium">{ds.name}</span> <span className="truncate text-body font-medium">{ds.name}</span>
{selectedId === ds.id && <Badge tone="bg-brand/10 text-brand">当前</Badge>} {selectedId === ds.id && <Badge tone="bg-brand/10 text-brand">当前</Badge>}
{ds.status === "ok" && <Badge tone="bg-ok/10 text-ok">已连通</Badge>} {ds.status === "ok" && <Badge tone="bg-ok/10 text-ok">已连通</Badge>}
{ds.status === "error" && <Badge tone="bg-bad/10 text-bad">连接异常</Badge>} {ds.status === "error" && <Badge tone="bg-bad/10 text-bad">连接异常</Badge>}
...@@ -161,17 +161,17 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged, onOpenApi }: ...@@ -161,17 +161,17 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged, onOpenApi }:
<span title="按只读方式使用"><ShieldCheck className="h-3.5 w-3.5 text-ok" /></span> <span title="按只读方式使用"><ShieldCheck className="h-3.5 w-3.5 text-ok" /></span>
)} )}
</span> </span>
<span className="mt-0.5 block truncate font-mono text-[11.5px] text-muted"> <span className="mt-0.5 block truncate font-mono text-label text-muted">
<Badge className="mr-1.5 font-sans">{TYPE_LABEL[ds.ds_type] || ds.ds_type}</Badge> <Badge className="mr-1.5 font-sans">{TYPE_LABEL[ds.ds_type] || ds.ds_type}</Badge>
{ds.ds_type === "sqlite" ? "上传文件导入的只读库" : `${ds.username}@${ds.host}:${ds.port}/${ds.db_name}`} {ds.ds_type === "sqlite" ? "上传文件导入的只读库" : `${ds.username}@${ds.host}:${ds.port}/${ds.db_name}`}
</span> </span>
<span className="mt-0.5 block text-[11.5px] text-muted"> <span className="mt-0.5 block text-label text-muted">
{ds.last_introspect_at {ds.last_introspect_at
? `上次内省 ${formatTime(ds.last_introspect_at)}` ? `上次内省 ${formatTime(ds.last_introspect_at)}`
: "还没有内省过 —— 内省一次才能开始提问"} : "还没有内省过 —— 内省一次才能开始提问"}
</span> </span>
{ds.status === "error" && ds.last_error && ( {ds.status === "error" && ds.last_error && (
<span className="mt-0.5 block truncate text-[11.5px] text-bad" title={ds.last_error}> <span className="mt-0.5 block truncate text-label text-bad" title={ds.last_error}>
{ds.last_error} {ds.last_error}
</span> </span>
)} )}
...@@ -204,7 +204,7 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged, onOpenApi }: ...@@ -204,7 +204,7 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged, onOpenApi }:
{job?.dsId === ds.id && job.item && ( {job?.dsId === ds.id && job.item && (
<div className="mt-2.5"> <div className="mt-2.5">
<Progress value={job.item.progress} /> <Progress value={job.item.progress} />
<p className="mt-1 text-[11.5px] text-muted">{job.item.message || "处理中…"}</p> <p className="mt-1 text-label text-muted">{job.item.message || "处理中…"}</p>
</div> </div>
)} )}
</div> </div>
...@@ -218,7 +218,7 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged, onOpenApi }: ...@@ -218,7 +218,7 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged, onOpenApi }:
<div className="space-y-3"> <div className="space-y-3">
{[...new Set(KINDS.map((k) => k.group))].map((g) => ( {[...new Set(KINDS.map((k) => k.group))].map((g) => (
<div key={g}> <div key={g}>
<p className="mb-1.5 text-[11.5px] font-medium text-muted">{g}</p> <p className="mb-1.5 text-label font-medium text-muted">{g}</p>
<div className="grid gap-2 sm:grid-cols-2"> <div className="grid gap-2 sm:grid-cols-2">
{KINDS.filter((k) => k.group === g).map((k) => ( {KINDS.filter((k) => k.group === g).map((k) => (
<button key={k.key} disabled={k.soon || (!cryptoReady && !!k.port)} <button key={k.key} disabled={k.soon || (!cryptoReady && !!k.port)}
...@@ -231,8 +231,8 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged, onOpenApi }: ...@@ -231,8 +231,8 @@ export function DataSourcePanel({ selectedId, onSelect, onChanged, onOpenApi }:
}}> }}>
<span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-brand/10 text-brand"> <span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-brand/10 text-brand">
{k.key === "api" ? <Globe className="h-4 w-4" /> : k.key === "file" ? <FileSpreadsheet className="h-4 w-4" /> : <Database className="h-4 w-4" />}</span> {k.key === "api" ? <Globe className="h-4 w-4" /> : k.key === "file" ? <FileSpreadsheet className="h-4 w-4" /> : <Database className="h-4 w-4" />}</span>
<span className="min-w-0"><span className="block text-[13px] font-medium">{k.label}</span> <span className="min-w-0"><span className="block text-body font-medium">{k.label}</span>
<span className="block text-[11.5px] text-muted">{k.desc}{k.port ? ` · 默认端口 ${k.port}` : ""}</span></span> <span className="block text-label text-muted">{k.desc}{k.port ? ` · 默认端口 ${k.port}` : ""}</span></span>
</button> </button>
))} ))}
</div> </div>
...@@ -327,7 +327,7 @@ function DataSourceForm({ open, creating, initial, onClose, onSaved }: { ...@@ -327,7 +327,7 @@ function DataSourceForm({ open, creating, initial, onClose, onSaved }: {
desc="保存后自动测试连接、读取表结构;接着到「业务建模」让 AI 按业务文档起草本体。" desc="保存后自动测试连接、读取表结构;接着到「业务建模」让 AI 按业务文档起草本体。"
footer={ footer={
<> <>
{err && <p className="mr-auto min-w-0 flex-1 text-[12.5px] text-bad">{err}</p>} {err && <p className="mr-auto min-w-0 flex-1 text-label text-bad">{err}</p>}
<button className="btn btn-sm" onClick={onClose}>取消</button> <button className="btn btn-sm" onClick={onClose}>取消</button>
<button className="btn btn-primary btn-sm" disabled={!ok || saving} onClick={save}> <button className="btn btn-primary btn-sm" disabled={!ok || saving} onClick={save}>
{saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />} {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
...@@ -343,7 +343,7 @@ function DataSourceForm({ open, creating, initial, onClose, onSaved }: { ...@@ -343,7 +343,7 @@ function DataSourceForm({ open, creating, initial, onClose, onSaved }: {
</Field> </Field>
<div className="space-y-3 rounded-lg border border-line bg-elevated/50 p-3"> <div className="space-y-3 rounded-lg border border-line bg-elevated/50 p-3">
<p className="text-[12px] font-medium text-muted">连接信息</p> <p className="text-label font-medium text-muted">连接信息</p>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]"> <div className="grid grid-cols-1 gap-3 sm:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
<Field label="主机" required> <Field label="主机" required>
<input className="input" value={form.host} placeholder="192.168.x.x" <input className="input" value={form.host} placeholder="192.168.x.x"
...@@ -384,14 +384,14 @@ function DataSourceForm({ open, creating, initial, onClose, onSaved }: { ...@@ -384,14 +384,14 @@ function DataSourceForm({ open, creating, initial, onClose, onSaved }: {
onChange={(e) => set("tables", e.target.value)} /> onChange={(e) => set("tables", e.target.value)} />
</Field> </Field>
<label className="flex items-start gap-2 rounded-lg border border-line p-3 text-[12.5px]"> <label className="flex items-start gap-2 rounded-lg border border-line p-3 text-label">
<input type="checkbox" className="mt-0.5" checked={form.writeback} onChange={(e) => set("writeback", e.target.checked)} /> <input type="checkbox" className="mt-0.5" checked={form.writeback} onChange={(e) => set("writeback", e.target.checked)} />
<span><span className="font-medium">允许审批通过的动作写回业务库</span> <span><span className="font-medium">允许审批通过的动作写回业务库</span>
<span className="block text-[11.5px] text-muted">打开后,「新建采购单」「改状态」这类动作在人工审批通过后直接写进业务表(只限已绑定的表和列,可撤销); <span className="block text-label text-muted">打开后,「新建采购单」「改状态」这类动作在人工审批通过后直接写进业务表(只限已绑定的表和列,可撤销);
关闭时只写在本系统的写回层,业务库不动。需要账号有写权限。</span></span> 关闭时只写在本系统的写回层,业务库不动。需要账号有写权限。</span></span>
</label> </label>
<p className="text-[11.5px] leading-relaxed text-muted"> <p className="text-label leading-relaxed text-muted">
保存后会自动测试连接并读取表结构。PostgreSQL 需要服务器装有 psycopg2 驱动。 保存后会自动测试连接并读取表结构。PostgreSQL 需要服务器装有 psycopg2 驱动。
</p> </p>
</div> </div>
...@@ -425,7 +425,7 @@ function FileSourceForm({ ds, onClose, onSaved }: { ds: DataSource | null; onClo ...@@ -425,7 +425,7 @@ function FileSourceForm({ ds, onClose, onSaved }: { ds: DataSource | null; onClo
<input type="file" multiple accept=".csv,.tsv,.xlsx,.xlsm,.json" className="input" <input type="file" multiple accept=".csv,.tsv,.xlsx,.xlsm,.json" className="input"
onChange={(e) => setFiles(Array.from(e.target.files || []))} /> onChange={(e) => setFiles(Array.from(e.target.files || []))} />
</Field> </Field>
{files.map((f) => <p key={f.name} className="text-[12px] text-muted">{f.name} · {Math.ceil(f.size / 1024)} KB</p>)} {files.map((f) => <p key={f.name} className="text-label text-muted">{f.name} · {Math.ceil(f.size / 1024)} KB</p>)}
</div> </div>
</Modal> </Modal>
); );
......
...@@ -124,7 +124,7 @@ export function LibraryPanel({ dsId }: { dsId: number }) { ...@@ -124,7 +124,7 @@ export function LibraryPanel({ dsId }: { dsId: number }) {
</div> </div>
{!status && (counts.verified > 0 || counts.draft > 0) && ( {!status && (counts.verified > 0 || counts.draft > 0) && (
<p className="border-b border-line bg-elevated/60 px-4 py-1.5 text-[11.5px] text-muted"> <p className="border-b border-line bg-elevated/60 px-4 py-1.5 text-label text-muted">
<span className="text-ok">{counts.verified} 条正在参与生成</span> <span className="text-ok">{counts.verified} 条正在参与生成</span>
{counts.draft > 0 && <> · {counts.draft} 条草稿等你确认,确认之后才会生效</>} {counts.draft > 0 && <> · {counts.draft} 条草稿等你确认,确认之后才会生效</>}
</p> </p>
...@@ -144,7 +144,7 @@ export function LibraryPanel({ dsId }: { dsId: number }) { ...@@ -144,7 +144,7 @@ export function LibraryPanel({ dsId }: { dsId: number }) {
p.status === "deprecated" && "opacity-55")}> p.status === "deprecated" && "opacity-55")}>
<button className="min-w-0 flex-1 text-left" onClick={() => setDetail(p)}> <button className="min-w-0 flex-1 text-left" onClick={() => setDetail(p)}>
<span className="flex flex-wrap items-center gap-1.5"> <span className="flex flex-wrap items-center gap-1.5">
<span className="min-w-0 truncate text-[13.5px] font-medium">{p.question}</span> <span className="min-w-0 truncate text-body font-medium">{p.question}</span>
<Badge tone={STATUS_META[p.status]?.tone}> <Badge tone={STATUS_META[p.status]?.tone}>
{STATUS_META[p.status]?.label ?? p.status} {STATUS_META[p.status]?.label ?? p.status}
</Badge> </Badge>
...@@ -157,7 +157,7 @@ export function LibraryPanel({ dsId }: { dsId: number }) { ...@@ -157,7 +157,7 @@ export function LibraryPanel({ dsId }: { dsId: number }) {
</span> </span>
{/* SQL 只给一行预览。要看全文点开详情 —— 几十条代码块摊在列表里 {/* SQL 只给一行预览。要看全文点开详情 —— 几十条代码块摊在列表里
只会把真正要管的状态信息淹掉 */} 只会把真正要管的状态信息淹掉 */}
<span className="mt-0.5 block truncate font-mono text-[11px] text-muted"> <span className="mt-0.5 block truncate font-mono text-caption text-muted">
{p.sql.replace(/\s+/g, " ").trim()} {p.sql.replace(/\s+/g, " ").trim()}
</span> </span>
</button> </button>
...@@ -187,7 +187,7 @@ export function LibraryPanel({ dsId }: { dsId: number }) { ...@@ -187,7 +187,7 @@ export function LibraryPanel({ dsId }: { dsId: number }) {
desc={detail ? STATUS_META[detail.status]?.hint : undefined} desc={detail ? STATUS_META[detail.status]?.hint : undefined}
footer={detail && ( footer={detail && (
<> <>
<span className="mr-auto text-[11.5px] text-muted"> <span className="mr-auto text-label text-muted">
{SOURCE_TEXT[detail.source] ?? detail.source} · {formatTime(detail.created_at)} {SOURCE_TEXT[detail.source] ?? detail.source} · {formatTime(detail.created_at)}
</span> </span>
{detail.status !== "verified" ? ( {detail.status !== "verified" ? (
...@@ -220,22 +220,22 @@ export function LibraryPanel({ dsId }: { dsId: number }) { ...@@ -220,22 +220,22 @@ export function LibraryPanel({ dsId }: { dsId: number }) {
<div> <div>
<div className="mb-1 flex items-center gap-1.5"> <div className="mb-1 flex items-center gap-1.5">
<span className="text-[12px] font-medium text-muted">实际执行的 SQL</span> <span className="text-label font-medium text-muted">实际执行的 SQL</span>
<span className="flex-1" /> <span className="flex-1" />
<CopyButton text={detail.sql} /> <CopyButton text={detail.sql} />
</div> </div>
<pre className="overflow-x-auto rounded-md bg-ink/[0.05] p-2.5 font-mono <pre className="overflow-x-auto rounded-md bg-ink/[0.05] p-2.5 font-mono
text-[11.5px] leading-relaxed">{detail.sql}</pre> text-label leading-relaxed">{detail.sql}</pre>
</div> </div>
{detail.sql_before && ( {detail.sql_before && (
<div> <div>
<p className="mb-1 text-[12px] font-medium text-muted"> <p className="mb-1 text-label font-medium text-muted">
模型原本生成的版本(被人工改掉了) 模型原本生成的版本(被人工改掉了)
</p> </p>
<pre className="overflow-x-auto rounded-md bg-bad/[0.06] p-2.5 font-mono <pre className="overflow-x-auto rounded-md bg-bad/[0.06] p-2.5 font-mono
text-[11.5px] leading-relaxed">{detail.sql_before}</pre> text-label leading-relaxed">{detail.sql_before}</pre>
<p className="mt-1 text-[11.5px] text-muted"> <p className="mt-1 text-label text-muted">
这种「改过才跑通」的记录最值钱:它直接标出了模型的系统性偏差。 这种「改过才跑通」的记录最值钱:它直接标出了模型的系统性偏差。
采纳之后,同类问题会照着改后的版本生成。 采纳之后,同类问题会照着改后的版本生成。
</p> </p>
......
...@@ -63,12 +63,12 @@ export function MappingPanel({ dsId, canEdit }: { dsId: number; canEdit: boolean ...@@ -63,12 +63,12 @@ export function MappingPanel({ dsId, canEdit }: { dsId: number; canEdit: boolean
const isOpen = open.has(m.id); const isOpen = open.has(m.id);
return ( return (
<div key={m.id}> <div key={m.id}>
<div className="flex items-center gap-2 px-4 py-2 text-[12.5px]"> <div className="flex items-center gap-2 px-4 py-2 text-label">
<button className="text-muted" onClick={() => { const n = new Set(open); if (isOpen) n.delete(m.id); else n.add(m.id); setOpen(n); }}> <button className="text-muted" onClick={() => { const n = new Set(open); if (isOpen) n.delete(m.id); else n.add(m.id); setOpen(n); }}>
{isOpen ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}</button> {isOpen ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}</button>
<span className="font-mono font-medium">{m.name}</span> <span className="font-mono font-medium">{m.name}</span>
<span className="min-w-0 flex-1 truncate text-muted">{m.description || ""}</span> <span className="min-w-0 flex-1 truncate text-muted">{m.description || ""}</span>
<span className="w-14 text-right text-[11px] text-muted">{m.columns?.length || 0} 列</span> <span className="w-14 text-right text-caption text-muted">{m.columns?.length || 0} 列</span>
{!m.enabled && <Badge>未启用</Badge>} {!m.enabled && <Badge>未启用</Badge>}
{hit.length ? hit.map((h) => ( {hit.length ? hit.map((h) => (
<button key={h.concept_id} className="chip text-ok" onClick={() => go("b_object", { id: h.concept_id })}> <button key={h.concept_id} className="chip text-ok" onClick={() => go("b_object", { id: h.concept_id })}>
...@@ -81,7 +81,7 @@ export function MappingPanel({ dsId, canEdit }: { dsId: number; canEdit: boolean ...@@ -81,7 +81,7 @@ export function MappingPanel({ dsId, canEdit }: { dsId: number; canEdit: boolean
{isOpen && ( {isOpen && (
<div className="flex flex-wrap gap-1 bg-ink/[0.02] px-10 py-2"> <div className="flex flex-wrap gap-1 bg-ink/[0.02] px-10 py-2">
{(m.columns || []).map((c) => ( {(m.columns || []).map((c) => (
<span key={c.id} className="rounded border border-line bg-surface px-1.5 py-0.5 font-mono text-[11px]" title={c.description}> <span key={c.id} className="rounded border border-line bg-surface px-1.5 py-0.5 font-mono text-caption" title={c.description}>
{c.name}<span className="ml-1 text-muted">{c.data_type}</span></span> {c.name}<span className="ml-1 text-muted">{c.data_type}</span></span>
))} ))}
</div> </div>
...@@ -91,7 +91,7 @@ export function MappingPanel({ dsId, canEdit }: { dsId: number; canEdit: boolean ...@@ -91,7 +91,7 @@ export function MappingPanel({ dsId, canEdit }: { dsId: number; canEdit: boolean
})} })}
</div> </div>
)} )}
<p className="flex items-center gap-1.5 border-t border-line px-4 py-2 text-[11.5px] text-muted"><Boxes className="h-3.5 w-3.5" /> <p className="flex items-center gap-1.5 border-t border-line px-4 py-2 text-label text-muted"><Boxes className="h-3.5 w-3.5" />
也可以在「业务建模」里让 AI 一次把所有已启用的表提议成对象与关系。</p> 也可以在「业务建模」里让 AI 一次把所有已启用的表提议成对象与关系。</p>
</Card> </Card>
); );
......
...@@ -144,7 +144,7 @@ export function ModelingPanel({ dsId }: { dsId: number }) { ...@@ -144,7 +144,7 @@ export function ModelingPanel({ dsId }: { dsId: number }) {
<input className="input pl-8" placeholder="搜表名、列名或描述" <input className="input pl-8" placeholder="搜表名、列名或描述"
value={keyword} onChange={(e) => setKeyword(e.target.value)} /> value={keyword} onChange={(e) => setKeyword(e.target.value)} />
</div> </div>
<label className="flex shrink-0 cursor-pointer items-center gap-1.5 text-[12.5px] text-muted"> <label className="flex shrink-0 cursor-pointer items-center gap-1.5 text-label text-muted">
<input type="checkbox" checked={onlyEnabled} <input type="checkbox" checked={onlyEnabled}
onChange={(e) => setOnlyEnabled(e.target.checked)} /> onChange={(e) => setOnlyEnabled(e.target.checked)} />
只看已启用 只看已启用
...@@ -164,12 +164,12 @@ export function ModelingPanel({ dsId }: { dsId: number }) { ...@@ -164,12 +164,12 @@ export function ModelingPanel({ dsId }: { dsId: number }) {
{busy && job && ( {busy && job && (
<div className="border-b border-line px-4 py-2"> <div className="border-b border-line px-4 py-2">
<Progress value={job.progress} /> <Progress value={job.progress} />
<p className="mt-1 text-[11.5px] text-muted">{job.message || "起草中…"}</p> <p className="mt-1 text-label text-muted">{job.message || "起草中…"}</p>
</div> </div>
)} )}
{enabledCount === 0 && ( {enabledCount === 0 && (
<p className="border-b border-line bg-warn/5 px-4 py-2 text-[12.5px] text-warn"> <p className="border-b border-line bg-warn/5 px-4 py-2 text-label text-warn">
一张表都没启用,现在还问不了。勾选几张真正要查的表再去「问答」页。 一张表都没启用,现在还问不了。勾选几张真正要查的表再去「问答」页。
</p> </p>
)} )}
...@@ -178,7 +178,7 @@ export function ModelingPanel({ dsId }: { dsId: number }) { ...@@ -178,7 +178,7 @@ export function ModelingPanel({ dsId }: { dsId: number }) {
<div className="grid h-[min(62vh,620px)] grid-cols-1 md:grid-cols-[minmax(0,280px)_minmax(0,1fr)]"> <div className="grid h-[min(62vh,620px)] grid-cols-1 md:grid-cols-[minmax(0,280px)_minmax(0,1fr)]">
<div className="min-h-0 overflow-auto border-b border-line md:border-b-0 md:border-r"> <div className="min-h-0 overflow-auto border-b border-line md:border-b-0 md:border-r">
{shown.length === 0 ? ( {shown.length === 0 ? (
<p className="px-4 py-6 text-center text-[13px] text-muted">没有匹配的表</p> <p className="px-4 py-6 text-center text-body text-muted">没有匹配的表</p>
) : ( ) : (
shown.map((m) => ( shown.map((m) => (
<div key={m.id} <div key={m.id}
...@@ -190,14 +190,14 @@ export function ModelingPanel({ dsId }: { dsId: number }) { ...@@ -190,14 +190,14 @@ export function ModelingPanel({ dsId }: { dsId: number }) {
title={m.enabled ? "停用后不再参与问答" : "启用后才能被查询"} /> title={m.enabled ? "停用后不再参与问答" : "启用后才能被查询"} />
<button className="min-w-0 flex-1 text-left" onClick={() => setActiveId(m.id)}> <button className="min-w-0 flex-1 text-left" onClick={() => setActiveId(m.id)}>
<span className="flex items-center gap-1.5"> <span className="flex items-center gap-1.5">
<span className="truncate font-mono text-[12.5px]">{m.physical_table}</span> <span className="truncate font-mono text-label">{m.physical_table}</span>
{m.kind === "view" && <Badge>视图</Badge>} {m.kind === "view" && <Badge>视图</Badge>}
</span> </span>
<span className="mt-0.5 block truncate text-[11px] text-muted"> <span className="mt-0.5 block truncate text-caption text-muted">
{m.description || "(无表说明)"} {m.description || "(无表说明)"}
</span> </span>
</button> </button>
<span className="shrink-0 text-[11px] tabular-nums text-muted">{m.columns.length}</span> <span className="shrink-0 text-caption tabular-nums text-muted">{m.columns.length}</span>
</div> </div>
)) ))
)} )}
...@@ -238,24 +238,24 @@ function ModelDetail({ model, onColumnSaved }: { ...@@ -238,24 +238,24 @@ function ModelDetail({ model, onColumnSaved }: {
<div> <div>
<div className="sticky top-0 z-10 border-b border-line bg-surface px-4 py-2.5"> <div className="sticky top-0 z-10 border-b border-line bg-surface px-4 py-2.5">
<div className="flex flex-wrap items-center gap-1.5"> <div className="flex flex-wrap items-center gap-1.5">
<span className="font-mono text-[13px] font-medium">{model.physical_table}</span> <span className="font-mono text-body font-medium">{model.physical_table}</span>
{model.enabled {model.enabled
? <Badge tone="bg-ok/10 text-ok"><CheckCircle2 className="h-3 w-3" />参与问答</Badge> ? <Badge tone="bg-ok/10 text-ok"><CheckCircle2 className="h-3 w-3" />参与问答</Badge>
: <Badge tone="bg-ink/5 text-muted">已停用</Badge>} : <Badge tone="bg-ink/5 text-muted">已停用</Badge>}
<span className="flex-1" /> <span className="flex-1" />
<div className="relative w-40"> <div className="relative w-40">
<Search className="pointer-events-none absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-muted" /> <Search className="pointer-events-none absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-muted" />
<input className="input py-1 pl-7 text-[12px]" placeholder="筛选列" <input className="input py-1 pl-7 text-label" placeholder="筛选列"
value={filter} onChange={(e) => setFilter(e.target.value)} /> value={filter} onChange={(e) => setFilter(e.target.value)} />
</div> </div>
</div> </div>
<p className="mt-1 text-[11.5px] text-muted"> <p className="mt-1 text-label text-muted">
{model.description || "(还没写表说明,AI 起草或手填都行)"} {model.description || "(还没写表说明,AI 起草或手填都行)"}
</p> </p>
<p className="mt-0.5 text-[11px] text-muted"> <p className="mt-0.5 text-caption text-muted">
「业务说明」可以直接改,它会原样进提示词,是这一页里对准确率影响最大的东西。 「业务说明」可以直接改,它会原样进提示词,是这一页里对准确率影响最大的东西。
</p> </p>
<p className="mt-0.5 flex flex-wrap gap-x-3 text-[11px] text-muted"> <p className="mt-0.5 flex flex-wrap gap-x-3 text-caption text-muted">
<span>{model.columns.length} 列</span> <span>{model.columns.length} 列</span>
{sampled > 0 && <span>{sampled} 个枚举列有取值样例</span>} {sampled > 0 && <span>{sampled} 个枚举列有取值样例</span>}
{empties > 0 && <span className="text-bad">{empties} 个整列全空,已自动停用</span>} {empties > 0 && <span className="text-bad">{empties} 个整列全空,已自动停用</span>}
...@@ -266,7 +266,7 @@ function ModelDetail({ model, onColumnSaved }: { ...@@ -266,7 +266,7 @@ function ModelDetail({ model, onColumnSaved }: {
{/* 表头一律不换行并给死宽度:右栏本来就窄,让「说明(可编辑,直接影响…)」 {/* 表头一律不换行并给死宽度:右栏本来就窄,让「说明(可编辑,直接影响…)」
这种长表头自由换行,四个字的列名会被挤成三行 */} 这种长表头自由换行,四个字的列名会被挤成三行 */}
<table className="w-full table-fixed text-[12.5px]"> <table className="w-full table-fixed text-label">
<thead> <thead>
<tr className="text-left text-muted [&>th]:whitespace-nowrap [&>th]:py-1.5 [&>th]:font-medium"> <tr className="text-left text-muted [&>th]:whitespace-nowrap [&>th]:py-1.5 [&>th]:font-medium">
<th className="w-[18%] px-4">列</th> <th className="w-[18%] px-4">列</th>
...@@ -312,7 +312,7 @@ function ColumnRow({ column, onSaved }: { column: SmColumn; onSaved: (c: SmColum ...@@ -312,7 +312,7 @@ function ColumnRow({ column, onSaved }: { column: SmColumn; onSaved: (c: SmColum
<td className="truncate py-1.5 pr-3 text-muted" title={column.data_type}>{column.data_type}</td> <td className="truncate py-1.5 pr-3 text-muted" title={column.data_type}>{column.data_type}</td>
<td className="w-[36%] py-1.5 pr-3"> <td className="w-[36%] py-1.5 pr-3">
<div className="flex items-center gap-1.5"> <div className="flex items-center gap-1.5">
<input className="input py-1 text-[12.5px]" value={desc} placeholder="补一句业务含义" <input className="input py-1 text-label" value={desc} placeholder="补一句业务含义"
onChange={(e) => setDesc(e.target.value)} onBlur={save} onChange={(e) => setDesc(e.target.value)} onBlur={save}
onKeyDown={(e) => { if (e.key === "Enter") e.currentTarget.blur(); }} /> onKeyDown={(e) => { if (e.key === "Enter") e.currentTarget.blur(); }} />
{saving && <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted" />} {saving && <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted" />}
...@@ -322,7 +322,7 @@ function ColumnRow({ column, onSaved }: { column: SmColumn; onSaved: (c: SmColum ...@@ -322,7 +322,7 @@ function ColumnRow({ column, onSaved }: { column: SmColumn; onSaved: (c: SmColum
{column.sample_values.length > 0 ? ( {column.sample_values.length > 0 ? (
<span className="flex flex-wrap gap-1"> <span className="flex flex-wrap gap-1">
{column.sample_values.slice(0, 6).map((v, i) => ( {column.sample_values.slice(0, 6).map((v, i) => (
<span key={i} className="chip max-w-full truncate px-1.5 py-0 text-[11px]" <span key={i} className="chip max-w-full truncate px-1.5 py-0 text-caption"
title={String(v)}>{String(v)}</span> title={String(v)}>{String(v)}</span>
))} ))}
</span> </span>
...@@ -428,13 +428,13 @@ function RelationCard({ dsId, models, relations, onChanged }: { ...@@ -428,13 +428,13 @@ function RelationCard({ dsId, models, relations, onChanged }: {
{recs && recs.length > 0 && ( {recs && recs.length > 0 && (
<div className="border-b border-line bg-brand/[0.03] px-4 py-2.5"> <div className="border-b border-line bg-brand/[0.03] px-4 py-2.5">
<p className="mb-1.5 text-[12px] font-medium"> <p className="mb-1.5 text-label font-medium">
候选关联(按取值重叠率排序,确认无误再采纳) 候选关联(按取值重叠率排序,确认无误再采纳)
</p> </p>
<div className="space-y-1"> <div className="space-y-1">
{recs.map((r, i) => ( {recs.map((r, i) => (
<div key={i} className="flex flex-wrap items-center gap-2"> <div key={i} className="flex flex-wrap items-center gap-2">
<code className="min-w-0 flex-1 truncate text-[12px]"> <code className="min-w-0 flex-1 truncate text-label">
{r.from_table}.{r.from_column} = {r.to_table}.{r.to_column} {r.from_table}.{r.from_column} = {r.to_table}.{r.to_column}
</code> </code>
<Badge tone="bg-ok/10 text-ok">重叠 {(r.overlap * 100).toFixed(1)}%</Badge> <Badge tone="bg-ok/10 text-ok">重叠 {(r.overlap * 100).toFixed(1)}%</Badge>
...@@ -483,19 +483,19 @@ function RelationCard({ dsId, models, relations, onChanged }: { ...@@ -483,19 +483,19 @@ function RelationCard({ dsId, models, relations, onChanged }: {
)} )}
{relations.length === 0 ? ( {relations.length === 0 ? (
<p className="px-4 py-5 text-center text-[13px] text-muted"> <p className="px-4 py-5 text-center text-body text-muted">
还没有关联路径。有外键的话内省会自动带出来;没有就在这里手动声明。 还没有关联路径。有外键的话内省会自动带出来;没有就在这里手动声明。
</p> </p>
) : ( ) : (
<div className="divide-y divide-line"> <div className="divide-y divide-line">
{relations.map((r) => ( {relations.map((r) => (
<div key={r.id} className="flex flex-wrap items-center gap-2 px-4 py-2"> <div key={r.id} className="flex flex-wrap items-center gap-2 px-4 py-2">
<code className="min-w-0 flex-1 truncate text-[12.5px]"> <code className="min-w-0 flex-1 truncate text-label">
{nameOf(r.from_model_id)}.{r.from_column} = {nameOf(r.to_model_id)}.{r.to_column} {nameOf(r.from_model_id)}.{r.from_column} = {nameOf(r.to_model_id)}.{r.to_column}
</code> </code>
<Badge>{r.cardinality}</Badge> <Badge>{r.cardinality}</Badge>
{r.description && ( {r.description && (
<span className="max-w-[40%] truncate text-[11.5px] text-muted" title={r.description}> <span className="max-w-[40%] truncate text-label text-muted" title={r.description}>
{r.description} {r.description}
</span> </span>
)} )}
......
...@@ -83,7 +83,7 @@ export function RulesPanel({ dsId }: { dsId: number }) { ...@@ -83,7 +83,7 @@ export function RulesPanel({ dsId }: { dsId: number }) {
{broken.length > 0 && ( {broken.length > 0 && (
<div className="flex items-start gap-2 border-b border-line bg-bad/5 px-4 py-2.5"> <div className="flex items-start gap-2 border-b border-line bg-bad/5 px-4 py-2.5">
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-bad" /> <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-bad" />
<div className="text-[12.5px]"> <div className="text-label">
<p className="font-medium text-bad">{broken.length} 个指标引用了不可用的列,已被排除在提示词之外</p> <p className="font-medium text-bad">{broken.length} 个指标引用了不可用的列,已被排除在提示词之外</p>
{broken.map((b) => <p key={b.metric_id} className="mt-0.5 text-muted">{b.name}:{b.reason}</p>)} {broken.map((b) => <p key={b.metric_id} className="mt-0.5 text-muted">{b.name}:{b.reason}</p>)}
</div> </div>
...@@ -94,7 +94,7 @@ export function RulesPanel({ dsId }: { dsId: number }) { ...@@ -94,7 +94,7 @@ export function RulesPanel({ dsId }: { dsId: number }) {
<button key={m.id} className="chip" title={m.calibre_note ? `${m.expression}\n口径:${m.calibre_note}` : m.expression} <button key={m.id} className="chip" title={m.calibre_note ? `${m.expression}\n口径:${m.calibre_note}` : m.expression}
onClick={() => go("b_function", { id: String(m.id) })}>{m.display_name || m.name}</button> onClick={() => go("b_function", { id: String(m.id) })}>{m.display_name || m.name}</button>
))} ))}
{!metrics.length && <p className="text-[12px] text-muted">还没有绑定到这个数据源的聚合函数。问数会直接生成 SQL。</p>} {!metrics.length && <p className="text-label text-muted">还没有绑定到这个数据源的聚合函数。问数会直接生成 SQL。</p>}
</div> </div>
</Card> </Card>
...@@ -125,12 +125,12 @@ export function RulesPanel({ dsId }: { dsId: number }) { ...@@ -125,12 +125,12 @@ export function RulesPanel({ dsId }: { dsId: number }) {
{[...list].sort((a, b) => b.priority - a.priority).map((i) => ( {[...list].sort((a, b) => b.priority - a.priority).map((i) => (
<div key={i.id} className={cn("flex items-start gap-2 px-4 py-2.5", !i.enabled && "opacity-50")}> <div key={i.id} className={cn("flex items-start gap-2 px-4 py-2.5", !i.enabled && "opacity-50")}>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="whitespace-pre-wrap text-[12.5px] leading-relaxed">{i.content}</p> <p className="whitespace-pre-wrap text-label leading-relaxed">{i.content}</p>
<p className="mt-1 flex flex-wrap items-center gap-1.5"> <p className="mt-1 flex flex-wrap items-center gap-1.5">
{i.is_default ? <Badge tone="bg-ok/10 text-ok">默认注入</Badge> : <Badge tone="bg-warn/10 text-warn">按条件匹配</Badge>} {i.is_default ? <Badge tone="bg-ok/10 text-ok">默认注入</Badge> : <Badge tone="bg-warn/10 text-warn">按条件匹配</Badge>}
{i.ds_id === 0 && <Badge>全局</Badge>} {i.ds_id === 0 && <Badge>全局</Badge>}
<span className="text-[11px] text-muted">优先级 {i.priority}</span> <span className="text-caption text-muted">优先级 {i.priority}</span>
{i.condition_text && <span className="text-[11px] text-muted">触发词:{i.condition_text}</span>} {i.condition_text && <span className="text-caption text-muted">触发词:{i.condition_text}</span>}
</p> </p>
</div> </div>
<button className="btn btn-ghost btn-sm shrink-0" onClick={() => setEditingRule(i)}>编辑</button> <button className="btn btn-ghost btn-sm shrink-0" onClick={() => setEditingRule(i)}>编辑</button>
...@@ -154,10 +154,10 @@ function Group({ name, count, children }: { name: string; count: number; childre ...@@ -154,10 +154,10 @@ function Group({ name, count, children }: { name: string; count: number; childre
return ( return (
<div> <div>
<div className="sticky top-0 z-10 flex items-baseline gap-2 border-y border-line bg-elevated px-4 py-1.5"> <div className="sticky top-0 z-10 flex items-baseline gap-2 border-y border-line bg-elevated px-4 py-1.5">
<span className="text-[12px] font-semibold">{name}</span> <span className="text-label font-semibold">{name}</span>
<span className="text-[11px] tabular-nums text-muted">{count}</span> <span className="text-caption tabular-nums text-muted">{count}</span>
{CATEGORY_HINT[name] && ( {CATEGORY_HINT[name] && (
<span className="min-w-0 truncate text-[11px] text-muted">· {CATEGORY_HINT[name]}</span> <span className="min-w-0 truncate text-caption text-muted">· {CATEGORY_HINT[name]}</span>
)} )}
</div> </div>
<div className="divide-y divide-line">{children}</div> <div className="divide-y divide-line">{children}</div>
...@@ -195,7 +195,7 @@ function RuleForm({ dsId, value, onClose, onSaved }: { ...@@ -195,7 +195,7 @@ function RuleForm({ dsId, value, onClose, onSaved }: {
desc="只写你对着真实数据验证过的事实。写错一条会主动把模型带偏,比不写更糟。" desc="只写你对着真实数据验证过的事实。写错一条会主动把模型带偏,比不写更糟。"
footer={ footer={
<> <>
{err && <p className="mr-auto min-w-0 flex-1 text-[12.5px] text-bad">{err}</p>} {err && <p className="mr-auto min-w-0 flex-1 text-label text-bad">{err}</p>}
<button className="btn btn-sm" onClick={onClose}>取消</button> <button className="btn btn-sm" onClick={onClose}>取消</button>
<button className="btn btn-primary btn-sm" disabled={saving || !f.content} onClick={save}> <button className="btn btn-primary btn-sm" disabled={saving || !f.content} onClick={save}>
{saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />} 保存 {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />} 保存
...@@ -222,22 +222,22 @@ function RuleForm({ dsId, value, onClose, onSaved }: { ...@@ -222,22 +222,22 @@ function RuleForm({ dsId, value, onClose, onSaved }: {
</Field> </Field>
</div> </div>
<div className="space-y-2 rounded-lg border border-line bg-elevated/50 p-3"> <div className="space-y-2 rounded-lg border border-line bg-elevated/50 p-3">
<label className="flex cursor-pointer items-start gap-2 text-[12.5px]"> <label className="flex cursor-pointer items-start gap-2 text-label">
<input type="checkbox" className="mt-0.5" checked={f.is_default ?? true} <input type="checkbox" className="mt-0.5" checked={f.is_default ?? true}
onChange={(e) => setF((p) => ({ ...p, is_default: e.target.checked }))} /> onChange={(e) => setF((p) => ({ ...p, is_default: e.target.checked }))} />
<span> <span>
每次提问都注入 每次提问都注入
<span className="block text-[11.5px] text-muted"> <span className="block text-label text-muted">
关掉之后只有问句里出现下面的触发词才会用上,适合只对某类问题成立的规则 关掉之后只有问句里出现下面的触发词才会用上,适合只对某类问题成立的规则
</span> </span>
</span> </span>
</label> </label>
<label className="flex cursor-pointer items-start gap-2 text-[12.5px]"> <label className="flex cursor-pointer items-start gap-2 text-label">
<input type="checkbox" className="mt-0.5" checked={f.ds_id === 0} <input type="checkbox" className="mt-0.5" checked={f.ds_id === 0}
onChange={(e) => setF((p) => ({ ...p, ds_id: e.target.checked ? 0 : dsId }))} /> onChange={(e) => setF((p) => ({ ...p, ds_id: e.target.checked ? 0 : dsId }))} />
<span> <span>
对所有数据源生效 对所有数据源生效
<span className="block text-[11.5px] text-muted"> <span className="block text-label text-muted">
写法类的通用约定可以开;带具体表名列名的规则别开,换个库就是错的 写法类的通用约定可以开;带具体表名列名的规则别开,换个库就是错的
</span> </span>
</span> </span>
......
...@@ -64,7 +64,7 @@ export function SqlPage({ me }: { me: Me | null }) { ...@@ -64,7 +64,7 @@ export function SqlPage({ me }: { me: Me | null }) {
<span className="flex-1" /> <span className="flex-1" />
{sources && sources.length > 0 && ( {sources && sources.length > 0 && (
<label className="flex items-center gap-1.5 text-[12.5px] text-muted"> <label className="flex items-center gap-1.5 text-label text-muted">
数据源 数据源
<select className="input w-auto py-1" value={dsId ?? ""} <select className="input w-auto py-1" value={dsId ?? ""}
onChange={(e) => setDsId(Number(e.target.value))}> onChange={(e) => setDsId(Number(e.target.value))}>
......
...@@ -40,7 +40,7 @@ export function SqlTrace({ trace, running }: { trace: SqlTraceEvent[]; running: ...@@ -40,7 +40,7 @@ export function SqlTrace({ trace, running }: { trace: SqlTraceEvent[]; running:
{META[ev.type].icon} {META[ev.type].icon}
</span> </span>
<div className="min-w-0 flex-1 pb-1"> <div className="min-w-0 flex-1 pb-1">
<p className="flex flex-wrap items-center gap-1.5 text-[12.5px] font-medium"> <p className="flex flex-wrap items-center gap-1.5 text-label font-medium">
{META[ev.type].label} {META[ev.type].label}
<StepBadges ev={ev} /> <StepBadges ev={ev} />
</p> </p>
...@@ -49,7 +49,7 @@ export function SqlTrace({ trace, running }: { trace: SqlTraceEvent[]; running: ...@@ -49,7 +49,7 @@ export function SqlTrace({ trace, running }: { trace: SqlTraceEvent[]; running:
</li> </li>
))} ))}
{running && ( {running && (
<li className="flex items-center gap-2.5 text-[12.5px] text-muted"> <li className="flex items-center gap-2.5 text-label text-muted">
<Sparkles className="h-3.5 w-3.5 animate-pulse" /> 处理中… <Sparkles className="h-3.5 w-3.5 animate-pulse" /> 处理中…
</li> </li>
)} )}
...@@ -94,7 +94,7 @@ function StepBody({ ev }: { ev: SqlTraceEvent }) { ...@@ -94,7 +94,7 @@ function StepBody({ ev }: { ev: SqlTraceEvent }) {
<div className="mt-1 space-y-1"> <div className="mt-1 space-y-1">
<div className="flex flex-wrap gap-1"> <div className="flex flex-wrap gap-1">
{ev.models.map((m) => ( {ev.models.map((m) => (
<span key={m.id} className="chip px-1.5 py-0 text-[11px]" title={`相关度 ${m.score}`}> <span key={m.id} className="chip px-1.5 py-0 text-caption" title={`相关度 ${m.score}`}>
{m.table} {m.table}
<span className="text-muted">{m.columns} 列</span> <span className="text-muted">{m.columns} 列</span>
</span> </span>
...@@ -105,7 +105,7 @@ function StepBody({ ev }: { ev: SqlTraceEvent }) { ...@@ -105,7 +105,7 @@ function StepBody({ ev }: { ev: SqlTraceEvent }) {
// 这里每个只留一行,完整内容挂在 title 上,要细看去「指标与规则」页。 // 这里每个只留一行,完整内容挂在 title 上,要细看去「指标与规则」页。
<div className="space-y-0.5"> <div className="space-y-0.5">
{ev.metrics.map((m) => ( {ev.metrics.map((m) => (
<p key={m.id} className="truncate text-[11.5px] text-muted" <p key={m.id} className="truncate text-label text-muted"
title={m.calibre || m.name}> title={m.calibre || m.name}>
指标 <span className="text-ink">{m.name}</span> 指标 <span className="text-ink">{m.name}</span>
{m.calibre && <> · 口径:{m.calibre}</>} {m.calibre && <> · 口径:{m.calibre}</>}
...@@ -114,12 +114,12 @@ function StepBody({ ev }: { ev: SqlTraceEvent }) { ...@@ -114,12 +114,12 @@ function StepBody({ ev }: { ev: SqlTraceEvent }) {
</div> </div>
)} )}
{ev.pairs.length > 0 && ( {ev.pairs.length > 0 && (
<p className="text-[11.5px] text-muted"> <p className="text-label text-muted">
命中沉淀:{ev.pairs.map((p) => p.question).join(" / ")} 命中沉淀:{ev.pairs.map((p) => p.question).join(" / ")}
</p> </p>
)} )}
{ev.dropped_columns > 0 && ( {ev.dropped_columns > 0 && (
<p className="text-[11.5px] text-warn"> <p className="text-label text-warn">
上下文超预算,按相关度剪掉了 {ev.dropped_columns} 个列 上下文超预算,按相关度剪掉了 {ev.dropped_columns} 个列
</p> </p>
)} )}
...@@ -128,7 +128,7 @@ function StepBody({ ev }: { ev: SqlTraceEvent }) { ...@@ -128,7 +128,7 @@ function StepBody({ ev }: { ev: SqlTraceEvent }) {
case "plan": case "plan":
return ( return (
<div className="mt-1 space-y-1 text-[12px] text-muted"> <div className="mt-1 space-y-1 text-label text-muted">
{ev.plan?.summary && <p className="text-ink">{ev.plan.summary}</p>} {ev.plan?.summary && <p className="text-ink">{ev.plan.summary}</p>}
{ev.plan?.grain && <p>粒度:{ev.plan.grain}</p>} {ev.plan?.grain && <p>粒度:{ev.plan.grain}</p>}
{!!ev.plan?.measures?.length && <p>度量:{ev.plan.measures.join("、")}</p>} {!!ev.plan?.measures?.length && <p>度量:{ev.plan.measures.join("、")}</p>}
...@@ -148,7 +148,7 @@ function StepBody({ ev }: { ev: SqlTraceEvent }) { ...@@ -148,7 +148,7 @@ function StepBody({ ev }: { ev: SqlTraceEvent }) {
case "validate": case "validate":
if (ev.issues.length === 0) { if (ev.issues.length === 0) {
return ( return (
<p className="mt-0.5 text-[11.5px] text-muted"> <p className="mt-0.5 text-label text-muted">
只读检查、表与关联白名单都通过{ev.limited && ";已自动补上 LIMIT"} 只读检查、表与关联白名单都通过{ev.limited && ";已自动补上 LIMIT"}
</p> </p>
); );
...@@ -156,7 +156,7 @@ function StepBody({ ev }: { ev: SqlTraceEvent }) { ...@@ -156,7 +156,7 @@ function StepBody({ ev }: { ev: SqlTraceEvent }) {
return ( return (
<ul className="mt-1 space-y-0.5"> <ul className="mt-1 space-y-0.5">
{ev.issues.map((it, i) => ( {ev.issues.map((it, i) => (
<li key={i} className={cn("flex gap-1.5 text-[11.5px]", <li key={i} className={cn("flex gap-1.5 text-label",
it.level === "error" ? "text-bad" : "text-warn")}> it.level === "error" ? "text-bad" : "text-warn")}>
<AlertTriangle className="mt-0.5 h-3 w-3 shrink-0" /> <AlertTriangle className="mt-0.5 h-3 w-3 shrink-0" />
<span> <span>
...@@ -169,12 +169,12 @@ function StepBody({ ev }: { ev: SqlTraceEvent }) { ...@@ -169,12 +169,12 @@ function StepBody({ ev }: { ev: SqlTraceEvent }) {
); );
case "repair": case "repair":
return <p className="mt-0.5 text-[11.5px] text-muted">因为:{ev.reason}</p>; return <p className="mt-0.5 text-label text-muted">因为:{ev.reason}</p>;
case "error": case "error":
// 只说清在哪一步挂的。完整报错在右边的醒目框里,这里重复一遍纯属噪声。 // 只说清在哪一步挂的。完整报错在右边的醒目框里,这里重复一遍纯属噪声。
return ( return (
<p className="mt-0.5 text-[11.5px] text-muted"> <p className="mt-0.5 text-label text-muted">
在「{STAGE_TEXT[ev.stage] ?? ev.stage}」阶段失败 在「{STAGE_TEXT[ev.stage] ?? ev.stage}」阶段失败
{ev.attempts ? `,已重试 ${ev.attempts - 1} 轮` : ""} {ev.attempts ? `,已重试 ${ev.attempts - 1} 轮` : ""}
</p> </p>
......
import { Hammer, LayoutDashboard } from "lucide-react";
import { Segmented } from "@/components/ui";
import { HomePage } from "@/features/home/HomePage";
import { go, useHashParams } from "@/lib/nav";
import type { Me } from "@/lib/onto";
import { WorkbenchPage } from "./WorkbenchPage";
/**
* 首页。所有人默认看「我的工作台」;搭建者多一个「搭建进度」页签(原本体首页:资产、映射、建议下一步)。
* 以前工作台、本体首页、运行总览是三个并列的首页,打开系统不知道该看哪个。
*/
export function DeskPage({ me, builder }: { me: Me | null; builder: boolean }) {
const hp = useHashParams();
const tab = builder && hp.get("tab") === "build" ? "build" : "mine";
return (
<div className="space-y-3">
{builder && (
<div className="mx-auto max-w-6xl">
<Segmented value={tab} onChange={(t) => go("desk", t === "build" ? { tab: "build" } : {})} options={[
{ key: "mine", label: <><LayoutDashboard className="h-3.5 w-3.5" />我的工作台</> },
{ key: "build", label: <><Hammer className="h-3.5 w-3.5" />搭建进度</> },
]} />
</div>
)}
{tab === "build" ? <HomePage me={me} /> : <WorkbenchPage />}
</div>
);
}
...@@ -45,7 +45,22 @@ export function WorkbenchPage() { ...@@ -45,7 +45,22 @@ export function WorkbenchPage() {
try { try {
await onto.decidePattern(h.id, adopt); await onto.decidePattern(h.id, adopt);
if (adopt && h.kind === "action") go("sop", { draft: `每天检查需要「${h.title}」的情况,自动起草并提交审批` }); if (adopt && h.kind === "action") go("sop", { draft: `每天检查需要「${h.title}」的情况,自动起草并提交审批` });
else if (adopt && h.kind === "sop") go("sop", { id: h.ref, tab: "trigger" }); else if (adopt && h.kind === "sop") {
// 「设为定时运行」以前跳到流程卡的触发方式页签,而触发器已经搬进「监控与定时」了。
// 这里直接把监控器建好(默认每天 8 点跑这张卡),再跳过去让人调频率。
try {
const wt = await onto.createWatch({
title: `「${h.title}」定时`,
description: "从工作台的操作习惯建议固化而来",
schedule: { kind: "daily", at: "08:00" },
source: { kind: "sop", sop: h.ref },
condition: "",
strategies: [{ kind: "run_sop", sop: h.ref }],
});
toast("ok", "已设为每天 8:00 运行", "可以在这里改频率");
go("watch", { id: wt.id });
} catch (e) { toast("error", "创建定时失败", errText(e)); }
}
else toast("ok", adopt ? "已加入常用问题" : "好的,不再提示"); else toast("ok", adopt ? "已加入常用问题" : "好的,不再提示");
load(); load();
} catch (e) { toast("error", "操作失败", errText(e)); } } catch (e) { toast("error", "操作失败", errText(e)); }
...@@ -56,15 +71,15 @@ export function WorkbenchPage() { ...@@ -56,15 +71,15 @@ export function WorkbenchPage() {
return ( return (
<div className="mx-auto max-w-6xl space-y-4"> <div className="mx-auto max-w-6xl space-y-4">
<Card className="p-4" style={{ background: "linear-gradient(120deg, rgb(var(--brand) / 0.08), transparent 60%)" }}> <Card className="p-4" style={{ background: "linear-gradient(120deg, rgb(var(--brand) / 0.08), transparent 60%)" }}>
<p className="text-[16px] font-semibold">{w.user.name},你好</p> <p className="text-section font-semibold">{w.user.name},你好</p>
<p className="mt-0.5 text-[12.5px] text-muted"> <p className="mt-0.5 text-label text-muted">
{today}{w.user.biz_roles.length ? ` · ${w.user.biz_roles.join("、")}` : ""} {today}{w.user.biz_roles.length ? ` · ${w.user.biz_roles.join("、")}` : ""}
{todoCount ? ` · 有 ${todoCount} 件事等你处理` : " · 暂时没有等你处理的事"} {todoCount ? ` · 有 ${todoCount} 件事等你处理` : " · 暂时没有等你处理的事"}
</p> </p>
<div className="mt-3 flex gap-2"> <div className="mt-3 flex gap-2">
<div className="relative min-w-0 flex-1"> <div className="relative min-w-0 flex-1">
<MessageSquareText className="absolute left-2.5 top-2.5 h-4 w-4 text-muted" /> <MessageSquareText className="absolute left-2.5 top-2.5 h-4 w-4 text-muted" />
<input className="input h-10 pl-8 text-[13.5px]" value={q} placeholder="直接问:哪些商品快缺货了?帮我给上海仓补抽纸……" <input className="input h-10 pl-8 text-body" value={q} placeholder="直接问:哪些商品快缺货了?帮我给上海仓补抽纸……"
onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") askNow(q); }} /> onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") askNow(q); }} />
</div> </div>
<button className="btn btn-primary h-10" disabled={!q.trim()} onClick={() => askNow(q)}><Send className="h-4 w-4" />提问</button> <button className="btn btn-primary h-10" disabled={!q.trim()} onClick={() => askNow(q)}><Send className="h-4 w-4" />提问</button>
...@@ -86,7 +101,7 @@ export function WorkbenchPage() { ...@@ -86,7 +101,7 @@ export function WorkbenchPage() {
<div className="divide-y divide-line"> <div className="divide-y divide-line">
{(w.habits || []).map((h) => ( {(w.habits || []).map((h) => (
<div key={h.id} className="flex flex-wrap items-center gap-2 px-4 py-2.5"> <div key={h.id} className="flex flex-wrap items-center gap-2 px-4 py-2.5">
<span className="min-w-0 flex-1 text-[13px]">{h.text || h.title}</span> <span className="min-w-0 flex-1 text-body">{h.text || h.title}</span>
<button className="btn btn-primary btn-sm" onClick={() => void decideHabit(h, true)}> <button className="btn btn-primary btn-sm" onClick={() => void decideHabit(h, true)}>
{h.kind === "question" ? "加入常用问题" : h.kind === "action" ? "做成流程卡" : "设为定时运行"}</button> {h.kind === "question" ? "加入常用问题" : h.kind === "action" ? "做成流程卡" : "设为定时运行"}</button>
<button className="btn btn-ghost btn-sm" onClick={() => void decideHabit(h, false)}>不用了</button> <button className="btn btn-ghost btn-sm" onClick={() => void decideHabit(h, false)}>不用了</button>
...@@ -101,17 +116,17 @@ export function WorkbenchPage() { ...@@ -101,17 +116,17 @@ export function WorkbenchPage() {
{w.kpis.map((k) => ( {w.kpis.map((k) => (
<button key={k.name} className="card p-3 text-left hover:border-brand/40" title={k.formula} <button key={k.name} className="card p-3 text-left hover:border-brand/40" title={k.formula}
onClick={() => askNow(k.dimensions[0] ? `${k.name}按${k.dimensions[0]}拆开看` : `${k.name}是怎么算出来的?`)}> onClick={() => askNow(k.dimensions[0] ? `${k.name}按${k.dimensions[0]}拆开看` : `${k.name}是怎么算出来的?`)}>
<p className="flex items-center gap-1 text-[12px] text-muted">{k.name} <p className="flex items-center gap-1 text-label text-muted">{k.name}
{k.direction === "higher_better" && <TrendingUp className="h-3 w-3" />} {k.direction === "higher_better" && <TrendingUp className="h-3 w-3" />}
{k.direction === "lower_better" && <TrendingDown className="h-3 w-3" />}</p> {k.direction === "lower_better" && <TrendingDown className="h-3 w-3" />}</p>
<p className="mt-1 text-[24px] font-semibold tabular-nums">{fmtValue(k.value, k.unit)} <p className="mt-1 text-[24px] font-semibold tabular-nums">{fmtValue(k.value, k.unit)}
{k.unit && k.unit !== "%" && <span className="ml-1 text-[12px] font-normal text-muted">{k.unit}</span>}</p> {k.unit && k.unit !== "%" && <span className="ml-1 text-label font-normal text-muted">{k.unit}</span>}</p>
<p className="mt-0.5 truncate text-[11px] text-muted">{k.formula || "点击查看明细"}</p> <p className="mt-0.5 truncate text-caption text-muted">{k.formula || "点击查看明细"}</p>
</button> </button>
))} ))}
</div> </div>
) : ( ) : (
<Card className="p-4 text-[12.5px] text-muted">还没有可展示的指标。实施人员在「业务建模」里发布带取数口径的指标后,这里会显示当天的数字。</Card> <Card className="p-4 text-label text-muted">还没有可展示的指标。实施人员在「业务建模」里发布带取数口径的指标后,这里会显示当天的数字。</Card>
)} )}
<div className="grid gap-4 lg:grid-cols-2 [&>*]:min-w-0"> <div className="grid gap-4 lg:grid-cols-2 [&>*]:min-w-0">
...@@ -124,21 +139,21 @@ export function WorkbenchPage() { ...@@ -124,21 +139,21 @@ export function WorkbenchPage() {
onClick={() => go("inbox", { tab: "approvals", run: r.id })}> onClick={() => go("inbox", { tab: "approvals", run: r.id })}>
<Badge tone={PRIORITY_TONE[r.priority]}>{r.priority}</Badge> <Badge tone={PRIORITY_TONE[r.priority]}>{r.priority}</Badge>
<span className="min-w-0 flex-1"> <span className="min-w-0 flex-1">
<span className="block text-[13px] font-medium">审批:{r.action_name}</span> <span className="block text-body font-medium">审批:{r.action_name}</span>
<span className="block truncate text-[11.5px] text-muted">{r.summary}</span> <span className="block truncate text-label text-muted">{r.summary}</span>
</span> </span>
<span className="shrink-0 text-[11px] text-muted">{fmtTime(r.created_at)}</span> <span className="shrink-0 text-caption text-muted">{fmtTime(r.created_at)}</span>
</button> </button>
))} ))}
{w.todo.releases.map((r) => ( {w.todo.releases.map((r) => (
<button key={r.id} className="flex w-full items-center gap-2 px-4 py-2.5 text-left hover:bg-ink/[0.03]" onClick={() => go("inbox", { tab: "releases" })}> <button key={r.id} className="flex w-full items-center gap-2 px-4 py-2.5 text-left hover:bg-ink/[0.03]" onClick={() => go("inbox", { tab: "releases" })}>
<Badge>变更</Badge><span className="min-w-0 flex-1 truncate text-[13px]">{r.title}</span> <Badge>变更</Badge><span className="min-w-0 flex-1 truncate text-body">{r.title}</span>
</button> </button>
))} ))}
{w.todo.tasks.map((t) => ( {w.todo.tasks.map((t) => (
<button key={t.id} className="flex w-full items-center gap-2 px-4 py-2.5 text-left hover:bg-ink/[0.03]" onClick={() => go("inbox", { tab: "tasks" })}> <button key={t.id} className="flex w-full items-center gap-2 px-4 py-2.5 text-left hover:bg-ink/[0.03]" onClick={() => go("inbox", { tab: "tasks" })}>
<ClipboardList className="h-4 w-4 text-brand" /><span className="min-w-0 flex-1 truncate text-[13px]">待办:{t.title}</span> <ClipboardList className="h-4 w-4 text-brand" /><span className="min-w-0 flex-1 truncate text-body">待办:{t.title}</span>
{t.due_at && <span className="text-[11px] text-muted">截止 {fmtTime(t.due_at)}</span>} {t.due_at && <span className="text-caption text-muted">截止 {fmtTime(t.due_at)}</span>}
</button> </button>
))} ))}
{!todoCount && <Empty icon={<CheckCircle2 className="h-8 w-8" />} title="都处理完了" desc="有新的审批和待办会出现在这里" />} {!todoCount && <Empty icon={<CheckCircle2 className="h-8 w-8" />} title="都处理完了" desc="有新的审批和待办会出现在这里" />}
...@@ -155,10 +170,10 @@ export function WorkbenchPage() { ...@@ -155,10 +170,10 @@ export function WorkbenchPage() {
onClick={() => go("inbox", { tab: "runs", run: r.id })}> onClick={() => go("inbox", { tab: "runs", run: r.id })}>
<Badge tone={tone}>{label}</Badge> <Badge tone={tone}>{label}</Badge>
<span className="min-w-0 flex-1"> <span className="min-w-0 flex-1">
<span className="block text-[13px] font-medium">{r.action_name}</span> <span className="block text-body font-medium">{r.action_name}</span>
<span className="block truncate text-[11.5px] text-muted">{r.summary}</span> <span className="block truncate text-label text-muted">{r.summary}</span>
</span> </span>
<span className="shrink-0 text-[11px] text-muted">{fmtTime(r.created_at)}</span> <span className="shrink-0 text-caption text-muted">{fmtTime(r.created_at)}</span>
</button> </button>
); );
})} })}
...@@ -174,10 +189,10 @@ export function WorkbenchPage() { ...@@ -174,10 +189,10 @@ export function WorkbenchPage() {
{w.sops.map((s) => ( {w.sops.map((s) => (
<div key={s.id} className="flex items-center gap-2 px-4 py-2.5"> <div key={s.id} className="flex items-center gap-2 px-4 py-2.5">
<span className="min-w-0 flex-1"> <span className="min-w-0 flex-1">
<span className="block text-[13px] font-medium">{s.title}</span> <span className="block text-body font-medium">{s.title}</span>
<span className="block truncate text-[11.5px] text-muted">{s.description}</span> <span className="block truncate text-label text-muted">{s.description}</span>
</span> </span>
<span className="text-[11px] text-muted">已运行 {s.run_count} 次</span> <span className="text-caption text-muted">已运行 {s.run_count} 次</span>
{w.user.can_run {w.user.can_run
? <button className="btn btn-sm" disabled={!!running} onClick={() => void runSop(s.id, s.title)}> ? <button className="btn btn-sm" disabled={!!running} onClick={() => void runSop(s.id, s.title)}>
{running === s.id ? <Spinner className="h-3.5 w-3.5" /> : <Play className="h-3.5 w-3.5" />}运行</button> {running === s.id ? <Spinner className="h-3.5 w-3.5" /> : <Play className="h-3.5 w-3.5" />}运行</button>
...@@ -191,8 +206,8 @@ export function WorkbenchPage() { ...@@ -191,8 +206,8 @@ export function WorkbenchPage() {
<CardHeader title="最近动态" right={<button className="btn btn-ghost btn-sm" onClick={() => go("monitor", { tab: "audit" })}>全部<ArrowRight className="h-3.5 w-3.5" /></button>} /> <CardHeader title="最近动态" right={<button className="btn btn-ghost btn-sm" onClick={() => go("monitor", { tab: "audit" })}>全部<ArrowRight className="h-3.5 w-3.5" /></button>} />
<div className="divide-y divide-line"> <div className="divide-y divide-line">
{w.feed.map((f, i) => ( {w.feed.map((f, i) => (
<p key={i} className="flex gap-2 px-4 py-2 text-[12.5px]"> <p key={i} className="flex gap-2 px-4 py-2 text-label">
<span className="w-24 shrink-0 text-[11px] text-muted">{fmtTime(f.ts)}</span> <span className="w-24 shrink-0 text-caption text-muted">{fmtTime(f.ts)}</span>
<span className="w-16 shrink-0 truncate text-muted">{f.actor}</span> <span className="w-16 shrink-0 truncate text-muted">{f.actor}</span>
<span className="min-w-0 flex-1 truncate">{f.summary}</span> <span className="min-w-0 flex-1 truncate">{f.summary}</span>
</p> </p>
......
...@@ -42,7 +42,7 @@ export function DialogHost() { ...@@ -42,7 +42,7 @@ export function DialogHost() {
<textarea ref={input} className="input min-h-[70px]" value={val} placeholder={req.placeholder} <textarea ref={input} className="input min-h-[70px]" value={val} placeholder={req.placeholder}
onChange={(e) => setVal(e.target.value)} onChange={(e) => setVal(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey && val.trim()) { e.preventDefault(); done(val.trim()); } }} /> onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey && val.trim()) { e.preventDefault(); done(val.trim()); } }} />
) : <p className="text-[13px] text-muted">{req.desc ? "" : "请确认这个操作。"}</p>} ) : <p className="text-body text-muted">{req.desc ? "" : "请确认这个操作。"}</p>}
</Modal> </Modal>
); );
} }
...@@ -223,6 +223,9 @@ export interface SopStep { ...@@ -223,6 +223,9 @@ export interface SopStep {
items?: string; limit?: number; items?: string; limit?: number;
} }
export interface SopParam { name: string; label: string; type: string; object_type: string; calendar: string; required: boolean; default?: any } export interface SopParam { name: string; label: string; type: string; object_type: string; calendar: string; required: boolean; default?: any }
/** 结构化校验结果:带 step_id,前端据此把错误标到对应节点上 */
export interface SopIssue { level: "error" | "warning"; step_id: string; message: string }
export interface SopSpec { export interface SopSpec {
params: SopParam[]; roles: string[]; trigger: any; start: string; steps: SopStep[]; evidence: any[]; params: SopParam[]; roles: string[]; trigger: any; start: string; steps: SopStep[]; evidence: any[];
priority?: string; domain?: string; priority?: string; domain?: string;
...@@ -333,6 +336,47 @@ export interface EvalRun { ...@@ -333,6 +336,47 @@ export interface EvalRun {
} }
// ============================== 接口 ============================== // ============================== 接口 ==============================
// ---------------- 监控与定时 ----------------
export interface WatchSchedule {
kind: "interval" | "daily" | "weekly" | "monthly" | "cron";
at?: string; weekday?: number; day?: number; every_minutes?: number; cron?: string;
tz?: string; misfire?: "skip" | "run_once";
}
export interface WatchStrategy {
kind: "run_sop" | "propose_action" | "notify";
sop?: string; action?: string; params?: Record<string, any>; object_key?: string;
reason?: string; role?: string; title?: string; instructions?: string;
}
export interface WatchDef {
id: string; title: string; description: string; enabled: boolean;
schedule: WatchSchedule; schedule_text: string;
source: { kind: "metric" | "object" | "sop"; metric?: string; dimensions?: string[];
time?: string; object_type?: string; limit?: number; sop?: string };
condition: string; strategies: WatchStrategy[];
dedup: { key: string; cooldown_hours: number };
owner_role: string; next_fire_at: string | null; last_fired_at: string | null;
last_status: string; last_error: string; fail_count: number;
created_by: string; created_at: string; updated_at: string;
run_counts?: Record<string, number>;
}
export interface WatchRunRec {
id: string; watch_id: string; trigger: string; status: string;
scanned: number; hit_count: number; fired_count: number; suppressed: number;
hits: Record<string, any>[]; fired: { kind: string; ok: boolean; text: string; ref?: string; key?: string }[];
error: string; started_at: string; finished_at: string | null;
}
export interface WatchScanResult {
watch: string; scanned: number; hits: Record<string, any>[]; hit_count: number;
over_limit: number; fired: WatchRunRec["fired"]; suppressed: number; run_id: string; ms: number;
}
export interface WatchMeta {
schedule_kinds: { key: string; label: string; desc: string }[];
source_kinds: { key: string; label: string; desc: string }[];
strategy_kinds: { key: string; label: string; desc: string }[];
max_hits: number;
}
export const onto = { export const onto = {
// 治理 // 治理
me: () => req<Me>("/api/gov/me"), me: () => req<Me>("/api/gov/me"),
...@@ -367,7 +411,9 @@ export const onto = { ...@@ -367,7 +411,9 @@ export const onto = {
createConcept: (body: any) => req<Concept>("/api/kernel/concepts", post(body)), createConcept: (body: any) => req<Concept>("/api/kernel/concepts", post(body)),
updateConcept: (id: string, body: any) => req<Concept>(`/api/kernel/concepts/${enc(id)}`, put(body)), updateConcept: (id: string, body: any) => req<Concept>(`/api/kernel/concepts/${enc(id)}`, put(body)),
deleteConcept: (id: string) => req<{ ok: boolean }>(`/api/kernel/concepts/${enc(id)}`, del), deleteConcept: (id: string) => req<{ ok: boolean }>(`/api/kernel/concepts/${enc(id)}`, del),
deprecateConcept: (id: string, reason = "") => req<Concept>(`/api/kernel/concepts/${enc(id)}/deprecate`, post({ reason })), deprecateConcept: (id: string, reason = "", force = false) => req<Concept>(`/api/kernel/concepts/${enc(id)}/deprecate`, post({ reason, force })),
restoreConcept: (id: string) => req<Concept>(`/api/kernel/concepts/${enc(id)}`, put({ restore: true })),
conceptUsage: (id: string) => req<{ type: string; id: string; name: string; kind: string }[]>(`/api/kernel/concepts/${enc(id)}/usage`),
usage: (id: string) => req<{ type: string; id: string; name: string; kind: string }[]>(`/api/kernel/concepts/${enc(id)}/usage`), usage: (id: string) => req<{ type: string; id: string; name: string; kind: string }[]>(`/api/kernel/concepts/${enc(id)}/usage`),
impact: (id: string) => req<any>(`/api/kernel/concepts/${enc(id)}/impact`), impact: (id: string) => req<any>(`/api/kernel/concepts/${enc(id)}/impact`),
lineage: (id: string) => req<{ nodes: { id: string; label: string; kind: string }[]; edges: { from: string; to: string; label: string }[] }>( lineage: (id: string) => req<{ nodes: { id: string; label: string; kind: string }[]; edges: { from: string; to: string; label: string }[] }>(
...@@ -486,6 +532,19 @@ export const onto = { ...@@ -486,6 +532,19 @@ export const onto = {
mcpLogs: (limit = 50) => req<AuditRec[]>(`/api/cap/mcp/logs?limit=${limit}`), mcpLogs: (limit = 50) => req<AuditRec[]>(`/api/cap/mcp/logs?limit=${limit}`),
runtimeOverview: () => req<RuntimeOverview>("/api/cap/runtime/overview"), runtimeOverview: () => req<RuntimeOverview>("/api/cap/runtime/overview"),
// 监控与定时
watchMeta: () => req<WatchMeta>("/api/watch/meta"),
watches: (q = "") => req<WatchDef[]>(`/api/watch${qs({ q })}`),
watch: (id: string) => req<WatchDef>(`/api/watch/${enc(id)}`),
createWatch: (body: any) => req<WatchDef>("/api/watch", post(body)),
saveWatch: (id: string, body: any) => req<WatchDef>(`/api/watch/${enc(id)}`, put(body)),
deleteWatch: (id: string) => req<{ ok: boolean }>(`/api/watch/${enc(id)}`, del),
setWatchEnabled: (id: string, enabled: boolean) => req<WatchDef>(`/api/watch/${enc(id)}/enabled`, post({ enabled })),
scanWatch: (id: string, dry = true, force = false) => req<WatchScanResult>(`/api/watch/${enc(id)}/scan`, post({ dry, force })),
watchRuns: (watch_id = "", limit = 50) => req<WatchRunRec[]>(`/api/watch/runs${qs({ watch_id, limit })}`),
previewSchedule: (schedule: any) => req<{ ok: boolean; error?: string; text: string; next: string[] }>(
"/api/watch/preview-schedule", post({ schedule })),
// SOP // SOP
sopMeta: () => req<{ step_types: { type: string; label: string }[]; param_types: string[] }>("/api/sop/meta"), sopMeta: () => req<{ step_types: { type: string; label: string }[]; param_types: string[] }>("/api/sop/meta"),
sops: (p: Record<string, unknown> = {}) => req<SopBrief[]>(`/api/sop/defs${qs(p)}`), sops: (p: Record<string, unknown> = {}) => req<SopBrief[]>(`/api/sop/defs${qs(p)}`),
...@@ -494,7 +553,12 @@ export const onto = { ...@@ -494,7 +553,12 @@ export const onto = {
draftSop: (topic: string, process_concept_id = "") => req<SopDef>("/api/sop/defs/draft", post({ topic, process_concept_id })), draftSop: (topic: string, process_concept_id = "") => req<SopDef>("/api/sop/defs/draft", post({ topic, process_concept_id })),
saveSop: (id: string, body: any) => req<SopDef>(`/api/sop/defs/${enc(id)}`, put(body)), saveSop: (id: string, body: any) => req<SopDef>(`/api/sop/defs/${enc(id)}`, put(body)),
archiveSop: (id: string) => req<SopDef>(`/api/sop/defs/${enc(id)}/archive`, post()), archiveSop: (id: string) => req<SopDef>(`/api/sop/defs/${enc(id)}/archive`, post()),
validateSop: (spec: any) => req<{ spec: SopSpec; errors: string[]; warnings: string[] }>("/api/sop/validate", post({ spec })), unarchiveSop: (id: string) => req<SopDef>(`/api/sop/defs/${enc(id)}/unarchive`, post()),
sopReferencedBy: (id: string) => req<{ id: string; title: string; step: string }[]>(`/api/sop/defs/${enc(id)}/referenced-by`),
validateSop: (spec: any) => req<{ spec: SopSpec; errors: string[]; warnings: string[]; issues?: SopIssue[] }>("/api/sop/validate", post({ spec })),
trySopStep: (id: string, stepId: string, env: Record<string, unknown> = {}) => req<{
step_id: string; type: string; title: string; ok: boolean; output?: any; note?: string;
var?: string; error?: string; ms: number }>(`/api/sop/defs/${enc(id)}/steps/${enc(stepId)}/try`, post({ env })),
dryRunSop: (id: string, params: any) => req<SopRun>(`/api/sop/defs/${enc(id)}/dry-run`, post({ params })), dryRunSop: (id: string, params: any) => req<SopRun>(`/api/sop/defs/${enc(id)}/dry-run`, post({ params })),
submitSop: (id: string, note: string) => req<ReviewItem>(`/api/sop/defs/${enc(id)}/submit`, post({ note })), submitSop: (id: string, note: string) => req<ReviewItem>(`/api/sop/defs/${enc(id)}/submit`, post({ note })),
runSop: (id: string, params: any, mode = "live") => req<SopRun>(`/api/sop/defs/${enc(id)}/run`, post({ params, mode })), runSop: (id: string, params: any, mode = "live") => req<SopRun>(`/api/sop/defs/${enc(id)}/run`, post({ params, mode })),
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!