"use client"; import { useEffect, useMemo, useRef, useState } from "react"; import { MessageSquare, Send, Square } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { EmptyState } from "@/components/shared/empty-state"; import { useI18n } from "@/i18n/i18n-context"; import { cn } from "@/lib/utils"; import type { ChatMessage } from "@/types/llm-chat"; import { QaMessage, type DreamDepositActions } from "./qa-message"; /** 会话内「沉淀到知识库」配置。仅聊天页传入;知识库 QA 页不传。 */ export interface QaChatDreamDeposit extends DreamDepositActions { /** 是否满足展示资格(记忆库+知识库绑定 且 轮次足够)。 */ eligible: boolean; } export interface QaChatPanelEmptyState { title: string; description: string; /** Optional CTA shown beneath the empty-state copy. */ actionLabel?: string; onAction?: () => void; } interface QaChatPanelProps { messages: ChatMessage[]; isStreaming: boolean; canSend: boolean; error: string | null; onSend: (text: string) => void; onStop: () => void; /** Remove a message; for user messages, optionally pair-delete the next * assistant reply (the dialog's "同时删除下方的 AI 回复" checkbox). */ onDelete: (id: string, opts?: { withNextAssistant?: boolean }) => void; /** Truncate to this user message and rerun the assistant turn. */ onResend: (userId: string) => void; /** Truncate to the user message above this assistant and rerun. */ onRegenerate: (assistantId: string) => void; /** Replace a user message's content and rerun the turn. */ onEditSave: (userId: string, nextContent: string) => void; /** * Override the built-in empty-state copy. The panel always renders the * composer at the bottom, so callers can use this to surface page-level * onboarding (e.g. "open settings to pick a model") without hiding the * input — matching the ChatGPT / Claude convention. */ emptyState?: QaChatPanelEmptyState; /** Composer placeholder shown when `canSend` is false. */ disabledPlaceholder?: string; /** In-session deposit-to-KB actions; when eligible, shown on the latest * assistant message's action row. Omitted by non-chat callers (KB QA). */ dreamDeposit?: QaChatDreamDeposit; } /** * Chat surface for the QA playground: scrollable message list on top, * sticky composer at the bottom. Handles Enter-to-send / Shift+Enter-for- * newline and auto-scrolls to the latest turn. * * The composer is always mounted, even when the message list is empty, so * users can start typing immediately on a fresh session. */ export function QaChatPanel({ messages, isStreaming, canSend, error, onSend, onStop, onDelete, onResend, onRegenerate, onEditSave, emptyState, disabledPlaceholder, dreamDeposit, }: QaChatPanelProps) { const { t } = useI18n(); const [input, setInput] = useState(""); // 只把 deposit 动作挂到「最新一条助手回复」上,避免每条回复都重复出现。 const lastAssistantId = useMemo(() => { for (let i = messages.length - 1; i >= 0; i--) { if (messages[i].role === "assistant") return messages[i].id; } return null; }, [messages]); // 稳定引用:仅当资格或运行态变化时才重建,配合 QaMessage 的 memo 精确重渲染。 const dreamActions = useMemo(() => { if (!dreamDeposit?.eligible) return undefined; return { running: dreamDeposit.running, onSummarizeSkill: dreamDeposit.onSummarizeSkill, onExtractProfile: dreamDeposit.onExtractProfile, }; }, [ dreamDeposit?.eligible, dreamDeposit?.running, dreamDeposit?.onSummarizeSkill, dreamDeposit?.onExtractProfile, ]); const scrollRef = useRef(null); // Track the previous list length so we can distinguish two cases on every // `messages` update: (a) a brand-new message was appended (send → user // bubble + assistant placeholder), or (b) tokens were streamed into an // existing assistant bubble. Case (a) must always scroll — that's the // user's just-sent message, they expect to see it. Case (b) should only // scroll when the user is already near the bottom, otherwise we'd fight // someone who scrolled up to re-read an earlier turn. const prevLengthRef = useRef(messages.length); useEffect(() => { const el = scrollRef.current; if (!el) return; const lengthGrew = messages.length > prevLengthRef.current; prevLengthRef.current = messages.length; if (lengthGrew) { // New turn appended. Defer one frame so the DOM has actually grown // before we measure scrollHeight — without the rAF the scroll lands // at the previous bottom and the new bubble peeks half-out. requestAnimationFrame(() => { el.scrollTo({ top: el.scrollHeight, behavior: "smooth" }); }); return; } const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 120; if (nearBottom) { el.scrollTo({ top: el.scrollHeight, behavior: "smooth" }); } }, [messages]); const handleSend = () => { const trimmed = input.trim(); if (!trimmed || !canSend || isStreaming) return; onSend(trimmed); setInput(""); }; const handleKeyDown = (event: React.KeyboardEvent) => { if ( event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing ) { event.preventDefault(); handleSend(); } }; return (
{messages.length === 0 ? (
{emptyState.actionLabel} ) : undefined } />
) : ( messages.map((m) => ( )) )}
{error && (

{error}

)}