AskPanel.tsx 23.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
import { sql as sqlLang } from "@codemirror/lang-sql";
import CodeMirror from "@uiw/react-codemirror";
import {
  AlertTriangle, BookmarkPlus, Code2, CornerDownLeft, Database, Download, FileText,
  ListTree, Loader2, Play, RotateCw, Send, Square, Trash2,
} from "lucide-react";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { api } from "@/lib/api";
import { cn, formatDuration } from "@/lib/utils";
import { toast, useAppStore } from "@/store/useAppStore";
import { useSqlStore, type SqlTurn } from "@/store/useSqlStore";
import { Badge, Card, Collapse, CopyButton, Empty, Spinner } from "@/components/ui";
import type { SqlPair } from "@/lib/types";
import { SqlTrace } from "./SqlTrace";

const FALLBACK_EXAMPLES = [
  "各门店的成交金额排名",
  "问界品牌下有哪些门店",
  "上个月成交订单数最多的 10 家门店",
];

/** 正在干什么。轨迹事件 → 一句人话。
 *
 * 一个转圈的「处理中…」是这套界面最招人烦的地方:等 15 秒和卡死了长得一模一样。
 * 每个阶段说清楚在干什么,等待就从"不知道还要多久"变成"知道进行到哪了"。 */
function statusOf(turn: SqlTurn): string {
  if (turn.draftSql) return "正在写 SQL…";
  const last = turn.trace[turn.trace.length - 1];
  if (!last) return "正在连接…";
  switch (last.type) {
    case "start": return "正在召回相关的表、指标和沉淀…";
    case "retrieve": return "正在理解问题、确定口径和取数计划…";
    case "plan": return "正在写 SQL…";
    case "sql_draft": return "正在做只读与关联校验…";
    case "validate": return last.ok ? "正在执行查询…" : "校验没过,正在自愈重试…";
    case "repair": return "正在按报错重写 SQL…";
    case "execute": return "正在读取结果…";
    case "rows": return "正在总结结论…";
    default: return "处理中…";
  }
}

/** running 期间的秒表。没有它,用户对"慢"的感受是无限的 */
function useElapsed(active: boolean, since: number): number {
  const [now, setNow] = useState(Date.now());
  useEffect(() => {
    if (!active) return;
    const t = window.setInterval(() => setNow(Date.now()), 100);
    return () => window.clearInterval(t);
  }, [active]);
  return active ? now - since : 0;
}

export function AskPanel({ dsId, dsName }: { dsId: number; dsName: string }) {
  const { question, running, turns, setQuestion, setDsId, ask, stop, reset } = useSqlStore();
  const scrollRef = useRef<HTMLDivElement>(null);
  const boxRef = useRef<HTMLTextAreaElement>(null);
  const stick = useRef(true);
  const [examples, setExamples] = useState<string[]>(FALLBACK_EXAMPLES);

  useEffect(() => { setDsId(dsId); }, [dsId, setDsId]);

  // 空状态里的例句用**这个库真正答对过的问题**,比写死三条更有说服力,
  // 也顺便告诉新用户这套系统的能力边界在哪
  useEffect(() => {
    let alive = true;
    api.sqlPairs({ dsId, status: "verified", limit: 6 })
      .then((ps: SqlPair[]) => {
        if (!alive) return;
        const qs = ps.map((p) => p.question).filter(Boolean).slice(0, 4);
        if (qs.length >= 2) setExamples(qs);
      })
      .catch(() => undefined);
    return () => { alive = false; };
  }, [dsId]);

  // 跟随滚动,但用户往上翻了就别抢 —— 抢滚动条比不滚动更烦人
  const onScroll = useCallback(() => {
    const el = scrollRef.current;
    if (!el) return;
    stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
  }, []);
  useEffect(() => {
    if (!stick.current) return;
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  });

  const submit = (q?: string) => {
    stick.current = true;
    ask(q ? { question: q } : undefined);
    boxRef.current?.focus();
  };

  return (
    <div className="flex h-full min-h-0 flex-col gap-2.5">
      <div ref={scrollRef} onScroll={onScroll} className="min-h-0 flex-1 space-y-2.5 overflow-auto pr-0.5">
        {turns.length === 0 ? (
          // 撑满滚动区并居中。以前是一张贴在顶上的小卡片,下面留一大片空地,
          // 看起来像页面没加载完
          <Card className="flex h-full min-h-[260px] items-center justify-center">
            <Empty
              icon={<Database className="h-6 w-6" />}
              title={`向「${dsName}」提问`}
              desc="用大白话问就行。系统会先说清打算怎么取数,再生成 SQL;SQL 可以改,改完直接重跑。"
              action={
                <div className="flex max-w-xl flex-wrap justify-center gap-1.5">
                  {examples.map((e) => (
                    <button key={e} className="chip" onClick={() => submit(e)}>{e}</button>
                  ))}
                </div>
              } />
          </Card>
        ) : (
          turns.map((t) => <TurnCard key={t.id} turn={t} onAsk={submit} />)
        )}
      </div>

      <Card className="shrink-0 p-2.5">
        <div className="flex items-end gap-2">
          <textarea
            ref={boxRef}
            className="input max-h-40 min-h-[40px] resize-none py-2 leading-6"
            rows={1}
            placeholder="问点什么,比如「每个门店这个月的成交金额」"
            value={question}
            onChange={(e) => {
              setQuestion(e.target.value);
              // 跟着内容长高,但别长到把结果区挤没
              e.target.style.height = "auto";
              e.target.style.height = `${Math.min(160, e.target.scrollHeight)}px`;
            }}
            onKeyDown={(e) => {
              if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
                e.preventDefault();
                if (!running && question.trim()) submit();
              }
            }} />
          {running ? (
            <button className="btn btn-sm shrink-0" onClick={stop}>
              <Square className="h-3.5 w-3.5" /> 停止
            </button>
          ) : (
            <button className="btn btn-primary btn-sm shrink-0"
                    disabled={!question.trim()} onClick={() => submit()}>
              <CornerDownLeft className="h-3.5 w-3.5" /> 提问
            </button>
          )}
          {turns.length > 0 && !running && (
            <button className="btn btn-ghost btn-sm shrink-0" onClick={reset} title="清空对话">
              <Trash2 className="h-3.5 w-3.5" />
            </button>
          )}
        </div>
        <p className="mt-1.5 text-[11.5px] text-muted">
          Enter 提交,Shift + Enter 换行。所有查询都经过只读校验,并强制加上行数与超时限制。
        </p>
      </Card>
    </div>
  );
}

/** memo:流式增量每秒几十次 setState,不隔离的话每个 token 都要重渲染所有历史轮次 */
const TurnCard = memo(function TurnCard({ turn, onAsk }: {
  turn: SqlTurn; onAsk: (q: string) => void;
}) {
  const { setSql, rerun, ask, loadExplain } = useSqlStore();
  const theme = useAppStore((s) => s.theme);
  const dark = useMemo(() => {
    if (theme === "dark") return true;
    if (theme === "light") return false;
    return window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? false;
  }, [theme]);

  const [adopting, setAdopting] = useState(false);
  const [openSql, setOpenSql] = useState(false);
  const [openExplain, setOpenExplain] = useState(false);
  // 轨迹:跑的时候摊开(让人看见在干活),跑完收起(结论才是主角),
  // 出错了保持摊开 —— 那时候用户最需要知道是哪一步挂的
  const [openTrace, setOpenTrace] = useState(true);
  const settled = useRef(false);
  useEffect(() => {
    if (turn.running || settled.current) return;
    settled.current = true;
    setOpenTrace(!!turn.error);
  }, [turn.running, turn.error]);

  const elapsed = useElapsed(turn.running, turn.startedAt);

  // 解释是按需生成的:展开才去要,而且只要一次
  const toggleExplain = () => {
    const next = !openExplain;
    setOpenExplain(next);
    if (next) void loadExplain(turn.id);
  };

  const adopt = async () => {
    if (!turn.pairId) return;
    setAdopting(true);
    try {
      await api.adoptSqlPair(turn.pairId);
      toast("ok", "已采纳", "这条问答会作为示例,参与后续同类问题的生成");
    } catch (e) {
      toast("error", "采纳失败", e instanceof Error ? e.message : String(e));
    } finally { setAdopting(false); }
  };

  const awaitingPlan = turn.outcome === "await_plan";
  const liveSql = turn.draftSql || turn.sql;
  const hasResult = turn.columns.length > 0;
  const traceSteps = turn.trace.filter((e) => e.type !== "rows").length;
  const suggestions = useFollowUps(turn);

  return (
    <Card className="overflow-hidden">
      <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>
        {turn.running ? (
          <Badge tone="bg-brand/10 text-brand" className="shrink-0 tabular-nums">
            <Loader2 className="h-3 w-3 animate-spin" />
            {(elapsed / 1000).toFixed(1)}s
          </Badge>
        ) : turn.durationMs > 0 ? (
          <Badge tone="bg-ink/5 text-muted" className="shrink-0">{formatDuration(turn.durationMs)}</Badge>
        ) : null}
      </div>

      <div className="space-y-2.5 p-3.5">
        {turn.running && (
          <p className="flex items-center gap-2 text-[12.5px] text-muted">
            <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="relative inline-flex h-1.5 w-1.5 rounded-full bg-brand" />
            </span>
            {statusOf(turn)}
          </p>
        )}

        {turn.clarify && (
          <div className="rounded-lg border border-warn/40 bg-warn/5 p-3">
            <p className="text-[13px] font-medium text-warn">需要你确认一下</p>
            <p className="mt-1 text-[13px]">{turn.clarify}</p>
            <ClarifyReply question={turn.question} onAsk={onAsk} />
          </div>
        )}

        {awaitingPlan && turn.plan && (
          <div className="rounded-lg border border-brand/40 bg-brand/5 p-3">
            <p className="text-[13px] font-medium">确认查询计划后再生成 SQL</p>
            <p className="mt-1 text-[12.5px] text-muted">{turn.plan.summary}</p>
            <button className="btn btn-primary btn-sm mt-2"
                    onClick={() => ask({ question: turn.question, plan: turn.plan ?? undefined })}>
              计划没问题,生成 SQL
            </button>
          </div>
        )}

        {/* 元数据问题(「有哪些表」「这个字段什么意思」)不会产出 SQL。
            以前这类回答被整条丢掉,用户看到的是一张空卡片 —— 那正是"一大片空白"的来源。 */}
        {turn.answer && (
          <div className="prose-answer text-[13.5px]">
            <ReactMarkdown remarkPlugins={[remarkGfm]}>{turn.answer}</ReactMarkdown>
          </div>
        )}

        {turn.error && (
          <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" />
            <div className="min-w-0 flex-1">
              <p className="text-[13px] leading-relaxed text-bad">{turn.error}</p>
              <p className="mt-1 text-[11.5px] text-muted">
                可以换个说法再问一次,或展开下面的 SQL 自己改完重跑。
              </p>
            </div>
            <button className="btn btn-sm shrink-0" onClick={() => onAsk(turn.question)}>
              <RotateCw className="h-3.5 w-3.5" /> 重问
            </button>
          </div>
        )}

        {/* 结论放在最前面。用户问的是业务问题,SQL 和轨迹是给他验算用的 */}
        {(turn.summary || turn.summarizing) && (
          <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">
              结论
              {turn.summarizing && <Loader2 className="h-3 w-3 animate-spin" />}
            </p>
            {turn.summary ? (
              <div className="prose-answer text-[13.5px]">
                <ReactMarkdown remarkPlugins={[remarkGfm]}>{turn.summary}</ReactMarkdown>
              </div>
            ) : (
              <p className="text-[12.5px] text-muted">数据已经换了,正在重新给结论…</p>
            )}
          </div>
        )}

        {hasResult && (
          <ResultTable columns={turn.columns} rows={turn.rows}
                       truncated={turn.truncated} question={turn.question} />
        )}
        {!hasResult && turn.outcome === "ok" && !turn.running && (
          <p className="rounded-lg border border-line px-3 py-4 text-center text-[13px] text-muted">
            查询成功,但没有符合条件的数据。多半是过滤条件太严或时间范围不对。
          </p>
        )}

        {liveSql && (
          <Collapse
            open={openSql || !!turn.draftSql}
            onToggle={() => setOpenSql((v) => !v)}
            icon={<Code2 className="h-3.5 w-3.5" />}
            title="SQL"
            summary={turn.draftSql ? "生成中…" : oneLine(turn.sql)}
            right={
              <>
                {turn.edited && <Badge tone="bg-warn/10 text-warn">已修改</Badge>}
                {turn.issues.some((i) => i.level === "error") && (
                  <Badge tone="bg-bad/10 text-bad">校验有问题</Badge>
                )}
                <CopyButton text={turn.sql || turn.draftSql} label="" />
              </>
            }>
            {turn.draftSql ? (
              // 流式阶段用 pre:CodeMirror 每个 token 重建编辑器状态,几十次/秒会明显卡
              <pre className="max-h-[260px] overflow-auto rounded-md bg-ink/[0.05] p-2.5
                              font-mono text-[12px] leading-relaxed">
                {turn.draftSql}
                <span className="ml-0.5 inline-block h-3.5 w-1.5 animate-pulse bg-brand align-middle" />
              </pre>
            ) : (
              <>
                <div className="overflow-hidden rounded-md border border-line">
                  <CodeMirror
                    value={turn.sql}
                    height="auto"
                    maxHeight="260px"
                    theme={dark ? "dark" : "light"}
                    extensions={[sqlLang()]}
                    basicSetup={{ lineNumbers: true, foldGutter: false, highlightActiveLine: false }}
                    onChange={(v) => setSql(turn.id, v)} />
                </div>
                {turn.issues.length > 0 && (
                  <ul className="mt-1.5 space-y-0.5">
                    {turn.issues.map((it, i) => (
                      <li key={i} className={cn("text-[11.5px]",
                        it.level === "error" ? "text-bad" : "text-warn")}>
                        {it.msg}{it.fix && <span className="text-muted"> — {it.fix}</span>}
                      </li>
                    ))}
                  </ul>
                )}
                <div className="mt-2 flex flex-wrap items-center gap-1.5">
                  <button className="btn btn-sm" disabled={turn.running || !turn.sql.trim()}
                          onClick={() => rerun(turn.id)}>
                    {turn.running ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                  : <Play className="h-3.5 w-3.5" />}
                    {turn.edited ? "用修改后的 SQL 重跑" : "重跑"}
                  </button>
                  {turn.pairId > 0 && (
                    <button className="btn btn-sm" disabled={adopting} onClick={adopt}
                            title="采纳后这条会进入示例库,让同类问题问得更准">
                      <BookmarkPlus className="h-3.5 w-3.5" /> 采纳为示例
                    </button>
                  )}
                </div>
              </>
            )}
          </Collapse>
        )}

        {turn.sql && !turn.running && (
          <Collapse open={openExplain} onToggle={toggleExplain}
                    icon={<FileText className="h-3.5 w-3.5" />}
                    title="这条 SQL 在做什么"
                    summary="用业务语言说一遍,不用懂 SQL 也能核对">
            {turn.explain ? (
              <div className="prose-answer text-[13px]">
                <ReactMarkdown remarkPlugins={[remarkGfm]}>{turn.explain}</ReactMarkdown>
              </div>
            ) : (
              <p className="flex items-center gap-2 text-[12.5px] text-muted">
                <Loader2 className="h-3.5 w-3.5 animate-spin" /> 正在翻译成业务语言…
              </p>
            )}
          </Collapse>
        )}

        {traceSteps > 0 && (
          <Collapse open={openTrace} onToggle={() => setOpenTrace((v) => !v)}
                    icon={<ListTree className="h-3.5 w-3.5" />}
                    title="执行轨迹"
                    tone={turn.error ? "border-bad/30" : undefined}
                    summary={traceSummary(turn)}>
            <SqlTrace trace={turn.trace} running={turn.running} />
          </Collapse>
        )}

        {suggestions.length > 0 && !turn.running && (
          <div className="flex flex-wrap items-center gap-1.5 pt-0.5">
            <span className="text-[11.5px] text-muted">接着问:</span>
            {suggestions.map((s) => (
              <button key={s} className="chip text-[11.5px]" onClick={() => onAsk(s)}>
                <Send className="h-3 w-3 text-muted" />{s}
              </button>
            ))}
          </div>
        )}
      </div>
    </Card>
  );
});

/** 澄清问题可以直接在原地补答,不用回到输入框重打一遍完整问句 */
function ClarifyReply({ question, onAsk }: { question: string; onAsk: (q: string) => void }) {
  const [text, setText] = useState("");
  const send = () => {
    if (!text.trim()) return;
    onAsk(`${question}(补充说明:${text.trim()})`);
    setText("");
  };
  return (
    <div className="mt-2 flex items-center gap-1.5">
      <input className="input py-1 text-[12.5px]" placeholder="在这儿补一句,比如「按自然月,只看问界」"
             value={text} onChange={(e) => setText(e.target.value)}
             onKeyDown={(e) => { if (e.key === "Enter" && !e.nativeEvent.isComposing) send(); }} />
      <button className="btn btn-sm shrink-0" disabled={!text.trim()} onClick={send}>
        <Send className="h-3.5 w-3.5" /> 补充后重问
      </button>
    </div>
  );
}

/** 折叠状态下也要一眼看出这条走得顺不顺 */
function traceSummary(turn: SqlTurn): string {
  const parts: string[] = [];
  const retrieve = turn.trace.find((e) => e.type === "retrieve");
  if (retrieve && retrieve.type === "retrieve") parts.push(`召回 ${retrieve.models.length} 张表`);
  const repairs = turn.trace.filter((e) => e.type === "repair").length;
  if (repairs > 0) parts.push(`自愈 ${repairs} 轮`);
  const exec = turn.trace.find((e) => e.type === "execute");
  if (exec && exec.type === "execute") parts.push(`执行 ${formatDuration(exec.duration_ms)}`);
  if (turn.error) parts.push("有失败步骤");
  return parts.join(" · ");
}

/**
 * 追问建议。刻意**不**再调一次大模型 —— 建议只从这轮真实用到的语义对象里长出来:
 * 召回到但没用上的指标、结果的行数。凭空编出来的追问点不开,比没有更伤信任。
 */
function useFollowUps(turn: SqlTurn): string[] {
  return useMemo(() => {
    if (turn.outcome !== "ok" || turn.columns.length === 0) return [];
    const out: string[] = [];
    const retrieve = turn.trace.find((e) => e.type === "retrieve");
    if (retrieve && retrieve.type === "retrieve") {
      for (const m of retrieve.metrics) {
        if (out.length >= 2) break;
        if (!turn.question.includes(m.name)) out.push(`同样的范围,换成「${m.name}」看`);
      }
    }
    if (turn.rows.length > 10) out.push("只看前 10 名");
    if (turn.plan?.time_range) {
      // 别推荐用户刚问过的那个时间段 —— 「上个月的…」后面跟一条「换成上个月」
      // 一眼就能看出这些建议是套模板凑出来的
      const asked = /上个月|上月|last month/i.test(turn.question);
      out.push(asked ? "换成最近一个月,口径不变" : "换成上个月,口径不变");
    }
    return out.slice(0, 3);
  }, [turn.outcome, turn.columns.length, turn.rows.length, turn.trace, turn.plan, turn.question]);
}

function oneLine(sql: string): string {
  return sql.replace(/\s+/g, " ").trim().slice(0, 120);
}

/** 整数加千分位,小数保留原样。业务同事看的是金额和台数,裸数字很难读 */
function fmtCell(v: unknown): string {
  if (typeof v === "number" && Number.isFinite(v)) {
    return Number.isInteger(v) ? v.toLocaleString() : String(v);
  }
  return String(v);
}

function toCsv(columns: string[], rows: unknown[][]): string {
  const esc = (v: unknown) => {
    const s = v === null || v === undefined ? "" : String(v);
    return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
  };
  return [columns.map(esc).join(","), ...rows.map((r) => r.map(esc).join(","))].join("\n");
}

function ResultTable({ columns, rows, truncated, question }: {
  columns: string[]; rows: unknown[][]; truncated: boolean; question: string;
}) {
  const [expanded, setExpanded] = useState(false);
  const shown = expanded ? rows : rows.slice(0, 20);

  const download = () => {
    // Excel 认 BOM,不加的话中文列名全是乱码
    const blob = new Blob(["" + toCsv(columns, rows)], { type: "text/csv;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `${question.slice(0, 30).replace(/[\\/:*?"<>|]/g, "") || "query"}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div>
      <div className="mb-1.5 flex flex-wrap items-center gap-1.5 text-[12px] text-muted">
        <span className="font-medium">结果</span>
        <Badge tone="bg-ok/10 text-ok">{rows.length} 行 × {columns.length} 列</Badge>
        {truncated && <Badge tone="bg-warn/10 text-warn">已达行数上限,结果被截断</Badge>}
        <span className="flex-1" />
        <CopyButton text={toCsv(columns, rows)} label="复制" />
        <button className="btn btn-ghost btn-sm" onClick={download} title="导出为 CSV">
          <Download className="h-3.5 w-3.5" /> CSV
        </button>
      </div>
      {/* 宽表一律横向滚动,别把整页撑出横向滚动条 */}
      <div className="max-h-[420px] overflow-auto rounded-lg border border-line">
        <table className="w-full border-collapse text-[12.5px]">
          <thead className="sticky top-0 z-10">
            <tr className="bg-elevated">
              {columns.map((c) => (
                <th key={c} className="whitespace-nowrap border-b border-line bg-elevated px-2.5 py-1.5
                                       text-left font-medium">
                  {c}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {shown.map((r, i) => (
              <tr key={i} className="border-b border-line last:border-0 hover:bg-ink/[0.02]">
                {r.map((v, j) => (
                  <td key={j} className="whitespace-nowrap px-2.5 py-1.5 tabular-nums">
                    {v === null || v === undefined
                      ? <span className="text-muted">NULL</span>
                      : fmtCell(v)}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {rows.length > 20 && (
        <button className="btn btn-ghost btn-sm mt-1" onClick={() => setExpanded(!expanded)}>
          {expanded ? "只看前 20 行" : `展开全部 ${rows.length} 行`}
        </button>
      )}
    </div>
  );
}