AskPage.tsx 16.2 KB
import { MessageSquarePlus, PanelRightClose, PanelRightOpen, Send, Square } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { Modal } from "@/components/ui";
import { api } from "@/lib/api";
import { go, useHashParams } from "@/lib/nav";
import type { ChunkRecord } from "@/lib/types";
import { errText, onto, type Turn } from "@/lib/onto";
import { streamSSE, type SSEHandle } from "@/lib/sse";
import { toast, loadFailed } from "@/store/useAppStore";
import { Welcome, TurnView } from "./AskTurn";
import { ConversationList } from "./ConversationList";
import { ReasoningPanel, type PanelTab } from "./ReasoningPanel";
import type { ConvBrief, LiveTurn, TurnStatus } from "./askTypes";
import { applyEvent, emptyTrace, foldEvents, type TraceState } from "./trace";

let seq = 0;
const newKey = () => `t${Date.now()}-${seq++}`;

/** 老版本存的轮次没有轨迹:用计划和步骤拼一个最小的推理链,界面照样能看。 */
function legacyTrace(t: Turn): { trace: TraceState; events: any[] } {
  const events: any[] = [{ type: "link", ...t.links, ts: 0 }];
  if (t.plan && Object.keys(t.plan).length) events.push({ type: "plan", span: "lead", ...t.plan, ts: 1 });
  events.push({ type: "agent_start", span: "lead", agent: "lead", label: "主持", task: t.question, ts: 1 });
  t.steps.forEach((s: any, i: number) => {
    const span = s.id || `s${i + 1}`;
    events.push({ type: "tool_start", span, parent: "lead", agent: s.agent || "lead", tool: s.call, label: s.call,
                  args: s.args, why: s.why, ts: 2 + i });
    events.push({ type: "tool_done", span, ok: !s.error, summary: s.summary, error: s.error, ts: 2 + i });
  });
  events.push({ type: "agent_done", span: "lead", ok: true, summary: "", ts: 99 });
  return { trace: foldEvents(events), events };
}

function fromTurn(t: Turn): LiveTurn {
  const lt = legacyTrace(t);
  return {
    key: t.id || newKey(), id: t.id, question: t.question,
    status: (["running", "done", "aborted", "error"].includes(t.status) ? t.status : "done") as TurnStatus,
    trace: lt.trace, events: lt.events, hasTrace: !!t.has_trace,
    answer: t.answer, citations: t.citations, data_refs: t.data_refs, actions: t.actions, sops: t.sops,
    follow_ups: Array.isArray(t.plan?.follow_ups) ? t.plan.follow_ups : [], plan: t.plan,
    duration_ms: t.duration_ms, rating: t.rating,
  };
}

const PANEL_KEY = "onto.ask.panel";

/** 上次看的对话:切到别的页面再回来,接着看它(回答在后台照常跑完,不会丢)。 */
let lastConv = "";

/** 宽屏(≥1280)推理面板常驻右侧;窄屏按需从右侧滑出,不挡对话。 */
function useWide(): boolean {
  const q = "(min-width: 1280px)";
  const [wide, setWide] = useState(() => window.matchMedia(q).matches);
  useEffect(() => {
    const m = window.matchMedia(q);
    const on = () => setWide(m.matches);
    m.addEventListener("change", on);
    return () => m.removeEventListener("change", on);
  }, []);
  return wide;
}

export function AskPage() {
  const [convs, setConvs] = useState<ConvBrief[]>([]);
  const [convId, setConvId] = useState("");
  const convRef = useRef("");            // 当前打开的对话(事件回调里要读最新值)
  const liveConv = useRef("");           // 正在回答的那个问题属于哪个对话
  convRef.current = convId;
  const [turns, setTurns] = useState<LiveTurn[]>([]);
  const [input, setInput] = useState("");
  const [running, setRunning] = useState(false);
  const [examples, setExamples] = useState<string[]>([]);
  const [selected, setSelected] = useState("");
  const [panelOpen, setPanelOpen] = useState(() => {
    try { return localStorage.getItem(PANEL_KEY) !== "0"; } catch { return true; }
  });
  const [tab, setTab] = useState<PanelTab>("chain");
  const wide = useWide();
  const [drawer, setDrawer] = useState(false);
  const showPanel = wide ? panelOpen : drawer;
  const openPanel = () => (wide ? setPanelOpen(true) : setDrawer(true));
  const closePanel = () => (wide ? setPanelOpen(false) : setDrawer(false));
  const [loadingConv, setLoadingConv] = useState(false);
  const [chunk, setChunk] = useState<ChunkRecord | null>(null);
  const openChunk = (id: string) => {
    void api.chunk(id).then(setChunk).catch((e) => toast("error", "原文打不开", errText(e)));
  };
  const handle = useRef<SSEHandle | null>(null);
  const replayTimer = useRef<number | null>(null);
  const bottom = useRef<HTMLDivElement>(null);
  const liveKey = useRef("");

  const loadConvs = useCallback(() => { void onto.conversations().then((c) => setConvs(Array.isArray(c) ? c : [])).catch((e) => { setConvs([]); loadFailed(e); }); }, []);
  useEffect(() => {
    loadConvs();
    // 示例问题和工作台同一份:按本体里真有的指标、维度、动作生成
    void onto.workbench().then((w) => setExamples(w?.questions?.length ? w.questions : ["本体里有哪些指标?", "能帮我做什么?"]))
      .catch(() => setExamples(["本体里有哪些指标?"]));
    return () => { handle.current?.abort(); stopReplay(); };
  }, [loadConvs]); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    try { localStorage.setItem(PANEL_KEY, panelOpen ? "1" : "0"); } catch { /* 隐私模式 */ }
  }, [panelOpen]);

  const lastLen = useRef(0);
  useEffect(() => {
    // 只在新增一轮、或正在作答时跟随到底部;看历史时不抢滚动条
    if (turns.length !== lastLen.current || running) bottom.current?.scrollIntoView({ behavior: "smooth", block: "end" });
    lastLen.current = turns.length;
  }, [turns, running]);

  const patch = (key: string, fn: (t: LiveTurn) => LiveTurn) =>
    setTurns((ts) => ts.map((t) => (t.key === key ? fn(t) : t)));

  const abortLive = () => {
    if (handle.current) {
      // 先告诉后端「停」;光断开连接只代表我不听了,后端会继续把这一轮答完
      const turnId = turns.find((t) => t.key === liveKey.current)?.id;
      if (turnId) void onto.stopAsk(turnId).catch(() => undefined);
      handle.current.abort();
      handle.current = null;
      const k = liveKey.current;
      if (k) patch(k, (t) => (t.status === "running" ? { ...t, status: "aborted" } : t));
    }
    setRunning(false);
  };

  const stopReplay = () => {
    if (replayTimer.current) window.clearTimeout(replayTimer.current);
    replayTimer.current = null;
  };

  const openConv = async (id: string, quiet = false) => {
    // 切换对话不打断正在回答的问题:它在后台继续,回到那个对话就能看到结果
    stopReplay();
    setConvId(id);
    lastConv = id;
    if (!quiet) { setLoadingConv(true); go("ask", { c: id }); }
    try {
      const c = await onto.conversation(id);
      const list = c.turns.map(fromTurn);
      setTurns(list);
      setSelected(list.length ? list[list.length - 1].key : "");
      // 有完整轨迹的轮次,把轨迹补回来(历史对话可以原样查看与回放)
      const withTrace = c.turns.filter((t) => t.has_trace);
      const traces = await Promise.all(withTrace.map((t) => onto.askTrace(t.id).catch(() => null)));
      setTurns((ts) => ts.map((t) => {
        const i = withTrace.findIndex((x) => x.id === t.id);
        const tr = i >= 0 ? traces[i] : null;
        return tr && tr.events.length ? { ...t, trace: foldEvents(tr.events), events: tr.events } : t;
      }));
    } catch (e) {
      toast("error", "打开对话失败", errText(e));
    } finally {
      setLoadingConv(false);
    }
  };

  // 从工作台带着问题跳过来(#/ask?q=...):直接问
  const hp = useHashParams();
  const asked = useRef("");
  useEffect(() => {
    const q = hp.get("q");
    if (q && asked.current !== q && !running) { asked.current = q; ask(q); go("ask"); }
  }, [hp]); // eslint-disable-line react-hooks/exhaustive-deps

  const newConv = () => { stopReplay(); lastConv = ""; setConvId(""); setTurns([]); setSelected(""); go("ask"); };

  // 地址里带着对话编号(刷新、复制链接给同事):打开它;
  // 从别的页面点回来、地址里什么都没有:接着看上次那个对话
  useEffect(() => {
    const c = hp.get("c");
    if (c && c !== convRef.current) { void openConv(c, true); return; }
    if (!c && !hp.get("q") && lastConv && !convRef.current) void openConv(lastConv);
  }, [hp]); // eslint-disable-line react-hooks/exhaustive-deps

  // 回到一个还在后台回答的对话:隔几秒看一眼,答完了就显示出来
  const pending = turns.some((t) => t.status === "running" && t.key !== liveKey.current);
  useEffect(() => {
    if (!pending || !convId) return undefined;
    const h = window.setInterval(() => { void openConv(convId, true); }, 4000);
    return () => window.clearInterval(h);
  }, [pending, convId]); // eslint-disable-line react-hooks/exhaustive-deps

  const ask = (q?: string) => {
    const question = (q ?? input).trim();
    if (!question || running) return;
    stopReplay();
    setInput("");
    setRunning(true);
    const key = newKey();
    liveKey.current = key;
    liveConv.current = convId;
    setSelected(key);
    setTurns((ts) => [...ts, {
      key, id: "", question, status: "running", trace: emptyTrace(), events: [], hasTrace: true, answer: "",
      citations: [], data_refs: [], actions: [], sops: [], follow_ups: [], plan: null, rating: 0,
    }]);
    const h = streamSSE<any>("/api/ask", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ question, conversation_id: convId }),
    }, (ev) => {
      if (!ev || typeof ev !== "object") return;
      switch (ev.type) {
        case "start":
          liveConv.current = ev.conversation_id || liveConv.current;
          if (ev.conversation_id) lastConv = ev.conversation_id;
          if (!convId && ev.conversation_id && !convRef.current) { setConvId(ev.conversation_id); go("ask", { c: ev.conversation_id }); }
          patch(key, (t) => ({ ...t, id: ev.turn_id || t.id }));
          break;
        case "answer_start":
          break;
        case "answer_delta":
          patch(key, (t) => ({ ...t, answer: t.answer + (ev.text || "") }));
          break;
        case "actions":
          patch(key, (t) => ({ ...t, actions: Array.isArray(ev.items) ? ev.items : [] }));
          break;
        case "sops":
          patch(key, (t) => ({ ...t, sops: Array.isArray(ev.items) ? ev.items : [] }));
          break;
        case "answer":
          patch(key, (t) => ({
            ...t, answer: ev.answer ?? t.answer, citations: ev.citations || [], data_refs: ev.data_refs || [],
            actions: ev.actions || [], sops: ev.sops || [], follow_ups: ev.follow_ups || [], plan: ev.plan || t.plan,
            duration_ms: ev.duration_ms, status: "done",
          }));
          break;
        case "error":
          patch(key, (t) => ({ ...t, error: ev.error, status: "error" }));
          break;
        case "done":
          patch(key, (t) => ({ ...t, status: t.status === "running" ? "done" : t.status }));
          break;
        default:
          patch(key, (t) => ({ ...t, trace: applyEvent(t.trace, ev), events: [...t.events, ev] }));
      }
    }, (err) => {
      patch(key, (t) => ({ ...t, error: err.message, status: "error" }));
    });
    handle.current = h;
    void h.done.finally(() => {
      if (handle.current === h) handle.current = null;
      liveKey.current = "";
      setRunning(false);
      loadConvs();
    });
  };

  /** 演示回放:把落库的事件按原来的节奏重新喂一遍(思考逐字打出来),给领导看、也方便复盘。 */
  const replay = (key: string) => {
    const t = turns.find((x) => x.key === key);
    if (!t || !t.events.length) return;
    stopReplay();
    setSelected(key);
    openPanel();
    const queue: { ev: any; wait: number }[] = [];
    let prevTs = 0;
    for (const ev of t.events) {
      const ts = typeof ev.ts === "number" ? ev.ts : prevTs;
      const gap = Math.min(900, Math.max(60, (ts - prevTs) / 3));
      prevTs = ts;
      if (ev.type === "thought" && typeof ev.text === "string" && ev.text.length > 12) {
        const parts = ev.text.match(/[\s\S]{1,6}/g) || [];
        parts.forEach((p: string, i: number) => queue.push({ ev: { ...ev, text: p }, wait: i === 0 ? gap : 28 }));
      } else {
        queue.push({ ev, wait: gap });
      }
    }
    patch(key, (x) => ({ ...x, trace: emptyTrace(), replaying: true }));
    let i = 0;
    const step = () => {
      if (i >= queue.length) {
        patch(key, (x) => ({ ...x, replaying: false }));
        replayTimer.current = null;
        return;
      }
      const { ev } = queue[i++];
      patch(key, (x) => ({ ...x, trace: applyEvent(x.trace, ev) }));
      replayTimer.current = window.setTimeout(step, queue[i]?.wait ?? 0);
    };
    replayTimer.current = window.setTimeout(step, 200);
  };

  const sel = turns.find((t) => t.key === selected) || turns[turns.length - 1];

  return (
    <div className="flex h-full min-h-0 gap-3">
      <ConversationList convs={convs} current={convId} answering={running ? liveConv.current : ""}
                        onNew={newConv} onOpen={(id) => void openConv(id)} onChanged={loadConvs}
                        onDeleted={(id) => { if (id === convId) newConv(); loadConvs(); }} />

      {/* 对话 */}
      <div className="flex min-w-0 flex-1 flex-col">
        <div className="flex items-center justify-end gap-2 pb-2">
          <button className="btn btn-ghost btn-sm lg:hidden" onClick={newConv}><MessageSquarePlus className="h-3.5 w-3.5" /> 新对话</button>
          <button className="btn btn-ghost btn-sm text-muted" onClick={() => (showPanel ? closePanel() : openPanel())}
                  title={showPanel ? "收起右边的过程" : "看这个答案是怎么得出来的"}>
            {showPanel ? <PanelRightClose className="h-4 w-4" /> : <PanelRightOpen className="h-4 w-4" />}
            {showPanel ? "收起" : "看过程"}
          </button>
        </div>
        <div className="min-h-0 flex-1 overflow-auto pr-1">
          {loadingConv && !turns.length ? (
            <p className="p-6 text-center text-label text-muted">正在打开对话…</p>
          ) : turns.length === 0 ? (
            <Welcome examples={examples} onAsk={ask} />
          ) : (
            <div className="mx-auto max-w-5xl space-y-6 pb-4">
              {turns.map((t) => (
                <TurnView key={t.key} t={t} onAsk={ask} active={sel?.key === t.key}
                          onSelect={() => { setSelected(t.key); openPanel(); }}
                          onReplay={() => replay(t.key)} disabled={running} />
              ))}
              <div ref={bottom} />
            </div>
          )}
        </div>
        <div className="mx-auto w-full max-w-5xl pt-3">
          <div className="card flex items-end gap-2 p-2">
            <textarea className="input min-h-[44px] flex-1 resize-none border-0 focus:ring-0" rows={2}
                      placeholder="问知识、问数据、问怎么办。Enter 发送,Shift+Enter 换行"
                      value={input} onChange={(e) => setInput(e.target.value)}
                      onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); ask(); } }} />
            {running ? (
              <button className="btn" onClick={abortLive}><Square className="h-3.5 w-3.5" /> 停止</button>
            ) : (
              <button className="btn btn-primary" disabled={!input.trim()} onClick={() => ask()}>
                <Send className="h-4 w-4" /> 发送
              </button>
            )}
          </div>
        </div>
      </div>

      {showPanel && (
        <ReasoningPanel turn={sel} wide={wide} tab={tab} onTab={setTab} onClose={closePanel} onOpenChunk={openChunk}
                        onToggleReplay={() => {
                          if (!sel) return;
                          if (sel.replaying) { stopReplay(); patch(sel.key, (x) => ({ ...x, replaying: false, trace: foldEvents(x.events) })); }
                          else replay(sel.key);
                        }} />
      )}
      <Modal open={!!chunk} onClose={() => setChunk(null)} width="max-w-2xl" title={chunk?.heading || "原文"}
             desc={chunk ? `${chunk.document?.filename || `文档 #${chunk.doc_id}`} · 片段 ${chunk.id}` : ""}>
        <pre className="whitespace-pre-wrap font-sans text-body leading-relaxed">{chunk?.text}</pre>
      </Modal>
    </div>
  );
}