"use client"; import { memo, useCallback, useEffect, useState } from "react"; import Link from "next/link"; import { AlertCircle, AlertTriangle, BookOpen, Brain, CheckCircle2, ChevronDown, Copy, FileText, FolderTree, GraduationCap, Loader2, Pencil, RotateCcw, Search, Send, Trash2, UserRound, } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Collapsible, CollapsibleContent, CollapsibleTrigger, } from "@/components/ui/collapsible"; import { Textarea } from "@/components/ui/textarea"; import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"; import { ConfirmDialog } from "@/components/shared/confirm-dialog"; import { useI18n, type TranslateFn } from "@/i18n/i18n-context"; import { useAddItem } from "@/hooks/use-file-memory"; import { cn, extractFileName } from "@/lib/utils"; import { IMAGE_FALLBACK_DATA_PREFIX } from "@/lib/constants"; import type { ChatMessage, RetrievalGroup, RetrievedChunk, } from "@/types/llm-chat"; import type { MemorySearchHit } from "@/types/memory"; import { normalizeFileMemoryPath, validateFileMemoryContent, validateFileMemoryPath, } from "@/components/memory/file-editor"; import { Markdown } from "./markdown"; import { AnswerEvidenceBlock } from "./answer-evidence-block"; import { MemoryEvidenceContent } from "./memory-evidence-content"; /** Fallback for clipboard copy when navigator.clipboard is unavailable (e.g. * non-HTTPS contexts). Uses the deprecated execCommand approach. */ function fallbackCopy(text: string, t: TranslateFn) { try { const textarea = document.createElement("textarea"); textarea.value = text; textarea.style.position = "fixed"; textarea.style.opacity = "0"; document.body.appendChild(textarea); textarea.select(); document.execCommand("copy"); document.body.removeChild(textarea); toast.success(t("qa.message.copied")); } catch { toast.error(t("qa.message.copyFailed")); } } /** * 会话内「沉淀到知识库」动作。仅在满足资格(记忆库+知识库均绑定且轮次足够) * 时由聊天页透传,且只挂到最新一条助手回复上;其它场景(如知识库 QA 页)不传, * 动作行保持原样。`running` 非 null 时两个按钮禁用并显示 spinner。 */ export interface DreamDepositActions { running: "skill" | "profile" | null; onSummarizeSkill(): void; onExtractProfile(): void; } interface QaMessageProps { message: ChatMessage; /** Whether ANY turn in the session is currently streaming. All action * buttons disable during streaming to avoid racing the message list * against in-flight SSE flushes. */ busy: boolean; onDelete(id: string, opts?: { withNextAssistant?: boolean }): void; onResend(userId: string): void; onRegenerate(assistantId: string): void; onEditSave(userId: string, nextContent: string): void; /** Optional in-session deposit actions; only passed for the latest assistant * message when eligible (undefined otherwise). */ dreamActions?: DreamDepositActions; } function QaMessageImpl({ message, busy, onDelete, onResend, onRegenerate, onEditSave, dreamActions, }: QaMessageProps) { if (message.role === "user") { return ( ); } return ( ); } /** * Memoised so that streaming a delta to message N does not re-render * messages 0..N-1. Reference equality on the message object is enough * because useQaChat replaces the touched message via map() and keeps * untouched ones identical. The action callbacks are stable from the * parent (chat hook returns stable refs), so we only diff on the message * + busy flag. */ export const QaMessage = memo( QaMessageImpl, (prev, next) => prev.message === next.message && prev.busy === next.busy && prev.dreamActions === next.dreamActions, ); QaMessage.displayName = "QaMessage"; // --------------------------------------------------------------------------- // Hover-revealed action row + tiny button — shared by both bubble variants. // --------------------------------------------------------------------------- type MessageActionsProps = { align: "left" | "right"; /** Disable all buttons (e.g. while another turn is streaming). */ disabled: boolean; onCopy: () => void; onDelete: () => void; /** User-bubble specific. Falsy → button not rendered. */ onEdit?: () => void; onResend?: () => void; /** Assistant-bubble specific. */ onRegenerate?: () => void; onSaveToFile?: () => void; /** Assistant-bubble specific: in-session deposit-to-KB actions. */ dreamActions?: DreamDepositActions; }; /** * Hover-revealed icon row beneath a chat bubble. Default state is invisible * (`opacity-0`) so the message list reads cleanly at rest; hover/focus on the * parent bubble (controlled via `group-hover:` / `group-focus-within:`) * fades the row in within 150ms — the ChatGPT/Claude convention. Mobile: * parents add `data-touched="true"` after first tap to keep the row visible. */ function MessageActions({ align, disabled, onCopy, onDelete, onEdit, onResend, onRegenerate, onSaveToFile, dreamActions, }: MessageActionsProps) { const { t } = useI18n(); const depositBusy = dreamActions?.running != null; return (
{onEdit && ( )} {onResend && ( )} {onRegenerate && ( )} {onSaveToFile && ( )} {dreamActions && ( <> {dreamActions.running === "skill" ? ( ) : ( )} {dreamActions.running === "profile" ? ( ) : ( )} )}
); } function ActionButton({ title, disabled, destructive, onClick, children, }: { title: string; disabled: boolean; destructive?: boolean; onClick: () => void; children: React.ReactNode; }) { return ( ); } // --------------------------------------------------------------------------- // In-message warning chips for non-fatal mid-flow failures (rewriter died, // some KBs returned errors). Static — these are passive notices, not // in-progress state, so no shimmer/pulse to compete with the brand-tinted // thinking pill. // --------------------------------------------------------------------------- type TurnNoticesProps = { rewriteFailed?: boolean; rewriteError?: string; failedKbCount?: number; failedKbDetails?: Array<{ name: string; reason: string }>; failedWikiCount?: number; failedWikiDetails?: Array<{ name: string; reason: string }>; }; function TurnNotices({ rewriteFailed, rewriteError, failedKbCount, failedKbDetails, failedWikiCount, failedWikiDetails, }: TurnNoticesProps) { const { t } = useI18n(); const hasRewrite = !!rewriteFailed; const hasRetrieval = (failedKbCount ?? 0) > 0; const hasWikiRetrieval = (failedWikiCount ?? 0) > 0; if (!hasRewrite && !hasRetrieval && !hasWikiRetrieval) return null; return (
{hasRewrite && ( )} {hasRetrieval && failedKbDetails && ( `• ${d.name}: ${d.reason}`) .join("\n")} /> )} {hasWikiRetrieval && failedWikiDetails && ( `• ${d.name}: ${d.reason}`) .join("\n")} /> )}
); } function NoticeChip({ label, detail }: { label: string; detail: string }) { const [open, setOpen] = useState(false); return (
{open && (
          {detail}
        
)}
); } // --------------------------------------------------------------------------- // User bubble — copy / edit / resend / delete. // --------------------------------------------------------------------------- function UserBubble({ message, busy, onDelete, onResend, onEditSave, }: { message: ChatMessage; busy: boolean; onDelete: QaMessageProps["onDelete"]; onResend: QaMessageProps["onResend"]; onEditSave: QaMessageProps["onEditSave"]; }) { const { t } = useI18n(); const [touched, setTouched] = useState(false); const [editing, setEditing] = useState(false); const [draft, setDraft] = useState(message.content); const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false); const [confirmResendOpen, setConfirmResendOpen] = useState(false); const [withNextAssistant, setWithNextAssistant] = useState(true); const handleCopy = useCallback(() => { if (!message.content) return; try { if (navigator.clipboard && window.isSecureContext) { void navigator.clipboard.writeText(message.content).then( () => toast.success(t("qa.message.copied")), () => { fallbackCopy(message.content, t); }, ); } else { fallbackCopy(message.content, t); } } catch { fallbackCopy(message.content, t); } }, [message.content, t]); const handleSaveEdit = useCallback(() => { const trimmed = draft.trim(); if (!trimmed || trimmed === message.content) { setEditing(false); setDraft(message.content); return; } setEditing(false); onEditSave(message.id, trimmed); }, [draft, message.content, message.id, onEditSave]); const handleCancelEdit = useCallback(() => { setDraft(message.content); setEditing(false); }, [message.content]); const handleEditKeyDown = useCallback( (e: React.KeyboardEvent) => { if (e.key === "Escape") { e.preventDefault(); handleCancelEdit(); } else if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); handleSaveEdit(); } }, [handleSaveEdit, handleCancelEdit], ); return (
setTouched(true)} >
{editing ? (