DraftModal.tsx 9.94 KB
import { CheckCircle2, Circle, Loader2, Play, Save, Wand2, XCircle } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { Badge, Field, Modal, Spinner } from "@/components/ui";
import { currentUserId } from "@/lib/identity";
import { errText, onto, type DraftEvent } from "@/lib/onto";
import { streamSSE, type SSEHandle } from "@/lib/sse";
import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { DecisionEditor } from "./BlockEditor";
import { ResultView, TypeBadge } from "./common";

const EXAMPLES: Record<string, string[]> = {
  function: ["实际值不低于目标值就算达标", "按达成率分三档:100% 以上 A,80%~100% B,其余 C",
             "计算还差多少单才能达到目标转化率,向上取整", "上月 26 日到本月 25 日算一个考核周期"],
  action: ["把对象标记为重点跟进,并给负责人派一个整改任务", "给指定角色发一条提醒通知"],
};

/**
 * 一句话生成函数 / 动作。AI 流式起草:判断类别 → 推荐对象与属性 → 生成逻辑 → 系统校验(不过就让 AI 修一次)
 * → 给出试跑样例。人看过、试过,点「保存为草稿」才落库;之后照常走发布。
 */
export function DraftModal({ kind, onClose, onSaved }: {
  kind: "function" | "action"; onClose: () => void; onSaved: (id: string) => void;
}) {
  const [intent, setIntent] = useState("");
  const [events, setEvents] = useState<DraftEvent[]>([]);
  const [running, setRunning] = useState(false);
  const [draft, setDraft] = useState<DraftEvent["draft"] | null>(null);
  const [samples, setSamples] = useState<{ input: any; expect?: any }[]>([]);
  const [tries, setTries] = useState<Record<number, any>>({});
  const [name, setName] = useState("");
  const h = useRef<SSEHandle | null>(null);
  useEffect(() => () => h.current?.abort(), []);

  const start = () => {
    setEvents([]); setDraft(null); setTries({}); setRunning(true);
    h.current = streamSSE<DraftEvent>("/api/kernel/draft", {
      method: "POST", headers: { "Content-Type": "application/json", "X-User-Id": currentUserId() },
      body: JSON.stringify({ intent, kind: kind === "action" ? "action" : "" }),
    }, (ev) => {
      setEvents((x) => [...x, ev]);
      if (ev.type === "done" && ev.draft) {
        setDraft(ev.draft); setName(ev.draft.name); setSamples(ev.samples || []);
      }
      if (ev.type === "done" || ev.type === "error") setRunning(false);
    }, (e) => { setRunning(false); setEvents((x) => [...x, { type: "error", error: e.message }]); });
    void h.current.done.then(() => setRunning(false));
  };

  const cls = events.find((e) => e.type === "classify");
  const ent = events.find((e) => e.type === "entities");
  const vals = events.filter((e) => e.type === "validate");
  const done = events.find((e) => e.type === "done");
  const err = events.find((e) => e.type === "error");
  const cat = draft?.spec?.category;

  const trySample = async (i: number) => {
    if (!draft) return;
    const input = samples[i]?.input || {};
    const args = cat === "rule" ? { vars: input } : cat === "decision" ? { inputs: input } : input;
    try {
      setTries((t) => ({ ...t, [i]: { running: true } }));
      const r = await onto.trySpec(draft.kind, draft.spec, args, String(input.obj_key || ""), name);
      setTries((t) => ({ ...t, [i]: r }));
    } catch (e) { setTries((t) => ({ ...t, [i]: { error: errText(e) } })); }
  };
  const save = async () => {
    if (!draft) return;
    try {
      const c = await onto.createConcept({ kind: draft.kind, name, description: draft.description,
                                           synonyms: draft.synonyms, spec: draft.spec });
      toast("ok", "已保存为草稿", "在编辑器里可以继续调整,发布后生效");
      onSaved(c.id);
    } catch (e) { toast("error", "保存失败", errText(e)); }
  };

  const step = (label: string, state: "wait" | "run" | "ok" | "bad", detail?: React.ReactNode) => (
    <li className="flex gap-2">
      {state === "ok" ? <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0 text-ok" />
        : 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" />
            : <Circle className="mt-0.5 h-4 w-4 shrink-0 text-muted/40" />}
      <div className="min-w-0 flex-1 text-label"><p className="font-medium">{label}</p>{detail && <div className="text-muted">{detail}</div>}</div>
    </li>
  );

  return (
    <Modal open onClose={onClose} width="max-w-3xl" title={<span className="flex items-center gap-2"><Wand2 className="h-4 w-4 text-brand" />一句话生成{kind === "action" ? "动作" : "函数"}</span>}
          
           footer={<>
             <button className="btn" onClick={onClose}>关闭</button>
             {draft && <button className="btn btn-primary" disabled={!name.trim() || !done?.ok} onClick={() => void save()}><Save className="h-3.5 w-3.5" />保存为草稿</button>}
           </>}>
      <div className="space-y-4">
        <div className="flex gap-2">
          <textarea className="input min-h-[52px] flex-1" value={intent} onChange={(e) => setIntent(e.target.value)}
                    placeholder={`用业务语言描述,例如:${EXAMPLES[kind][0]}`}
                    onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey && intent.trim() && !running) { e.preventDefault(); start(); } }} />
          <button className="btn btn-primary self-start" disabled={!intent.trim() || running} onClick={start}>
            {running ? <Spinner className="h-3.5 w-3.5" /> : <Wand2 className="h-3.5 w-3.5" />}起草
          </button>
        </div>
        {!events.length && (
          <div className="flex flex-wrap gap-1.5">
            {EXAMPLES[kind].map((x) => <button key={x} className="chip" onClick={() => setIntent(x)}>{x}</button>)}
          </div>
        )}

        {events.length > 0 && (
          <ol className="space-y-2 rounded-lg border border-line p-3">
            {step("判断类别", cls ? "ok" : running ? "run" : "wait", cls && <span className="flex flex-wrap items-center gap-1.5">
              <TypeBadge t={cls.kind === "action" ? "action" : cls.category || "rule"} />{cls.name} <span>· {cls.reason}</span></span>)}
            {step("推荐对象与属性", ent ? "ok" : cls && running ? "run" : "wait", ent && (
              <span>{ent.object_type ? `对象:${ent.object_type}` : "不作用于具体对象"}
                {!!ent.properties?.length && ` · 属性:${ent.properties.join("、")}`}
                {!!ent.inputs?.length && ` · 输入:${ent.inputs.join("、")}`}</span>))}
            {step("生成逻辑并校验", done ? (done.ok ? "ok" : "bad") : ent && running ? "run" : err ? "bad" : "wait", (
              <>{vals.map((v, i) => <p key={i}>第 {v.attempt} 次:{v.ok ? "校验通过" : `没通过(${v.error}),让 AI 修正`}</p>)}
                {err && <p className="text-bad">{err.error}</p>}</>))}
          </ol>
        )}

        {draft && (
          <div className="space-y-3 rounded-lg border border-brand/30 bg-brand/[0.03] p-3">
            <div className="flex flex-wrap items-end gap-3">
              <Field label="名称" className="w-60"><input className="input" value={name} onChange={(e) => setName(e.target.value)} /></Field>
              <TypeBadge t={draft.kind === "action" ? "action" : cat} />
              {!done?.ok && <Badge tone="bg-bad/10 text-bad">校验没通过,保存前需要修正</Badge>}
            </div>
            {draft.description && <p className="text-label text-muted">{draft.description}</p>}
            <SpecPreview kind={draft.kind} spec={draft.spec} onChange={(s) => setDraft({ ...draft, spec: s })} />
            {samples.length > 0 && (
              <div className="space-y-1.5">
                <p className="text-label font-medium">试跑样例</p>
                {samples.map((s, i) => (
                  <div key={i} className="rounded-md border border-line bg-surface p-2">
                    <div className="flex flex-wrap items-center gap-2 text-label">
                      <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>}
                      <button className="btn btn-sm" onClick={() => void trySample(i)}><Play className="h-3 w-3" />试跑</button>
                    </div>
                    {tries[i] && (tries[i].running ? <Spinner /> : <div className="mt-1.5"><ResultView data={tries[i]} /></div>)}
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
      </div>
    </Modal>
  );
}

function SpecPreview({ kind, spec, onChange }: { kind: string; spec: any; onChange: (s: any) => void }) {
  if (kind === "function" && spec.category === "decision") return <DecisionEditor spec={spec} onChange={onChange} canEdit />;
  if (kind === "function" && spec.category === "rule") {
    return (
      <div className="space-y-1">
        <input className="input font-mono" value={spec.expression || ""} onChange={(e) => onChange({ ...spec, expression: e.target.value })} />
        {spec.text && <p className="text-label text-muted">{spec.text}</p>}
      </div>
    );
  }
  if (kind === "action") {
    return (
      <div className="space-y-1 text-label">
        <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.effects || []).map((e: any, i: number) => <p key={i}>效果 {i + 1}:<code>{e.tool}</code> {JSON.stringify(e.args)}</p>)}
        <p>审批角色:{spec.approval?.approver_roles?.join("、") || "任何审批人"}</p>
      </div>
    );
  }
  return <pre className={cn("max-h-56 overflow-auto rounded bg-surface p-2 text-label")}>{JSON.stringify(spec, null, 2)}</pre>;
}