LibraryPanel.tsx 11.3 KB
import { Ban, BookmarkCheck, Clock, Flame, Search, Trash2 } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { api } from "@/lib/api";
import { cn, formatTime } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import {
  Badge, Card, CardHeader, Confirm, CopyButton, Empty, ErrorNote, Modal, Segmented, Spinner,
} from "@/components/ui";
import type { SqlPair } from "@/lib/types";

/**
 * 沉淀库。
 *
 * 这里堆的是「跑通过的问答对」,而只有 verified 的那些才会当 few-shot 参与生成 ——
 * 所以页面的首要职责是**让人分得清哪些在生效**,其次才是翻历史。
 * 以前是一条一条平铺、每条都把整段 SQL 摊开,几十条下去全是代码块,
 * 正在生效的那几条反而找不到。现在:先按状态分段、默认收起 SQL、详情点开看。
 */
const STATUS_META: Record<string, { label: string; tone: string; hint: string }> = {
  draft: { label: "草稿", tone: "bg-warn/10 text-warn", hint: "自动捕获,还没人确认过,不参与生成" },
  verified: { label: "已采纳", tone: "bg-ok/10 text-ok", hint: "会作为示例参与同类问题的生成" },
  deprecated: { label: "已停用", tone: "bg-ink/5 text-muted", hint: "不再参与生成" },
};

const SOURCE_TEXT: Record<string, string> = {
  auto: "执行成功自动留存",
  user_saved: "人工保存",
  user_edited: "用户改过 SQL 后跑通",
};

type Filter = "" | "verified" | "draft" | "deprecated";
type Sort = "smart" | "recent" | "hit";

export function LibraryPanel({ dsId }: { dsId: number }) {
  const [items, setItems] = useState<SqlPair[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [status, setStatus] = useState<Filter>("");
  const [sort, setSort] = useState<Sort>("smart");
  const [keyword, setKeyword] = useState("");
  const [detail, setDetail] = useState<SqlPair | null>(null);
  const [confirmDel, setConfirmDel] = useState<SqlPair | null>(null);

  const load = useCallback(() => {
    api.sqlPairs({ dsId, status: status || undefined, keyword })
      .then((d) => { setItems(d); setError(null); })
      .catch((e) => setError(e instanceof Error ? e.message : String(e)));
  }, [dsId, status, keyword]);

  useEffect(() => {
    const t = window.setTimeout(load, keyword ? 250 : 0);
    return () => window.clearTimeout(t);
  }, [load, keyword]);

  const setPairStatus = async (p: SqlPair, next: string) => {
    try {
      if (next === "verified") await api.adoptSqlPair(p.id);
      else await api.updateSqlPair(p.id, { status: next });
      toast("ok", next === "verified" ? "已采纳" : "已停用",
            next === "verified" ? "同类问题之后会参照这条来生成" : undefined);
      setDetail(null);
      load();
    } catch (e) {
      toast("error", "操作失败", e instanceof Error ? e.message : String(e));
    }
  };

  const remove = async (p: SqlPair) => {
    try {
      await api.deleteSqlPair(p.id);
      setDetail(null);
      load();
    } catch (e) {
      toast("error", "删除失败", e instanceof Error ? e.message : String(e));
    }
    setConfirmDel(null);
  };

  /** 默认排序刻意不是「按时间倒序」:
   *  生效中的(verified)永远排最前,其次是等人确认的草稿,停用的沉底。
   *  这个库是用来「管哪些在生效」的,不是用来翻流水账的。 */
  const sorted = useMemo(() => {
    const list = [...(items ?? [])];
    const rank = (p: SqlPair) => (p.status === "verified" ? 0 : p.status === "draft" ? 1 : 2);
    const time = (p: SqlPair) => new Date(p.created_at ?? 0).getTime();
    if (sort === "recent") return list.sort((a, b) => time(b) - time(a));
    if (sort === "hit") return list.sort((a, b) => b.hit_count - a.hit_count || time(b) - time(a));
    return list.sort((a, b) =>
      rank(a) - rank(b) || b.hit_count - a.hit_count || time(b) - time(a));
  }, [items, sort]);

  if (error) return <ErrorNote onRetry={load}>{error}</ErrorNote>;

  const all = items ?? [];
  const counts = {
    verified: all.filter((p) => p.status === "verified").length,
    draft: all.filter((p) => p.status === "draft").length,
  };

  return (
    <Card>
      <CardHeader
        title="沉淀库"
        desc="跑通的问答会自动存成草稿;点「采纳」升级后,才会作为示例参与后续生成。"
        right={
          <Segmented<Sort> value={sort} onChange={setSort} options={[
            { key: "smart", label: "生效优先" },
            { key: "hit", label: "按命中" },
            { key: "recent", label: "按时间" },
          ]} />
        } />

      <div className="flex flex-wrap items-center gap-2 border-b border-line px-4 pb-3">
        <div className="relative min-w-[200px] flex-1">
          <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 pl-8" placeholder="搜问题"
                 value={keyword} onChange={(e) => setKeyword(e.target.value)} />
        </div>
        <Segmented<Filter> value={status} onChange={setStatus} options={[
          { key: "", label: "全部" },
          { key: "verified", label: "生效中" },
          { key: "draft", label: "待确认" },
          { key: "deprecated", label: "已停用" },
        ]} />
      </div>

      {!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">
          <span className="text-ok">{counts.verified} 条正在参与生成</span>
          {counts.draft > 0 && <> · {counts.draft} 条草稿等你确认,确认之后才会生效</>}
        </p>
      )}

      {!items ? (
        <div className="p-4"><Spinner /></div>
      ) : sorted.length === 0 ? (
        <Empty icon={<BookmarkCheck className="h-6 w-6" />}
               title={keyword || status ? "没有匹配的沉淀" : "还没有沉淀"}
               desc={keyword || status ? undefined : "在「问答」页跑通一个问题,它就会自动出现在这里。"} />
      ) : (
        <div className="divide-y divide-line">
          {sorted.map((p) => (
            <div key={p.id}
                 className={cn("flex items-center gap-2 px-4 py-2.5 transition-colors hover:bg-ink/[0.02]",
                   p.status === "deprecated" && "opacity-55")}>
              <button className="min-w-0 flex-1 text-left" onClick={() => setDetail(p)}>
                <span className="flex flex-wrap items-center gap-1.5">
                  <span className="min-w-0 truncate text-[13.5px] font-medium">{p.question}</span>
                  <Badge tone={STATUS_META[p.status]?.tone}>
                    {STATUS_META[p.status]?.label ?? p.status}
                  </Badge>
                  {p.hit_count > 0 && (
                    <Badge tone="bg-brand/10 text-brand" >
                      <Flame className="h-3 w-3" />{p.hit_count}
                    </Badge>
                  )}
                  {p.sql_before && <Badge tone="bg-warn/10 text-warn">人工修正过</Badge>}
                </span>
                {/* SQL 只给一行预览。要看全文点开详情 —— 几十条代码块摊在列表里
                    只会把真正要管的状态信息淹掉 */}
                <span className="mt-0.5 block truncate font-mono text-[11px] text-muted">
                  {p.sql.replace(/\s+/g, " ").trim()}
                </span>
              </button>
              <div className="flex shrink-0 items-center gap-1">
                {p.status !== "verified" ? (
                  <button className="btn btn-sm" onClick={() => setPairStatus(p, "verified")}>
                    <BookmarkCheck className="h-3.5 w-3.5" /> 采纳
                  </button>
                ) : (
                  <button className="btn btn-ghost btn-sm" onClick={() => setPairStatus(p, "deprecated")}
                          title="停用后不再参与生成">
                    <Ban className="h-3.5 w-3.5" />
                  </button>
                )}
                <button className="btn btn-ghost btn-sm text-bad" onClick={() => setConfirmDel(p)}>
                  <Trash2 className="h-3.5 w-3.5" />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      <Modal
        open={!!detail} onClose={() => setDetail(null)} width="max-w-3xl"
        title={detail?.question ?? ""}
        desc={detail ? STATUS_META[detail.status]?.hint : undefined}
        footer={detail && (
          <>
            <span className="mr-auto text-[11.5px] text-muted">
              {SOURCE_TEXT[detail.source] ?? detail.source} · {formatTime(detail.created_at)}
            </span>
            {detail.status !== "verified" ? (
              <button className="btn btn-primary btn-sm" onClick={() => setPairStatus(detail, "verified")}>
                <BookmarkCheck className="h-3.5 w-3.5" /> 采纳为示例
              </button>
            ) : (
              <button className="btn btn-sm" onClick={() => setPairStatus(detail, "deprecated")}>
                <Ban className="h-3.5 w-3.5" /> 停用
              </button>
            )}
          </>
        )}>
        {detail && (
          <div className="space-y-3">
            <div className="flex flex-wrap items-center gap-1.5">
              <Badge tone={STATUS_META[detail.status]?.tone}>
                {STATUS_META[detail.status]?.label ?? detail.status}
              </Badge>
              <Badge tone="bg-ink/5 text-muted">
                <Clock className="h-3 w-3" />{formatTime(detail.created_at)}
              </Badge>
              {detail.hit_count > 0 && (
                <Badge tone="bg-brand/10 text-brand">被复用 {detail.hit_count} 次</Badge>
              )}
              {detail.models_used.map((t) => (
                <Badge key={t} tone="bg-ink/5 text-muted">{t}</Badge>
              ))}
            </div>

            <div>
              <div className="mb-1 flex items-center gap-1.5">
                <span className="text-[12px] font-medium text-muted">实际执行的 SQL</span>
                <span className="flex-1" />
                <CopyButton text={detail.sql} />
              </div>
              <pre className="overflow-x-auto rounded-md bg-ink/[0.05] p-2.5 font-mono
                              text-[11.5px] leading-relaxed">{detail.sql}</pre>
            </div>

            {detail.sql_before && (
              <div>
                <p className="mb-1 text-[12px] font-medium text-muted">
                  模型原本生成的版本(被人工改掉了)
                </p>
                <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>
                <p className="mt-1 text-[11.5px] text-muted">
                  这种「改过才跑通」的记录最值钱:它直接标出了模型的系统性偏差。
                  采纳之后,同类问题会照着改后的版本生成。
                </p>
              </div>
            )}
          </div>
        )}
      </Modal>

      <Confirm
        open={!!confirmDel} danger title="删除这条沉淀?"
        body={confirmDel?.question ?? ""} confirmText="删除"
        onConfirm={() => confirmDel && remove(confirmDel)}
        onClose={() => setConfirmDel(null)} />
    </Card>
  );
}