useQueryStore.ts 4.77 KB
import { create } from "zustand";
import { streamSSE, type SSEHandle } from "@/lib/sse";
import type { Citation, QueryMode, Subgraph, TraceEvent } from "@/lib/types";

/** 一轮问答:对话框里的一条"消息",含它自己的检索轨迹、回答与命中子图。 */
export interface QueryTurn {
  id: number;
  question: string;
  mode: QueryMode;
  trace: TraceEvent[];
  answer: string;
  streaming: boolean;
  citations: Citation[];
  subgraph: Subgraph | null;
  durationMs: number;
  error: string | null;
  running: boolean;
}

interface QueryState {
  question: string;
  mode: QueryMode;
  running: boolean;
  turns: QueryTurn[];
  /** 轨迹回放:显示哪个 turn 回放到第几步;step=null 表示显示该 turn 全部 */
  replay: { turnId: number; step: number | null } | null;
  history: { role: string; content: string }[];

  setQuestion: (q: string) => void;
  setMode: (m: QueryMode) => void;
  setReplay: (r: { turnId: number; step: number | null } | null) => void;
  ask: () => void;
  stop: () => void;
  reset: () => void;
  loadFromLog: (d: { question: string; mode: QueryMode; trace: TraceEvent[]; answer: string; subgraph: Subgraph; duration_ms: number }) => void;
}

let handle: SSEHandle | null = null;
let turnSeq = 0;

const updateLastTurn = (turns: QueryTurn[], patch: Partial<QueryTurn> | ((t: QueryTurn) => Partial<QueryTurn>)) => {
  if (turns.length === 0) return turns;
  const last = turns[turns.length - 1];
  const p = typeof patch === "function" ? patch(last) : patch;
  return [...turns.slice(0, -1), { ...last, ...p }];
};

export const useQueryStore = create<QueryState>((set, get) => ({
  question: "",
  mode: "agentic",
  running: false,
  turns: [],
  replay: null,
  history: [],

  setQuestion: (q) => set({ question: q }),
  setMode: (m) => set({ mode: m }),
  setReplay: (r) => set({ replay: r }),

  stop: () => {
    handle?.abort();
    handle = null;
    set((s) => ({ running: false, turns: updateLastTurn(s.turns, { running: false, streaming: false }) }));
  },

  reset: () => {
    handle?.abort();
    handle = null;
    set({ turns: [], running: false, replay: null, history: [] });
  },

  loadFromLog: (d) => {
    handle?.abort();
    handle = null;
    const turn: QueryTurn = {
      id: ++turnSeq, question: d.question, mode: d.mode, trace: d.trace, answer: d.answer,
      streaming: false,
      citations: (d.trace.find((t) => t.type === "answer") as { citations?: Citation[] } | undefined)?.citations ?? [],
      subgraph: d.subgraph, durationMs: d.duration_ms, error: null, running: false,
    };
    set({ turns: [turn], running: false, replay: null, history: [], question: "" });
  },

  ask: () => {
    const { question, mode, history, turns } = get();
    if (!question.trim() || get().running) return;
    handle?.abort();

    const q = question.trim();
    const turn: QueryTurn = {
      id: ++turnSeq, question: q, mode, trace: [], answer: "", streaming: false,
      citations: [], subgraph: null, durationMs: 0, error: null, running: true,
    };
    set({ running: true, question: "", replay: null, turns: [...turns, turn] });

    handle = streamSSE<TraceEvent>(
      "/api/query",
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ question: q, mode, history }),
      },
      (ev) => {
        if (ev.type === "answer_delta") {
          set((s) => ({ turns: updateLastTurn(s.turns, (t) => ({ answer: t.answer + ev.text, streaming: true })) }));
          return;
        }
        if (ev.type === "answer_start") {
          set((s) => ({ turns: updateLastTurn(s.turns, { streaming: true }) }));
          return;
        }
        if (ev.type === "answer") {
          set((s) => ({
            turns: updateLastTurn(s.turns, (t) => ({
              trace: [...t.trace, ev], answer: ev.answer || t.answer, citations: ev.citations,
              subgraph: ev.subgraph, durationMs: ev.duration_ms, running: false, streaming: false,
            })),
            running: false,
            history: [...s.history,
                      { role: "user", content: q },
                      { role: "assistant", content: (ev.answer || "").slice(0, 1500) }],
          }));
          handle = null;
          return;
        }
        if (ev.type === "error") {
          set((s) => ({
            turns: updateLastTurn(s.turns, (t) => ({ trace: [...t.trace, ev], error: ev.error, running: false, streaming: false })),
            running: false,
          }));
          handle = null;
          return;
        }
        set((s) => ({ turns: updateLastTurn(s.turns, (t) => ({ trace: [...t.trace, ev] })) }));
      },
      (err) => {
        set((s) => ({ turns: updateLastTurn(s.turns, { error: err.message, running: false, streaming: false }), running: false }));
        handle = null;
      },
    );
  },
}));