"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Settings2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { AppShellLayout } from "@/components/layout/detail-sidebar"; import { QaChatPanel } from "@/components/qa/qa-chat-panel"; import { ChatHistorySidebar } from "@/components/chat/chat-history-sidebar"; import { ChatMountConfig } from "@/components/chat/chat-mount-config"; import { ChatScopeEntryHydrator } from "@/components/chat/chat-scope-entry-hydrator"; import { ChatConfigProvider, DEFAULT_AGGREGATE_TOP_K, DEFAULT_PER_KB_TOP_K, DEFAULT_WIKI_TOP_K, buildMemoryFromBinding, buildRagFromMounts, buildWikiFromBinding, useChatConfig, } from "@/components/chat/chat-config-context"; import { useChatHistory, deriveSessionTitle, type ChatSession, } from "@/hooks/use-chat-history"; import { useQaChat } from "@/hooks/use-qa-chat"; import { readLastConfig, writeLastConfig } from "@/hooks/use-chat-last-config"; import { toast } from "sonner"; import { createDreamTask, getDreamTask, depositDreamToKb, } from "@/services/memory"; import { DREAM_TERMINAL_STATUSES, type DreamTaskSummary } from "@/types/memory"; import { isDreamDepositEligible } from "@/lib/chat-dream-deposit"; import { useActiveInstance, type ActiveInstanceState, } from "@/hooks/use-active-instance"; import { newId } from "@/lib/random-id"; import { findUserAnchorAbove } from "@/lib/chat-message-ops"; import { PENDING_DATA_SCOPE_KEY } from "@/lib/query-keys"; import { useI18n } from "@/i18n/i18n-context"; import type { ChatMessage } from "@/types/llm-chat"; /** 轮询 dream 任务直到终态(或超时预算耗尽)。用于会话内「沉淀到知识库」: * 创建 skill/profile 任务后等它跑完,再把产出落库。 */ async function pollDreamTaskUntilTerminal( memoryStoreName: string, dreamId: string, ): Promise { const deadline = Date.now() + 3 * 60 * 1000; // 3 分钟预算 const intervalMs = 2500; for (;;) { const task = await getDreamTask(memoryStoreName, dreamId); if (DREAM_TERMINAL_STATUSES.has(task.status)) return task; if (Date.now() > deadline) return task; // 超时:返回最后已知(多半仍在跑),由调用方处理 await new Promise((resolve) => setTimeout(resolve, intervalMs)); } } /** Next.js page entry for the chat homepage. Wraps the UI tree with the * shared config context so mount/prompt/model state survives across * renders and session switches. */ export default function ChatPage() { return ( ); } function ChatHomepage() { const { t } = useI18n(); const cfg = useChatConfig(); const activeInstanceState = useActiveInstance(); const activeInstance = activeInstanceState.activeInstance; const history = useChatHistory(activeInstanceState); const [activeSessionId, setActiveSessionId] = useState(null); const [sheetOpen, setSheetOpen] = useState(false); // Guard to skip persistence on the very first render of a blank session; // otherwise we'd spam localStorage with empty rows whenever the user just // opens the page. const hasSentRef = useRef(false); /** * Unified session snapshot helper used by both the stream-end auto-save * (`persistSession`) and the manual "save config" CTA (`handleSaveConfig`). * * The two call sites were previously ~95% identical — only the `title` * fallback and the `hasSentRef` guard differed. Folding them into a * single function eliminates the drift risk flagged in CR round 2 * (N-L3) while preserving the distinct intents through the flags: * - `requireSent`: skip persistence when `hasSentRef` is false * (used by auto-save to avoid spamming empty sessions). * - `preserveTitle`: keep the existing stored title instead of * re-deriving from the possibly-empty message list (used by the * manual save path where the user may click "save config" before * sending a single message). */ const saveChatSession = useCallback( ( messages: ChatMessage[], opts: { requireSent: boolean; preserveTitle: boolean }, ) => { if (!activeInstanceState.ready) return; if (opts.requireSent && !hasSentRef.current) return; const id = activeSessionId ?? newId("session"); if (!activeSessionId) setActiveSessionId(id); const existing = opts.preserveTitle ? history.get(id) : null; const title = existing?.title ?? deriveSessionTitle(messages, t("chat.history.newChat")); const session: ChatSession = { id, title, updatedAt: Date.now(), activeInstance, config: cfg.toSessionConfig(), messages, }; history.upsert(session); // Remember this instance's last-used provider/model so the next new // chat on this instance auto-fills the same pair. if (cfg.providerId) { writeLastConfig(activeInstance, { providerId: cfg.providerId, model: cfg.model, }); } }, [ activeSessionId, cfg, history, activeInstance, activeInstanceState.ready, t, ], ); const persistSession = useCallback( (messages: ChatMessage[]) => { saveChatSession(messages, { requireSent: true, preserveTitle: false }); }, [saveChatSession], ); // Build the RAG slice from the current mount list on every send so mid-session // mount edits take effect on the next turn without requiring a restart. const rag = useMemo(() => buildRagFromMounts(cfg), [cfg]); const memory = useMemo(() => buildMemoryFromBinding(cfg), [cfg]); const wiki = useMemo(() => buildWikiFromBinding(cfg), [cfg]); const chat = useQaChat({ dataScopeKey: activeInstanceState.dataScopeKey, activeInstance, providerId: cfg.providerId, model: cfg.model, systemPrompt: cfg.systemPrompt, temperature: cfg.temperature, rag, memory, wiki, onPersist: persistSession, }); // Load an existing session from localStorage into the chat + config state. const loadSession = useCallback( (id: string) => { if (!activeInstanceState.ready) return; const session = history.get(id); if (!session) return; if ((session.activeInstance ?? null) !== activeInstance) return; setActiveSessionId(id); hasSentRef.current = session.messages.length > 0; chat.setMessages(session.messages); cfg.hydrate({ providerId: session.config.providerId ?? "", model: session.config.model ?? "", systemPrompt: session.config.systemPrompt ?? "", temperature: session.config.temperature, aggregateTopK: session.config.aggregateTopK ?? DEFAULT_AGGREGATE_TOP_K, perKbTopK: session.config.perKbTopK ?? DEFAULT_PER_KB_TOP_K, retrieval: session.config.retrieval ?? {}, memory: session.config.memory, mounts: session.config.mounts ?? [], wikiEnabled: session.config.wiki?.enabled === true, wikiTopK: session.config.wiki?.topK ?? DEFAULT_WIKI_TOP_K, }); }, // `chat.setMessages` and `cfg.hydrate` are stable references; depend on // the ids instead of the full objects to avoid reload loops. // eslint-disable-next-line react-hooks/exhaustive-deps [ history, chat.setMessages, cfg.hydrate, activeInstance, activeInstanceState.ready, ], ); const newSession = useCallback(() => { setActiveSessionId(null); hasSentRef.current = false; chat.clear(); // Preserve mounts/prompt/temperature/retrieval so rapid-fire "new chat" // doesn't force users to remount KBs; only refresh provider/model from // this instance's remembered pair. const last = readLastConfig(activeInstance); cfg.setProvider(last.providerId ?? "", last.model ?? ""); // eslint-disable-next-line react-hooks/exhaustive-deps }, [chat.clear, activeInstance, cfg.setProvider]); const deleteSession = useCallback( (id: string) => { history.remove(id); if (activeSessionId === id) { setActiveSessionId(null); hasSentRef.current = false; chat.clear(); } }, [history, activeSessionId, chat], ); const clearAll = useCallback(() => { history.clear(); setActiveSessionId(null); hasSentRef.current = false; chat.clear(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [history, chat.clear]); const handleSend = useCallback( (text: string) => { hasSentRef.current = true; void chat.send(text); }, [chat], ); // Edit-and-resend: rewrite the user message in place, then rerun the // assistant pipeline against the new content. const handleEditSave = useCallback( (userId: string, nextContent: string) => { hasSentRef.current = true; chat.editUserMessage(userId, nextContent); void chat.reissueTurn(userId); }, [chat], ); // Regenerate-from-assistant: walk back to the user message above and // reissue. The truncate happens inside reissueTurn, so callers don't need // to pre-trim — passing the user anchor id is enough. const handleRegenerate = useCallback( (assistantId: string) => { const anchor = findUserAnchorAbove(chat.messages, assistantId); if (!anchor) return; hasSentRef.current = true; void chat.reissueTurn(anchor.id); }, [chat], ); // ---- 会话内「沉淀到知识库」(总结 skill / 提取画像)---- // 触发资格:会话已绑定记忆库 + 至少挂载一个知识库(不限轮次)。 // 沉淀目标 = 首个挂载的知识库(任意知识库均可,不要求 subspace / dream_* 字段)。 const targetKbName = useMemo( () => cfg.mounts?.[0]?.knowledgeBaseName ?? null, [cfg.mounts], ); const depositEligible = isDreamDepositEligible({ hasMemory: !!memory, mountedKbCount: (cfg.mounts ?? []).length, }); const [depositRunning, setDepositRunning] = useState< "skill" | "profile" | null >(null); const runDeposit = useCallback( async (taskType: "skill" | "profile") => { if (depositRunning) return; if (!memory) { toast.error(t("chat.page.bindMemoryFirst")); return; } if (!targetKbName) { toast.error(t("chat.page.mountKbFirst")); return; } const label = taskType === "skill" ? t("chat.page.typeSkill") : t("chat.page.typeProfile"); setDepositRunning(taskType); const toastId = toast.loading( t("chat.page.depositLoading", { type: label }), ); // 复用 loading toast 的 id 就地更新为终态。必须显式给有限 duration: // toast.loading 的 duration 是 Infinity,更新为 message/success/error 时若不 // 重置,会一直挂着不消失(用户遇到的 bug)。 const done = { id: toastId, duration: 5000 }; try { // 1. 对「当前会话」创建对应类型的 dream 抽取任务。 const created = await createDreamTask(memory.memoryStoreName, { scopes: [memory.scope], taskType, }); // 2. 等任务跑到终态。 const task = await pollDreamTaskUntilTerminal( memory.memoryStoreName, created.dreamId, ); if (!DREAM_TERMINAL_STATUSES.has(task.status)) { toast.message(t("chat.page.depositSlow", { type: label }), done); return; } if (task.status === "failed" || task.status === "cancelled") { toast.error( task.status === "failed" ? t("chat.page.depositTaskFailed", { type: label }) : t("chat.page.depositTaskCancelled", { type: label }), done, ); return; } // 3. 把任务产出落到绑定的知识库(同会话重复提取会覆盖旧文件)。 const result = await depositDreamToKb(memory.memoryStoreName, { dreamId: created.dreamId, knowledgeBaseName: targetKbName, kinds: [taskType], }); const entry = result.deposited.find((d) => d.kind === taskType); if (result.failures.length > 0) { const reason = result.failures[0]?.error ?? ""; toast.error( t("chat.page.depositFailedReason", { type: label, reason }), done, ); } else if (!entry) { toast.info(t("chat.page.depositNone", { type: label }), done); } else { toast.success( t("chat.page.depositSuccess", { count: entry.count, type: label, kbName: targetKbName, }), done, ); } } catch (err) { toast.error( err instanceof Error ? err.message : t("chat.page.depositFailed", { type: label }), done, ); } finally { setDepositRunning(null); } }, [depositRunning, memory, targetKbName, t], ); const onSummarizeSkill = useCallback( () => void runDeposit("skill"), [runDeposit], ); const onExtractProfile = useCallback( () => void runDeposit("profile"), [runDeposit], ); // Snapshot the current config to localStorage on demand. Unlike // `persistSession`, this path runs even when no message has been sent yet // so users can lock in their setup before chatting; the resulting session // simply carries an empty message list until the first turn. const handleSaveConfig = useCallback(() => { hasSentRef.current = chat.messages.length > 0 || hasSentRef.current; saveChatSession(chat.messages, { requireSent: false, preserveTitle: true, }); }, [chat.messages, saveChatSession]); // Cross-tab / CLI config-change fallback. The runtime context poller and // focus refetch update this scope when the active project or current // project's underlying credentials change. Without this guard the chat page // would keep showing the previous scope's mounted KBs and unsent draft. const lastInstanceRef = useRef({ activeInstance: null, ready: false, dataScopeKey: PENDING_DATA_SCOPE_KEY, configRevision: "", }); useEffect(() => { const prev = lastInstanceRef.current; // Only act after runtime context has produced a stable scope. The first // loading -> ready transition must not wipe a freshly-opened blank chat. if ( prev.ready && activeInstanceState.ready && prev.dataScopeKey !== activeInstanceState.dataScopeKey ) { cfg.reset(); setActiveSessionId(null); hasSentRef.current = false; chat.clear(); } if (activeInstanceState.ready) { lastInstanceRef.current = activeInstanceState; } // `cfg.reset` and `chat.clear` are stable; tracking the primitive scope // key keeps this to one purge per runtime context change. // eslint-disable-next-line react-hooks/exhaustive-deps }, [activeInstanceState.dataScopeKey, activeInstanceState.ready]); // Auto-fill provider/model with the pair remembered for the current // instance on first mount, and whenever the active instance changes // (instance switcher / cross-tab focus). Only runs while no existing // session is loaded and the context is still in its blank slate, so we // never clobber a session the user just opened. useEffect(() => { if (activeSessionId) return; if (cfg.providerId) return; const last = readLastConfig(activeInstance); if (last.providerId) { cfg.setProvider(last.providerId, last.model ?? ""); } // `cfg.setProvider` is stable from the reducer; depending on the // primitive instance name keeps this to one fill per instance change. // eslint-disable-next-line react-hooks/exhaustive-deps }, [activeInstance, activeSessionId, cfg.providerId]); const activeSession = activeSessionId ? history.get(activeSessionId) : null; const canSend = activeInstanceState.ready && Boolean(cfg.providerId && cfg.model); const headerTitle = activeSession?.title ?? t("chat.page.newChatTitle"); const mountCount = cfg.mounts.length; // Hint surfaced in the empty-state copy when the user just clicked // 「新对话」 and inherited mounts from the previous session. Addresses // the cognitive bias of "this fresh session feels like it remembers // things" — that perception is mostly RAG retrieving similar chunks, // and showing the carry-over count makes the cause visible. const mountsCarryover = !activeSessionId && cfg.mounts.length > 0 ? t("chat.page.mountsCarryover", { count: cfg.mounts.length }) : null; return (

{headerTitle}

{cfg.providerId && cfg.model ? ( <> {t("chat.page.headerStats", { model: cfg.model, count: mountCount, topK: cfg.aggregateTopK, })} {cfg.memory ? t("chat.page.headerMemory", { name: cfg.memory.memoryStoreName, }) : ""} {cfg.wikiEnabled ? ` · ${t("chat.wikiBind.enabled")}` : ""} ) : ( t("chat.page.headerNoConfig") )}

{/* The composer is always rendered (even on a fresh session) so users can start typing immediately. Empty-state copy + a CTA into the config drawer surface inside the panel; this matches the ChatGPT / Claude convention of a sticky composer at the bottom and contextual guidance above it. */} setSheetOpen(true), }} disabledPlaceholder={t("chat.page.disabledPlaceholder")} />
); }