DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
merge: guided-learning-v2 into feature/guided-learning (target dev)
whfa8801f929a6d
diff --cc deeptutor/runtime/bootstrap/builtin_capabilities.pyindex 352b01d74,f034fd0d7..3caeb69df--- a/deeptutor/runtime/bootstrap/builtin_capabilities.py+++ b/deeptutor/runtime/bootstrap/builtin_capabilities.py@@@ -7,5 -7,5 +7,6 @@@ BUILTIN_CAPABILITY_CLASSES: dict[str, s"deep_research": "deeptutor.capabilities.deep_research:DeepResearchCapability","math_animator": "deeptutor.capabilities.math_animator:MathAnimatorCapability","visualize": "deeptutor.capabilities.visualize:VisualizeCapability",+ "auto": "deeptutor.capabilities.auto:AutoCapability",+ "guided_learning": "deeptutor.capabilities.guided_learning:GuidedLearningCapability",}diff --cc deeptutor/services/session/pocketbase_store.pyindex 6b78b55f5,4730110f5..2b58fb94f--- a/deeptutor/services/session/pocketbase_store.py+++ b/deeptutor/services/session/pocketbase_store.py@@@ -93,11 -99,10 +102,12 @@@ class PocketBaseSessionStore)record = await asyncio.to_thread(_create)- return self._session_record_to_dict(record, resolved_id, resolved_title, now)+ result = self._session_record_to_dict(record, resolved_id, resolved_title, now)+ result.setdefault("kind", resolved_kind)+ return resultasync def get_session(self, session_id: str) -> dict[str, Any] | None:+ sid = _validate_id(session_id, "session_id")def _get():try:records = (@@@ -290,12 -288,8 +304,13 @@@events: list[dict[str, Any]] | None = None,attachments: list[dict[str, Any]] | None = None,metadata: dict[str, Any] | None = None,+ parent_message_id: int | None = None,) -> int:+ # ``parent_message_id`` is accepted to match the protocol shape but is+ # not yet wired through PocketBase storage — branching only works on+ # the SQLite backend today.+ _ = parent_message_id+ sid = _validate_id(session_id, "session_id")now = time.time()def _add():diff --cc web/app/(workspace)/chat/[[...sessionId]]/page.tsxindex 4d7efdd97,b5cca7225..a708dd7f3--- a/web/app/(workspace)/chat/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/chat/[[...sessionId]]/page.tsx@@@ -1,1849 -1,1427 +1,3276 @@@-"use client";--import dynamic from "next/dynamic";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { useParams, useRouter } from "next/navigation";--import {- BarChart3,- BrainCircuit,- Clapperboard,- Code2,- Database,- FileSearch,- Globe,- Lightbulb,- MessageSquare,- Microscope,- PenLine,- Sparkles,- type LucideIcon,-} from "lucide-react";-import { useTranslation } from "react-i18next";-import type { SelectedRecord } from "@/lib/notebook-selection-types";-import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";-import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";-import ChatComposer from "@/components/chat/home/ChatComposer";-import { ChatMessageList } from "@/components/chat/home/ChatMessages";-// Imported eagerly so the drawer shell is always mounted off-screen —-// clicking a chip becomes a single CSS class flip, no chunk fetch + double-// render. The heavy renderers inside still load lazily.-import FilePreviewDrawer from "@/components/chat/preview/FilePreviewDrawer";-import {- useUnifiedChat,- type MessageAttachment,- type MessageRequestSnapshot,-} from "@/context/UnifiedChatContext";-import { useAppShell } from "@/context/AppShellContext";-import type { FilePreviewSource } from "@/components/chat/preview/previewerFor";-import type { LLMSelection, StreamEvent } from "@/lib/unified-ws";-import {- extractBase64FromDataUrl,- readFileAsDataUrl,-} from "@/lib/file-attachments";-import {- classifyFile,- isSvgFilename,- MAX_ATTACHMENT_BYTES,- MAX_TOTAL_ATTACHMENT_BYTES,-} from "@/lib/doc-attachments";-import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";-import { useMeasuredHeight } from "@/hooks/useMeasuredHeight";-import {- loadCapabilityPlaygroundConfigs,- resolveCapabilityPlaygroundConfig,- type CapabilityPlaygroundConfigMap,-} from "@/lib/playground-config";-import {- DEFAULT_QUIZ_CONFIG,- buildQuizWSConfig,- type DeepQuestionFormConfig,-} from "@/lib/quiz-types";-import {- DEFAULT_MATH_ANIMATOR_CONFIG,- buildMathAnimatorWSConfig,- type MathAnimatorFormConfig,-} from "@/lib/math-animator-types";-import {- DEFAULT_VISUALIZE_CONFIG,- buildVisualizeWSConfig,- type VisualizeFormConfig,-} from "@/lib/visualize-types";-import {- buildResearchWSConfig,- createEmptyResearchConfig,- validateResearchConfig,- type DeepResearchFormConfig,- type OutlineItem,- type ResearchSource,-} from "@/lib/research-types";-import { listKnowledgeBases } from "@/lib/knowledge-api";-import { listLLMOptions, type LLMOption } from "@/lib/llm-options";-import { downloadChatMarkdown } from "@/lib/chat-export";-import type { SpaceMemoryFile } from "@/lib/space-items";-import {- selectedBooksToPayload,- type SelectedBookReference,-} from "@/lib/book-references";--const NotebookRecordPicker = dynamic(- () => import("@/components/notebook/NotebookRecordPicker"),- {- ssr: false,- },-);-const HistorySessionPicker = dynamic(- () => import("@/components/chat/HistorySessionPicker"),- {- ssr: false,- },-);-const QuestionBankPicker = dynamic(- () => import("@/components/chat/QuestionBankPicker"),- {- ssr: false,- },-);-const SkillsPicker = dynamic(() => import("@/components/chat/SkillsPicker"), {- ssr: false,-});-const MemoryPicker = dynamic(() => import("@/components/chat/MemoryPicker"), {- ssr: false,-});-const BookReferencePicker = dynamic(- () => import("@/components/chat/BookReferencePicker"),- {- ssr: false,- },-);-const SaveToNotebookModal = dynamic(- () => import("@/components/notebook/SaveToNotebookModal"),- {- ssr: false,- },-);--/* ------------------------------------------------------------------ */-/* Type & data definitions */-/* ------------------------------------------------------------------ */--type ToolName =- | "brainstorm"- | "rag"- | "web_search"- | "code_execution"- | "reason"- | "paper_search";--interface ToolDef {- name: ToolName;- label: string;- icon: LucideIcon;-}--interface ResearchSourceDef {- name: ResearchSource;- label: string;- icon: LucideIcon;-}--const ALL_TOOLS: ToolDef[] = [- { name: "brainstorm", label: "Brainstorm", icon: Lightbulb },- { name: "rag", label: "RAG", icon: Database },- { name: "web_search", label: "Web Search", icon: Globe },- { name: "code_execution", label: "Code", icon: Code2 },- { name: "reason", label: "Reason", icon: Sparkles },- { name: "paper_search", label: "Arxiv Search", icon: FileSearch },-];--const RESEARCH_SOURCES: ResearchSourceDef[] = [- { name: "kb", label: "Knowledge Base", icon: Database },- { name: "web", label: "Web", icon: Globe },- { name: "papers", label: "Papers", icon: FileSearch },-];--interface CapabilityDef {- value: string;- label: string;- description: string;- icon: LucideIcon;- allowedTools: ToolName[];- defaultTools: ToolName[];-}--const CAPABILITIES: CapabilityDef[] = [- {- value: "",- label: "Chat",- description: "Flexible conversation with any tool",- icon: MessageSquare,- allowedTools: [- "brainstorm",- "rag",- "web_search",- "code_execution",- "reason",- "paper_search",- ],- defaultTools: [],- },- {- value: "deep_solve",- label: "Deep Solve",- description: "Multi-step reasoning & problem solving",- icon: BrainCircuit,- allowedTools: ["rag", "web_search", "code_execution", "reason"],- defaultTools: ["rag", "web_search", "code_execution", "reason"],- },- {- value: "deep_question",- label: "Quiz Generation",- description: "Auto-validated question generation",- icon: PenLine,- allowedTools: ["rag", "web_search", "code_execution"],- defaultTools: ["rag", "web_search", "code_execution"],- },- {- value: "deep_research",- label: "Deep Research",- description: "Comprehensive multi-agent research",- icon: Microscope,- allowedTools: [],- defaultTools: [],- },- {- value: "math_animator",- label: "Math Animator",- description: "Generate math videos or storyboard images",- icon: Clapperboard,- allowedTools: [],- defaultTools: [],- },- {- value: "visualize",- label: "Visualize",- description: "Generate SVG, Chart.js, or Mermaid visualizations",- icon: BarChart3,- allowedTools: [],- defaultTools: [],- },-];--interface KnowledgeBase {- name: string;- is_default?: boolean;-}--interface PendingAttachment {- type: string;- filename: string;- base64?: string;- previewUrl?: string;- size?: number;- mimeType?: string;-}--/* ------------------------------------------------------------------ */-/* Helpers */-/* ------------------------------------------------------------------ */--function getCapability(value: string | null): CapabilityDef {- return CAPABILITIES.find((c) => c.value === (value || "")) ?? CAPABILITIES[0];-}--/* ------------------------------------------------------------------ */-/* Chat page */-/* ------------------------------------------------------------------ */--export default function ChatPage() {- const params = useParams<{ sessionId?: string[] }>();- const router = useRouter();- const { t } = useTranslation();- const sessionIdParam = params.sessionId?.[0] ?? null;- const { setActiveSessionId, language: appLanguage } = useAppShell();-- const {- state,- setTools,- setCapability,- setKBs,- setLLMSelection,- sendMessage,- cancelStreamingTurn,- regenerateLastMessage,- newSession,- loadSession,- } = useUnifiedChat();-- const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);- const [llmOptions, setLLMOptions] = useState<LLMOption[]>([]);- const [activeLLMDefault, setActiveLLMDefault] = useState<LLMSelection | null>(- null,- );- const [llmOptionsLoading, setLLMOptionsLoading] = useState(true);- const [llmOptionsError, setLLMOptionsError] = useState(false);- const [capabilityConfigs, setCapabilityConfigs] =- useState<CapabilityPlaygroundConfigMap>({});- const [attachments, setAttachments] = useState<PendingAttachment[]>([]);- const [dragging, setDragging] = useState(false);- const [attachmentError, setAttachmentError] = useState<string | null>(null);- const [previewSource, setPreviewSource] = useState<FilePreviewSource | null>(- null,- );- const attachmentErrorTimer = useRef<ReturnType<typeof setTimeout> | null>(- null,- );- const [capMenuOpen, setCapMenuOpen] = useState(false);- const [quizConfig, setQuizConfig] = useState<DeepQuestionFormConfig>({- ...DEFAULT_QUIZ_CONFIG,- });- const [quizPdf, setQuizPdf] = useState<File | null>(null);- const [mathAnimatorConfig, setMathAnimatorConfig] =- useState<MathAnimatorFormConfig>({- ...DEFAULT_MATH_ANIMATOR_CONFIG,- });- const [visualizeConfig, setVisualizeConfig] = useState<VisualizeFormConfig>({- ...DEFAULT_VISUALIZE_CONFIG,- });- const [researchConfig, setResearchConfig] = useState<DeepResearchFormConfig>(- createEmptyResearchConfig(),- );- // Unified collapse state for the capability-specific config panel- // (Quiz / Math Animator / Visualize / Deep Research). Default collapsed so- // a fresh Chat / Deep Solve session has the shortest possible composer.- const [panelCollapsed, setPanelCollapsed] = useState(true);- const [showSaveModal, setShowSaveModal] = useState(false);- const [showNotebookPicker, setShowNotebookPicker] = useState(false);- const [showBookPicker, setShowBookPicker] = useState(false);- const [showHistoryPicker, setShowHistoryPicker] = useState(false);- const [showQuestionBankPicker, setShowQuestionBankPicker] = useState(false);- const [showSkillsPicker, setShowSkillsPicker] = useState(false);- const [showMemoryPicker, setShowMemoryPicker] = useState(false);- const [toolMenuOpen, setToolMenuOpen] = useState(false);- const [spaceMenuOpen, setSpaceMenuOpen] = useState(false);- const [selectedNotebookRecords, setSelectedNotebookRecords] = useState<- SelectedRecord[]- >([]);- const [selectedBookReferences, setSelectedBookReferences] = useState<- SelectedBookReference[]- >([]);- const [selectedHistorySessions, setSelectedHistorySessions] = useState<- SelectedHistorySession[]- >([]);- const [selectedQuestionEntries, setSelectedQuestionEntries] = useState<- SelectedQuestionEntry[]- >([]);- const [selectedSkills, setSelectedSkills] = useState<string[]>([]);- const [skillsAutoMode, setSkillsAutoMode] = useState(false);- const [selectedMemoryFiles, setSelectedMemoryFiles] = useState<- SpaceMemoryFile[]- >([]);- const dragCounter = useRef(0);- const capMenuRef = useRef<HTMLDivElement>(null);- const capBtnRef = useRef<HTMLButtonElement>(null);- const toolMenuRef = useRef<HTMLDivElement>(null);- const toolBtnRef = useRef<HTMLButtonElement>(null);- const spaceMenuRef = useRef<HTMLDivElement>(null);- const spaceBtnRef = useRef<HTMLButtonElement>(null);- const initialLoadRef = useRef(false);-- const activeCap = useMemo(- () => getCapability(state.activeCapability),- [state.activeCapability],- );- const isQuizMode = activeCap.value === "deep_question";- const isMathAnimatorMode = activeCap.value === "math_animator";- const isVisualizeMode = activeCap.value === "visualize";- const isResearchMode = activeCap.value === "deep_research";- const selectedTools = useMemo(- () => new Set(state.enabledTools),- [state.enabledTools],- );- const ragActive = isResearchMode- ? researchConfig.sources.includes("kb")- : selectedTools.has("rag");- const hasMessages = state.messages.length > 0;- const { ref: composerRef, height: composerHeight } =- useMeasuredHeight<HTMLDivElement>();- const visibleTools = useMemo(- () => ALL_TOOLS.filter((t) => activeCap.allowedTools.includes(t.name)),- [activeCap.allowedTools],- );- const researchValidation = useMemo(- () => validateResearchConfig(researchConfig),- [researchConfig],- );- const notebookReferenceGroups = useMemo(() => {- const groups = new Map<string, { notebookName: string; count: number }>();- selectedNotebookRecords.forEach((record) => {- const existing = groups.get(record.notebookId);- if (existing) {- existing.count += 1;- } else {- groups.set(record.notebookId, {- notebookName: record.notebookName,- count: 1,- });- }- });- return Array.from(groups.entries()).map(([notebookId, value]) => ({- notebookId,- ...value,- }));- }, [selectedNotebookRecords]);- const notebookReferencesPayload = useMemo(() => {- const grouped = new Map<string, string[]>();- selectedNotebookRecords.forEach((record) => {- const current = grouped.get(record.notebookId) || [];- current.push(record.id);- grouped.set(record.notebookId, current);- });- return Array.from(grouped.entries()).map(([notebook_id, record_ids]) => ({- notebook_id,- record_ids,- }));- }, [selectedNotebookRecords]);- const bookReferencesPayload = useMemo(- () => selectedBooksToPayload(selectedBookReferences),- [selectedBookReferences],- );- const historyReferencesPayload = useMemo(- () => selectedHistorySessions.map((session) => session.sessionId),- [selectedHistorySessions],- );- const questionNotebookReferencesPayload = useMemo(- () => selectedQuestionEntries.map((entry) => entry.id),- [selectedQuestionEntries],- );- const memoryReferencesPayload = useMemo(- () => [...selectedMemoryFiles],- [selectedMemoryFiles],- );- const chatSaveMessages = useMemo(- () =>- state.messages.map((msg) => ({- role: msg.role,- content: msg.content,- capability: msg.capability,- })),- [state.messages],- );- const chatSavePayload = useMemo(() => {- if (!state.messages.length) return null;- const title =- state.messages- .find((msg) => msg.role === "user")- ?.content.trim()- .slice(0, 80) || "Chat Session";- return {- recordType: "chat" as const,- title,- // The actual transcript / userQuery are rebuilt inside SaveToNotebookModal- // from the user's selected subset of messages. We still provide a- // sensible fallback for non-selection callers.- userQuery: "",- output: "",- metadata: {- source: "chat",- capability: state.activeCapability || "chat",- ui_language: state.language,- session_id: state.sessionId,- total_message_count: state.messages.length,- },- };- }, [state.activeCapability, state.language, state.messages, state.sessionId]);- const lastMessage = state.messages[state.messages.length - 1];- const {- containerRef: messagesContainerRef,- endRef: messagesEndRef,- shouldAutoScrollRef,- handleScroll: handleMessagesScroll,- } = useChatAutoScroll({- hasMessages,- isStreaming: state.isStreaming,- composerHeight,- messageCount: state.messages.length,- lastMessageContent: lastMessage?.content,- lastEventCount: lastMessage?.events?.length,- });- const copyAssistantMessage = useCallback(async (content: string) => {- if (!content.trim()) return;- try {- await navigator.clipboard.writeText(content);- } catch (error) {- console.error("Failed to copy assistant message:", error);- }- }, []);- const handleAnswerNow = useCallback(- (- snapshot?: MessageRequestSnapshot,- assistantMsg?: { content: string; events?: StreamEvent[] },- ) => {- if (!snapshot || !state.isStreaming) return;- const answerNowEvents = (assistantMsg?.events ?? []).map((event) => ({- type: event.type,- stage: event.stage,- content: event.content,- metadata: event.metadata ?? {},- }));- cancelStreamingTurn();- // Preserve the original capability — each capability now owns its- // own answer-now fast-path (deep_solve jumps to writing,- // deep_question to direct quiz synthesis, math_animator to- // code-gen + render, etc.). The backend orchestrator only falls- // back to ``chat`` if the requested capability is missing.- const answerNowSnapshot: MessageRequestSnapshot = {- ...snapshot,- language: appLanguage,- config: {- ...(snapshot.config || {}),- answer_now_context: {- original_user_message: snapshot.content,- partial_response: assistantMsg?.content || "",- events: answerNowEvents,- },- },- };- window.setTimeout(() => {- sendMessage(- answerNowSnapshot.content,- answerNowSnapshot.attachments,- answerNowSnapshot.config,- answerNowSnapshot.notebookReferences,- answerNowSnapshot.historyReferences,- {- displayUserMessage: false,- persistUserMessage: false,- requestSnapshotOverride: answerNowSnapshot,- bookReferences: answerNowSnapshot.bookReferences,- },- answerNowSnapshot.questionNotebookReferences,- answerNowSnapshot.skills,- answerNowSnapshot.memoryReferences,- );- shouldAutoScrollRef.current = true;- }, 0);- },- [- appLanguage,- cancelStreamingTurn,- sendMessage,- shouldAutoScrollRef,- state.isStreaming,- ],- );-- /* ---- URL-driven session loading ---- */- useEffect(() => {- if (initialLoadRef.current) return;- initialLoadRef.current = true;- if (sessionIdParam) {- void loadSession(sessionIdParam).catch(() => {- router.replace("/chat", { scroll: false });- });- } else {- newSession();- }- }, []); // eslint-disable-line react-hooks/exhaustive-deps-- // When URL param changes (sidebar navigation), load the corresponding session- const prevSessionIdParam = useRef(sessionIdParam);- useEffect(() => {- if (sessionIdParam === prevSessionIdParam.current) return;- prevSessionIdParam.current = sessionIdParam;- if (sessionIdParam) {- if (sessionIdParam === state.sessionId) return;- void loadSession(sessionIdParam).catch(() => {- router.replace("/chat", { scroll: false });- });- } else {- newSession();- }- }, [sessionIdParam, loadSession, newSession, router, state.sessionId]);-- // When a new session_id is assigned by the server, update the URL- useEffect(() => {- if (state.sessionId && !sessionIdParam) {- router.replace(`/chat/${state.sessionId}`, { scroll: false });- }- }, [state.sessionId, sessionIdParam, router]);-- useEffect(() => {- setActiveSessionId(state.sessionId || sessionIdParam || null);- }, [state.sessionId, sessionIdParam, setActiveSessionId]);-- const refreshKnowledgeBases = useCallback(- async (options?: { force?: boolean }) => {- try {- const list = await listKnowledgeBases({ force: options?.force });- setKnowledgeBases(list);- if (!state.knowledgeBases.length && list.length) {- const def = list.find((k: KnowledgeBase) => k.is_default);- setKBs([def?.name || list[0].name]);- }- } catch {- setKnowledgeBases([]);- }- },- [setKBs, state.knowledgeBases.length],- );-- /* Load KBs */- useEffect(() => {- void refreshKnowledgeBases({ force: true });- }, [refreshKnowledgeBases]);-- const refreshLLMOptions = useCallback(async () => {- setLLMOptionsLoading(true);- try {- const payload = await listLLMOptions();- setLLMOptions(payload.options);- setActiveLLMDefault(payload.active);- setLLMOptionsError(false);- } catch {- setLLMOptionsError(true);- setLLMOptions([]);- setActiveLLMDefault(null);- } finally {- setLLMOptionsLoading(false);- }- }, []);-- useEffect(() => {- void refreshLLMOptions();- }, [refreshLLMOptions]);-- useEffect(() => {- if (state.llmSelection || !activeLLMDefault) return;- setLLMSelection(activeLLMDefault);- }, [activeLLMDefault, setLLMSelection, state.llmSelection]);-- useEffect(() => {- if (typeof window === "undefined") return;- const refresh = () => {- void refreshKnowledgeBases({ force: true });- void refreshLLMOptions();- };- const refreshWhenVisible = () => {- if (document.visibilityState === "visible") refresh();- };- window.addEventListener("focus", refresh);- window.addEventListener("pageshow", refresh);- document.addEventListener("visibilitychange", refreshWhenVisible);- return () => {- window.removeEventListener("focus", refresh);- window.removeEventListener("pageshow", refresh);- document.removeEventListener("visibilitychange", refreshWhenVisible);- };- }, [refreshKnowledgeBases, refreshLLMOptions]);-- useEffect(() => {- setCapabilityConfigs(loadCapabilityPlaygroundConfigs());- }, []);-- /* URL query params (capability, tool) */- useEffect(() => {- if (typeof window === "undefined") return;- const p = new URLSearchParams(window.location.search);- const qc = p.get("capability");- const qt = p.getAll("tool");- if (qc !== null) handleSelectCapability(qc || "");- else if (qt.length) {- const valid = qt.filter((t): t is ToolName =>- ALL_TOOLS.some((d) => d.name === t),- );- if (valid.length) setTools(Array.from(new Set(valid)));- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- useEffect(() => {- const handler = (e: MouseEvent) => {- const t = e.target as Node;- if (- capMenuRef.current &&- !capMenuRef.current.contains(t) &&- capBtnRef.current &&- !capBtnRef.current.contains(t)- )- setCapMenuOpen(false);- if (- toolMenuRef.current &&- !toolMenuRef.current.contains(t) &&- toolBtnRef.current &&- !toolBtnRef.current.contains(t)- )- setToolMenuOpen(false);- if (- spaceMenuRef.current &&- !spaceMenuRef.current.contains(t) &&- spaceBtnRef.current &&- !spaceBtnRef.current.contains(t)- )- setSpaceMenuOpen(false);- };- document.addEventListener("mousedown", handler);- return () => document.removeEventListener("mousedown", handler);- }, []);-- useEffect(() => {- const allowed = new Set(visibleTools.map((tool) => tool.name));- const nextTools = state.enabledTools.filter((tool) =>- allowed.has(tool as ToolName),- );- if (nextTools.length !== state.enabledTools.length) setTools(nextTools);- }, [setTools, state.enabledTools, visibleTools]);-- /* ---- handlers ---- */-- const handleSelectCapability = useCallback(- (value: string) => {- const cap =- CAPABILITIES.find((c) => c.value === value) ?? CAPABILITIES[0];- const storageKey = cap.value || "chat";- const config = resolveCapabilityPlaygroundConfig(- capabilityConfigs,- storageKey,- cap.allowedTools,- );- setCapability(cap.value || null);- setTools(- config.enabledTools.length > 0 || capabilityConfigs[storageKey]- ? [...config.enabledTools]- : [...cap.defaultTools],- );- if (config.enabledTools.includes("rag") && config.knowledgeBase)- setKBs([config.knowledgeBase]);- // Default-expand the per-capability settings panel right after a- // capability switch so users immediately see the form. Sending a- // message later will auto-collapse it (see handleSend).- setPanelCollapsed(false);- setCapMenuOpen(false);- },- [capabilityConfigs, setCapability, setKBs, setTools],- );-- const toggleTool = useCallback(- (tool: string) => {- if (!activeCap.allowedTools.includes(tool as ToolName)) return;- if (selectedTools.has(tool)) {- setTools(state.enabledTools.filter((t) => t !== tool));- } else {- setTools([...state.enabledTools, tool]);- }- },- [activeCap.allowedTools, selectedTools, setTools, state.enabledTools],- );-- const toggleResearchSource = useCallback((source: ResearchSource) => {- setResearchConfig((current) => ({- ...current,- sources: current.sources.includes(source)- ? current.sources.filter((item) => item !== source)- : [...current.sources, source],- }));- }, []);-- const fileToAttachment = useCallback(- (f: File): Promise<PendingAttachment> =>- new Promise((resolve, reject) => {- readFileAsDataUrl(f)- .then((raw) => {- // SVG: treat as file (text extraction on server, vision models- // reject SVG) but keep the data URL so the chip can render a- // thumbnail via a raw <img> tag.- const svg = isSvgFilename(f.name) || f.type === "image/svg+xml";- const isImage = !svg && f.type.startsWith("image/");- const b64 = extractBase64FromDataUrl(raw);- resolve({- type: isImage ? "image" : "file",- filename: f.name,- base64: b64,- previewUrl: isImage || svg ? raw : undefined,- size: f.size,- mimeType: f.type || undefined,- });- })- .catch(reject);- }),- [],- );-- const showAttachmentError = useCallback((message: string) => {- setAttachmentError(message);- if (attachmentErrorTimer.current) {- clearTimeout(attachmentErrorTimer.current);- }- attachmentErrorTimer.current = setTimeout(() => {- setAttachmentError(null);- attachmentErrorTimer.current = null;- }, 4000);- }, []);-- const filterAndReportFiles = useCallback(- (files: File[]): File[] => {- let runningTotal = attachments.reduce((s, a) => s + (a.size ?? 0), 0);- const accepted: File[] = [];- const rejected: {- name: string;- reason: "unsupported" | "too_large" | "quota";- }[] = [];- for (const f of files) {- const kind = classifyFile(f);- if (!kind) {- rejected.push({ name: f.name, reason: "unsupported" });- continue;- }- if (f.size > MAX_ATTACHMENT_BYTES) {- rejected.push({ name: f.name, reason: "too_large" });- continue;- }- if (runningTotal + f.size > MAX_TOTAL_ATTACHMENT_BYTES) {- rejected.push({ name: f.name, reason: "quota" });- break;- }- runningTotal += f.size;- accepted.push(f);- }- if (rejected.length) {- const first = rejected[0];- let msg: string;- if (first.reason === "too_large") {- msg = t("File too large: {{name}}", { name: first.name });- } else if (first.reason === "quota") {- msg = t("Too many files, skipped some");- } else {- msg = t("Unsupported file type: {{name}}", { name: first.name });- }- showAttachmentError(msg);- }- return accepted;- },- [attachments, showAttachmentError, t],- );-- const handlePaste = useCallback(- async (event: React.ClipboardEvent) => {- const items = Array.from(event.clipboardData.items);- const files = items- .filter((item) => item.kind === "file")- .map((item) => item.getAsFile())- .filter((f): f is File => f !== null);- const accepted = filterAndReportFiles(files);- if (!accepted.length) return;- event.preventDefault();- const next = await Promise.all(accepted.map(fileToAttachment));- setAttachments((prev) => [...prev, ...next]);- },- [fileToAttachment, filterAndReportFiles],- );-- const removeAttachment = useCallback((index: number) => {- setAttachments((prev) => prev.filter((_, i) => i !== index));- }, []);-- const handlePreviewPendingAttachment = useCallback(- (index: number) => {- const a = attachments[index];- if (!a) return;- setPreviewSource({- filename: a.filename,- mimeType: a.mimeType,- type: a.type,- base64: a.base64,- size: a.size,- });- },- [attachments],- );-- const handlePreviewMessageAttachment = useCallback((a: MessageAttachment) => {- setPreviewSource({- filename: a.filename || "",- mimeType: a.mime_type,- type: a.type,- url: a.url,- base64: a.base64,- extractedText: a.extracted_text,- id: a.id,- });- }, []);-- const handleClosePreview = useCallback(() => {- setPreviewSource(null);- }, []);-- const handleDragEnter = useCallback((e: React.DragEvent) => {- e.preventDefault();- e.stopPropagation();- dragCounter.current += 1;- if (e.dataTransfer.types.includes("Files")) setDragging(true);- }, []);-- const handleDragLeave = useCallback((e: React.DragEvent) => {- e.preventDefault();- e.stopPropagation();- dragCounter.current -= 1;- if (dragCounter.current === 0) setDragging(false);- }, []);-- const handleDragOver = useCallback((e: React.DragEvent) => {- e.preventDefault();- e.stopPropagation();- }, []);-- const handleDrop = useCallback(- async (e: React.DragEvent) => {- e.preventDefault();- e.stopPropagation();- setDragging(false);- dragCounter.current = 0;- const accepted = filterAndReportFiles(Array.from(e.dataTransfer.files));- if (!accepted.length) return;- const next = await Promise.all(accepted.map(fileToAttachment));- setAttachments((prev) => [...prev, ...next]);- },- [fileToAttachment, filterAndReportFiles],- );-- const handleAddFiles = useCallback(- async (files: File[]) => {- const accepted = filterAndReportFiles(files);- if (!accepted.length) return;- const next = await Promise.all(accepted.map(fileToAttachment));- setAttachments((prev) => [...prev, ...next]);- },- [fileToAttachment, filterAndReportFiles],- );-- const handleSend = useCallback(- async (content: string) => {- if (- (!content &&- !attachments.length &&- !selectedBookReferences.length &&- !selectedNotebookRecords.length &&- !selectedHistorySessions.length &&- !selectedQuestionEntries.length &&- !selectedSkills.length &&- !skillsAutoMode &&- !selectedMemoryFiles.length) ||- state.isStreaming- )- return;-- let extraAttachments = attachments.map((a) => ({- type: a.type,- filename: a.filename,- base64: a.base64,- mime_type: a.mimeType,- }));- let config: Record<string, unknown> | undefined;-- if (isQuizMode) {- config = buildQuizWSConfig(quizConfig);- if (quizConfig.mode === "mimic" && quizPdf) {- const b64 = extractBase64FromDataUrl(- await readFileAsDataUrl(quizPdf),- );- extraAttachments = [- ...extraAttachments,- {- type: "pdf",- filename: quizPdf.name,- base64: b64,- mime_type: "application/pdf",- },- ];- }- }- if (isMathAnimatorMode)- config = buildMathAnimatorWSConfig(mathAnimatorConfig);- if (isVisualizeMode) config = buildVisualizeWSConfig(visualizeConfig);- if (isResearchMode) config = buildResearchWSConfig(researchConfig);-- const skillsPayload = skillsAutoMode ? ["auto"] : [...selectedSkills];- const memoryPayload = [...memoryReferencesPayload];- const messageContent =- content ||- (selectedNotebookRecords.length ||- selectedBookReferences.length ||- selectedHistorySessions.length ||- selectedQuestionEntries.length ||- skillsPayload.length ||- memoryPayload.length- ? t("Please use the selected context to help with this request.")- : "") ||- (isMathAnimatorMode- ? attachments.some((a) => a.type === "image")- ? t(- "Generate a math animation from the attached reference image(s).",- )- : ""- : attachments.some((a) => a.type === "image")- ? t("Please analyze the attached image(s).")- : "");- sendMessage(- messageContent,- extraAttachments,- config,- notebookReferencesPayload,- historyReferencesPayload,- { bookReferences: bookReferencesPayload },- questionNotebookReferencesPayload,- skillsPayload,- memoryPayload,- );- shouldAutoScrollRef.current = true;- // Auto-collapse the per-capability settings panel after sending so the- // composer stays compact during conversation.- setPanelCollapsed(true);- setAttachments([]);- setSelectedBookReferences([]);- setSelectedNotebookRecords([]);- setSelectedHistorySessions([]);- setSelectedQuestionEntries([]);- setSelectedSkills([]);- setSkillsAutoMode(false);- setSelectedMemoryFiles([]);- },- [- attachments,- bookReferencesPayload,- historyReferencesPayload,- isMathAnimatorMode,- isQuizMode,- isResearchMode,- isVisualizeMode,- mathAnimatorConfig,- memoryReferencesPayload,- notebookReferencesPayload,- questionNotebookReferencesPayload,- quizConfig,- quizPdf,- researchConfig,- selectedHistorySessions.length,- selectedMemoryFiles.length,- selectedBookReferences.length,- selectedNotebookRecords.length,- selectedQuestionEntries.length,- selectedSkills,- skillsAutoMode,- sendMessage,- shouldAutoScrollRef,- state.isStreaming,- t,- visualizeConfig,- ],- );-- const handleConfirmOutline = useCallback(- (- outline: OutlineItem[],- _topic: string,- originalConfig?: Record<string, unknown> | null,- ) => {- const config: Record<string, unknown> = {- ...(originalConfig ?? {- mode: researchConfig.mode,- depth: researchConfig.depth,- sources: [...researchConfig.sources],- }),- confirmed_outline: outline,- };- sendMessage(_topic, [], config, undefined, undefined, {- displayUserMessage: false,- persistUserMessage: false,- });- shouldAutoScrollRef.current = true;- },- [researchConfig, sendMessage, shouldAutoScrollRef],- );-- const handleRegenerateMessage = useCallback(() => {- regenerateLastMessage();- }, [regenerateLastMessage]);-- const handleSetKB = useCallback(- (kb: string) => {- setKBs(kb ? [kb] : []);- },- [setKBs],- );- const handleSelectNotebookPicker = useCallback(() => {- setShowNotebookPicker(true);- }, []);- const handleSelectBookPicker = useCallback(() => {- setShowBookPicker(true);- }, []);- const handleSelectHistoryPicker = useCallback(() => {- setShowHistoryPicker(true);- }, []);- const handleSelectQuestionBankPicker = useCallback(() => {- setShowQuestionBankPicker(true);- }, []);- const handleSelectSkillsPicker = useCallback(() => {- setShowSkillsPicker(true);- }, []);- const handleSelectMemoryPicker = useCallback(() => {- setShowMemoryPicker(true);- }, []);- const handleRemoveHistory = useCallback((sessionId: string) => {- setSelectedHistorySessions((prev) =>- prev.filter((item) => item.sessionId !== sessionId),- );- }, []);- const handleRemoveNotebook = useCallback((notebookId: string) => {- setSelectedNotebookRecords((prev) =>- prev.filter((record) => record.notebookId !== notebookId),- );- }, []);- const handleRemoveBookReference = useCallback((bookId: string) => {- setSelectedBookReferences((prev) =>- prev.filter((record) => record.bookId !== bookId),- );- }, []);- const handleRemoveQuestion = useCallback((entryId: number) => {- setSelectedQuestionEntries((prev) =>- prev.filter((entry) => entry.id !== entryId),- );- }, []);- const handleToggleSkill = useCallback((name: string) => {- setSkillsAutoMode(false);- setSelectedSkills((prev) =>- prev.includes(name) ? prev.filter((n) => n !== name) : [...prev, name],- );- }, []);-- const handleSetSkillsAuto = useCallback((auto: boolean) => {- setSkillsAutoMode(auto);- if (auto) setSelectedSkills([]);- }, []);-- const handleToggleMemoryFile = useCallback((file: SpaceMemoryFile) => {- setSelectedMemoryFiles((prev) =>- prev.includes(file)- ? prev.filter((item) => item !== file)- : [...prev, file],- );- }, []);-- const handleTogglePanelCollapsed = useCallback(() => {- setPanelCollapsed((prev) => !prev);- }, []);- const handleCloseNotebookPicker = useCallback(() => {- setShowNotebookPicker(false);- }, []);- const handleCloseBookPicker = useCallback(() => {- setShowBookPicker(false);- }, []);- const handleApplyBookReferences = useCallback(- (references: SelectedBookReference[]) => {- setSelectedBookReferences(references);- },- [],- );- const handleApplyNotebookRecords = useCallback(- (records: SelectedRecord[]) => {- setSelectedNotebookRecords(records);- },- [],- );- const handleCloseHistoryPicker = useCallback(() => {- setShowHistoryPicker(false);- }, []);- const handleApplyHistorySessions = useCallback(- (sessions: SelectedHistorySession[]) => {- setSelectedHistorySessions(sessions);- },- [],- );- const handleCloseQuestionBankPicker = useCallback(() => {- setShowQuestionBankPicker(false);- }, []);- const handleApplyQuestionEntries = useCallback(- (entries: SelectedQuestionEntry[]) => {- setSelectedQuestionEntries(entries);- },- [],- );- const handleCloseSkillsPicker = useCallback(() => {- setShowSkillsPicker(false);- }, []);- const handleApplySkillsSelection = useCallback(- (selection: { auto: boolean; skills: string[] }) => {- setSkillsAutoMode(selection.auto);- setSelectedSkills(selection.auto ? [] : selection.skills);- },- [],- );- const handleCloseMemoryPicker = useCallback(() => {- setShowMemoryPicker(false);- }, []);- const handleApplyMemoryFiles = useCallback((files: SpaceMemoryFile[]) => {- setSelectedMemoryFiles(files);- }, []);- const handleCloseSaveModal = useCallback(() => {- setShowSaveModal(false);- }, []);-- const handleNewChat = useCallback(() => {- cancelStreamingTurn();- router.push("/chat");- }, [cancelStreamingTurn, router]);-- const handleDownloadMarkdown = useCallback(() => {- if (!state.messages.length) return;- const title =- state.messages- .find((msg) => msg.role === "user")- ?.content.trim()- .slice(0, 80) || "Chat Session";- downloadChatMarkdown(state.messages, { title });- }, [state.messages]);-- return (- <div- // When the preview drawer is open AND the viewport is wide enough,- // push the chat content to the left by the drawer's width so the two- // panels live side-by-side (matches Claude desktop). On smaller- // screens the drawer overlays — squeezing a phone-width chat into- // the remaining ~30 px would be useless. The actual padding +- // transition lives in `chat-preview-shell` (globals.css) so we can- // hand-tune it without fighting Tailwind's arbitrary-value parser.- data-preview-open={previewSource ? "true" : "false"}- className="chat-preview-shell flex h-full flex-col overflow-hidden bg-[var(--background)]"- >- <div className="mx-auto flex w-full max-w-[960px] items-center justify-between px-6 pt-3 pb-0">- <span className="text-[15px] font-semibold tracking-[-0.01em] text-[var(--foreground)]">- {t(activeCap.label)}- </span>- <div className="flex items-center gap-2">- <button- onClick={() => setShowSaveModal(true)}- disabled={!chatSavePayload}- className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-[var(--border)]/50 disabled:hover:text-[var(--muted-foreground)]"- >- {t("Save to Notebook")}- </button>- <button- onClick={handleDownloadMarkdown}- disabled={!state.messages.length}- title={t("Download chat history as Markdown")}- className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-[var(--border)]/50 disabled:hover:text-[var(--muted-foreground)]"- >- {t("Download Markdown")}- </button>- <button- onClick={handleNewChat}- className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"- >- {t("New chat")}- </button>- </div>- </div>- <div className="mx-auto flex w-full max-w-[960px] flex-1 min-h-0 flex-col overflow-hidden px-6">- {!hasMessages ? (- <div className="flex flex-1 min-h-0 flex-col items-center justify-center animate-fade-in">- <div className="text-center">- <h1 className="font-serif text-[36px] font-medium tracking-[-0.01em] text-[var(--foreground)]">- {t("What would you like to learn?")}- </h1>- <p className="mt-4 text-[15px] text-[var(--muted-foreground)]">- {t("Ask anything — I'm here to help you understand.")}- </p>- </div>- </div>- ) : (- <div- ref={messagesContainerRef}- data-chat-scroll-root="true"- onScroll={handleMessagesScroll}- className={`mx-auto w-full flex-1 min-h-0 space-y-7 overflow-y-auto pr-4 [scrollbar-gutter:stable] ${hasMessages ? "pt-0" : "pt-2 pb-6"}`}- style={- hasMessages- ? (() => {- const maskImage =- "linear-gradient(to bottom, transparent 0px, #000 32px, #000 calc(100% - 40px), transparent 100%)";- return {- paddingBottom: "4px",- WebkitMaskImage: maskImage,- maskImage,- };- })()- : undefined- }- >- <ChatMessageList- messages={state.messages}- isStreaming={state.isStreaming}- sessionId={state.sessionId}- language={state.language}- onAnswerNow={handleAnswerNow}- onCopyAssistantMessage={copyAssistantMessage}- onRegenerateMessage={handleRegenerateMessage}- onConfirmOutline={handleConfirmOutline}- onPreviewAttachment={handlePreviewMessageAttachment}- />- <div ref={messagesEndRef} className="h-px w-full shrink-0" />- </div>- )}-- <ChatComposer- composerRef={composerRef}- capMenuRef={capMenuRef}- capBtnRef={capBtnRef}- toolMenuRef={toolMenuRef}- toolBtnRef={toolBtnRef}- spaceMenuRef={spaceMenuRef}- spaceBtnRef={spaceBtnRef}- dragCounter={dragCounter}- dragging={dragging}- capMenuOpen={capMenuOpen}- toolMenuOpen={toolMenuOpen}- spaceMenuOpen={spaceMenuOpen}- hasMessages={hasMessages}- attachments={attachments}- attachmentError={attachmentError}- activeCap={activeCap}- visibleTools={visibleTools}- selectedTools={selectedTools}- ragActive={ragActive}- knowledgeBases={knowledgeBases}- llmOptions={llmOptions}- activeLLMDefault={activeLLMDefault}- llmSelection={state.llmSelection}- llmOptionsLoading={llmOptionsLoading}- llmOptionsError={llmOptionsError}- selectedBookReferences={selectedBookReferences}- selectedNotebookRecords={selectedNotebookRecords}- selectedHistorySessions={selectedHistorySessions}- selectedQuestionEntries={selectedQuestionEntries}- notebookReferenceGroups={notebookReferenceGroups}- selectedSkills={selectedSkills}- skillsAutoMode={skillsAutoMode}- selectedMemoryFiles={selectedMemoryFiles}- stateKnowledgeBase={state.knowledgeBases[0] || ""}- isStreaming={state.isStreaming}- isResearchMode={isResearchMode}- isQuizMode={isQuizMode}- isMathAnimatorMode={isMathAnimatorMode}- isVisualizeMode={isVisualizeMode}- quizConfig={quizConfig}- quizPdf={quizPdf}- mathAnimatorConfig={mathAnimatorConfig}- visualizeConfig={visualizeConfig}- researchConfig={researchConfig}- researchValidationErrors={researchValidation.errors}- panelCollapsed={panelCollapsed}- capabilities={CAPABILITIES}- researchSources={RESEARCH_SOURCES}- onSetCapMenuOpen={setCapMenuOpen}- onSetToolMenuOpen={setToolMenuOpen}- onSetSpaceMenuOpen={setSpaceMenuOpen}- onSetKB={handleSetKB}- onSelectLLM={setLLMSelection}- onSelectNotebookPicker={handleSelectNotebookPicker}- onSelectBookPicker={handleSelectBookPicker}- onSelectHistoryPicker={handleSelectHistoryPicker}- onSelectQuestionBankPicker={handleSelectQuestionBankPicker}- onSelectSkillsPicker={handleSelectSkillsPicker}- onSelectMemoryPicker={handleSelectMemoryPicker}- onToggleTool={toggleTool}- onToggleSkill={handleToggleSkill}- onSetSkillsAuto={handleSetSkillsAuto}- onToggleMemoryFile={handleToggleMemoryFile}- onToggleResearchSource={toggleResearchSource}- onSend={handleSend}- onRemoveAttachment={removeAttachment}- onPreviewAttachment={handlePreviewPendingAttachment}- onRemoveHistory={handleRemoveHistory}- onRemoveBookReference={handleRemoveBookReference}- onRemoveNotebook={handleRemoveNotebook}- onRemoveQuestion={handleRemoveQuestion}- onDragEnter={handleDragEnter}- onDragLeave={handleDragLeave}- onDragOver={handleDragOver}- onDrop={handleDrop}- onPaste={handlePaste}- onAddFiles={handleAddFiles}- onSelectCapability={handleSelectCapability}- onCancelStreaming={cancelStreamingTurn}- onChangeQuizConfig={setQuizConfig}- onUploadQuizPdf={setQuizPdf}- onChangeMathAnimatorConfig={setMathAnimatorConfig}- onChangeVisualizeConfig={setVisualizeConfig}- onChangeResearchConfig={setResearchConfig}- onTogglePanelCollapsed={handleTogglePanelCollapsed}- />- </div>- <NotebookRecordPicker- open={showNotebookPicker}- onClose={handleCloseNotebookPicker}- onApply={handleApplyNotebookRecords}- />- <BookReferencePicker- open={showBookPicker}- initialReferences={selectedBookReferences}- onClose={handleCloseBookPicker}- onApply={handleApplyBookReferences}- />- <HistorySessionPicker- open={showHistoryPicker}- onClose={handleCloseHistoryPicker}- onApply={handleApplyHistorySessions}- />- <QuestionBankPicker- open={showQuestionBankPicker}- onClose={handleCloseQuestionBankPicker}- onApply={handleApplyQuestionEntries}- />- <SkillsPicker- open={showSkillsPicker}- initialAuto={skillsAutoMode}- initialSkills={selectedSkills}- onClose={handleCloseSkillsPicker}- onApply={handleApplySkillsSelection}- />- <MemoryPicker- open={showMemoryPicker}- initialFiles={selectedMemoryFiles}- onClose={handleCloseMemoryPicker}- onApply={handleApplyMemoryFiles}- />- <SaveToNotebookModal- open={showSaveModal}- payload={chatSavePayload}- messages={chatSaveMessages}- onClose={handleCloseSaveModal}- />- <FilePreviewDrawer- open={previewSource !== null}- source={previewSource}- onClose={handleClosePreview}- />- </div>- );-}+"use client";++import dynamic from "next/dynamic";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useParams, useRouter } from "next/navigation";++import {+ BarChart3,+ BrainCircuit,+ Clapperboard,+ Code2,+ Database,+ FileSearch,+ Globe,+ Lightbulb,+ MessageSquare,+ Microscope,+ PenLine,+ Sparkles,+ type LucideIcon,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import type { SelectedRecord } from "@/lib/notebook-selection-types";+import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";+import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";+import ChatComposer from "@/components/chat/home/ChatComposer";+import { ChatMessageList } from "@/components/chat/home/ChatMessages";+// Imported eagerly so the drawer shell is always mounted off-screen —+// clicking a chip becomes a single CSS class flip, no chunk fetch + double+// render. The heavy renderers inside still load lazily.+import FilePreviewDrawer from "@/components/chat/preview/FilePreviewDrawer";+import SessionActivityPanel, {+ buildSessionActivity,+} from "@/components/chat/home/SessionActivityPanel";+import SessionViewerPanel, {+ type SessionViewerPanelHandle,+} from "@/components/chat/home/SessionViewerPanel";+import {+ BookmarkPlus,+ BookOpen,+ Download,+ PanelRight,+ SquarePen,+} from "lucide-react";+import {+ useUnifiedChat,+ type MessageAttachment,+ type MessageRequestSnapshot,+} from "@/context/UnifiedChatContext";+import { useAppShell } from "@/context/AppShellContext";+import type { FilePreviewSource } from "@/components/chat/preview/previewerFor";+import type { LLMSelection, StreamEvent } from "@/lib/unified-ws";+import {+ extractBase64FromDataUrl,+ readFileAsDataUrl,+} from "@/lib/file-attachments";+import {+ classifyFile,+ isSvgFilename,+ MAX_ATTACHMENT_BYTES,+ MAX_TOTAL_ATTACHMENT_BYTES,+} from "@/lib/doc-attachments";+import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";+import { useMeasuredHeight } from "@/hooks/useMeasuredHeight";+import {+ loadCapabilityPlaygroundConfigs,+ resolveCapabilityPlaygroundConfig,+ type CapabilityPlaygroundConfigMap,+} from "@/lib/playground-config";+import {+ DEFAULT_QUIZ_CONFIG,+ buildQuizWSConfig,+ type DeepQuestionFormConfig,+} from "@/lib/quiz-types";+import {+ DEFAULT_MATH_ANIMATOR_CONFIG,+ buildMathAnimatorWSConfig,+ type MathAnimatorFormConfig,+} from "@/lib/math-animator-types";+import {+ DEFAULT_VISUALIZE_CONFIG,+ buildVisualizeWSConfig,+ type VisualizeFormConfig,+} from "@/lib/visualize-types";+import {+ buildResearchWSConfig,+ createEmptyResearchConfig,+ validateResearchConfig,+ type DeepResearchFormConfig,+ type OutlineItem,+ type ResearchSource,+} from "@/lib/research-types";+import { listKnowledgeBases } from "@/lib/knowledge-api";+import { listLLMOptions, type LLMOption } from "@/lib/llm-options";+import { downloadChatMarkdown } from "@/lib/chat-export";+import type { SpaceMemoryFile } from "@/lib/space-items";+import {+ selectedBooksToPayload,+ type SelectedBookReference,+} from "@/lib/book-references";++const NotebookRecordPicker = dynamic(+ () => import("@/components/notebook/NotebookRecordPicker"),+ {+ ssr: false,+ },+);+const HistorySessionPicker = dynamic(+ () => import("@/components/chat/HistorySessionPicker"),+ {+ ssr: false,+ },+);+const QuestionBankPicker = dynamic(+ () => import("@/components/chat/QuestionBankPicker"),+ {+ ssr: false,+ },+);+const SkillsPicker = dynamic(() => import("@/components/chat/SkillsPicker"), {+ ssr: false,+});+const MemoryPicker = dynamic(() => import("@/components/chat/MemoryPicker"), {+ ssr: false,+});+const BookReferencePicker = dynamic(+ () => import("@/components/chat/BookReferencePicker"),+ {+ ssr: false,+ },+);+const SaveToNotebookModal = dynamic(+ () => import("@/components/notebook/SaveToNotebookModal"),+ {+ ssr: false,+ },+);+// Activity-panel config card hosts the capability-specific form (Quiz /+// Animator / Visualize / Research). Lazy-loaded so capabilities that+// don't need a form (Chat / Solve) don't ship the form JS.+const CapabilityConfigCard = dynamic(+ () => import("@/components/chat/home/CapabilityConfigCard"),+ { ssr: false },+);+const QuizConfigPanel = dynamic(+ () => import("@/components/quiz/QuizConfigPanel"),+ { ssr: false },+);+const MathAnimatorConfigPanel = dynamic(+ () => import("@/components/math-animator/MathAnimatorConfigPanel"),+ { ssr: false },+);+const VisualizeConfigPanel = dynamic(+ () => import("@/components/visualize/VisualizeConfigPanel"),+ { ssr: false },+);+const ResearchConfigPanel = dynamic(+ () => import("@/components/research/ResearchConfigPanel"),+ { ssr: false },+);++/* ------------------------------------------------------------------ */+/* Type & data definitions */+/* ------------------------------------------------------------------ */++type ToolName =+ | "brainstorm"+ | "web_search"+ | "code_execution"+ | "reason"+ | "paper_search";++interface ToolDef {+ name: ToolName;+ label: string;+ icon: LucideIcon;+}++interface ResearchSourceDef {+ name: ResearchSource;+ label: string;+ icon: LucideIcon;+}++const ALL_TOOLS: ToolDef[] = [+ { name: "brainstorm", label: "Brainstorm", icon: Lightbulb },+ { name: "web_search", label: "Web Search", icon: Globe },+ { name: "code_execution", label: "Code", icon: Code2 },+ { name: "reason", label: "Reason", icon: Sparkles },+ { name: "paper_search", label: "Arxiv Search", icon: FileSearch },+];++const RESEARCH_SOURCES: ResearchSourceDef[] = [+ { name: "kb", label: "Knowledge Base", icon: Database },+ { name: "web", label: "Web", icon: Globe },+ { name: "papers", label: "Papers", icon: FileSearch },+];++interface CapabilityDef {+ value: string;+ label: string;+ description: string;+ icon: LucideIcon;+ allowedTools: ToolName[];+ defaultTools: ToolName[];+}++const CAPABILITIES: CapabilityDef[] = [+ {+ value: "",+ label: "Chat",+ description: "Flexible conversation with any tool",+ icon: MessageSquare,+ allowedTools: [+ "brainstorm",+ "web_search",+ "code_execution",+ "reason",+ "paper_search",+ ],+ defaultTools: [],+ },+ {+ value: "deep_solve",+ label: "Solve",+ description: "Multi-step reasoning & problem solving",+ icon: BrainCircuit,+ allowedTools: ["web_search", "code_execution", "reason"],+ defaultTools: ["web_search", "code_execution", "reason"],+ },+ {+ value: "deep_question",+ label: "Quiz",+ description: "Auto-validated question generation",+ icon: PenLine,+ allowedTools: ["web_search", "code_execution"],+ defaultTools: ["web_search", "code_execution"],+ },+ {+ value: "deep_research",+ label: "Research",+ description: "Comprehensive multi-agent research",+ icon: Microscope,+ allowedTools: [],+ defaultTools: [],+ },+ {+ value: "math_animator",+ label: "Animator",+ description: "Generate math videos or storyboard images",+ icon: Clapperboard,+ allowedTools: [],+ defaultTools: [],+ },+ {+ value: "visualize",+ label: "Visualize",+ description: "Generate SVG, Chart.js, or Mermaid visualizations",+ icon: BarChart3,+ allowedTools: [],+ defaultTools: [],+ },+];++interface KnowledgeBase {+ name: string;+ is_default?: boolean;+}++interface PendingAttachment {+ type: string;+ filename: string;+ base64?: string;+ previewUrl?: string;+ size?: number;+ mimeType?: string;+}++/* ------------------------------------------------------------------ */+/* Helpers */+/* ------------------------------------------------------------------ */++// ChatComposer still accepts isAutoMode/autoEnabledCaps/onToggleAutoCap so that+// the same component can also be reused by the /co-learn page. Manual chat+// always passes these dummies — the auto multi-select popover is never shown.+const EMPTY_SET = new Set<string>();+const noopToggleAutoCap = (_cap: string) => undefined;++function getCapability(value: string | null): CapabilityDef {+ return CAPABILITIES.find((c) => c.value === (value || "")) ?? CAPABILITIES[0];+}++/* ------------------------------------------------------------------ */+/* Chat page */+/* ------------------------------------------------------------------ */++export default function ChatPage() {+ const params = useParams<{ sessionId?: string[] }>();+ const router = useRouter();+ const { t } = useTranslation();+ const sessionIdParam = params.sessionId?.[0] ?? null;+ const { setActiveSessionId, language: appLanguage } = useAppShell();++ const {+ state,+ setTools,+ setCapability,+ setKBs,+ setLLMSelection,+ sendMessage,+ cancelStreamingTurn,+ regenerateLastMessage,+ deleteTurn,+ editMessage,+ switchBranch,+ newSession,+ loadSession,+ } = useUnifiedChat();++ const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);+ const [llmOptions, setLLMOptions] = useState<LLMOption[]>([]);+ const [activeLLMDefault, setActiveLLMDefault] = useState<LLMSelection | null>(+ null,+ );+ const [llmOptionsLoading, setLLMOptionsLoading] = useState(true);+ const [llmOptionsError, setLLMOptionsError] = useState(false);+ const [capabilityConfigs, setCapabilityConfigs] =+ useState<CapabilityPlaygroundConfigMap>({});+ const [attachments, setAttachments] = useState<PendingAttachment[]>([]);+ const [dragging, setDragging] = useState(false);+ const [attachmentError, setAttachmentError] = useState<string | null>(null);+ const [previewSource, setPreviewSource] = useState<FilePreviewSource | null>(+ null,+ );+ // When the chat column squeezes (e.g. the Viewer panel opens), the header+ // action labels can collide. We measure the actual header width and flip+ // to icon-only buttons below a threshold so the row never overflows.+ // Important: read full border-box width via getBoundingClientRect — the+ // ResizeObserverEntry.contentRect excludes the header's px-6 padding+ // (48 px), which makes a "naive" threshold land 48 px below where labels+ // actually start colliding.+ const headerRef = useRef<HTMLDivElement | null>(null);+ const [headerMeasuredWidth, setHeaderMeasuredWidth] = useState<number>(+ Number.POSITIVE_INFINITY,+ );+ useEffect(() => {+ const el = headerRef.current;+ if (!el || typeof ResizeObserver === "undefined") return;+ setHeaderMeasuredWidth(el.getBoundingClientRect().width);+ const observer = new ResizeObserver(() => {+ // entry.contentRect drops padding; the visual collision happens at+ // border-box width, so read it directly off the element.+ if (headerRef.current) {+ setHeaderMeasuredWidth(+ headerRef.current.getBoundingClientRect().width,+ );+ }+ });+ observer.observe(el);+ return () => observer.disconnect();+ }, []);+ // Right-side panels — Activity (floating cards) and Viewer (full sidebar+ // with tabs for file previews + web pages). Each independently togglable+ // and persisted across reloads.+ //+ // We initialise both to `false` so the SSR-rendered HTML matches the+ // first client render exactly (no hydration mismatch). The persisted+ // preference is then applied in a post-mount effect below.+ const [activityPanelOpen, setActivityPanelOpen] = useState(false);+ const [viewerPanelOpen, setViewerPanelOpen] = useState(false);+ useEffect(() => {+ if (typeof window === "undefined") return;+ if (window.localStorage.getItem("dt:chat:activity-panel") === "1") {+ setActivityPanelOpen(true);+ }+ if (window.localStorage.getItem("dt:chat:viewer-panel") === "1") {+ setViewerPanelOpen(true);+ }+ }, []);+ const toggleActivityPanel = useCallback(() => {+ setActivityPanelOpen((prev) => {+ const next = !prev;+ if (typeof window !== "undefined") {+ window.localStorage.setItem(+ "dt:chat:activity-panel",+ next ? "1" : "0",+ );+ }+ return next;+ });+ }, []);+ /**+ * Force the Activity panel open. Used by the send-gate when the user+ * tries to send while the active capability still needs its config+ * confirmed — we surface the right-side panel so the Confirm button is+ * visible. Persisted to localStorage so subsequent reloads remember the+ * preference. Also used by the capability-switch auto-open effect below.+ */+ const ensureActivityPanelOpen = useCallback(() => {+ setActivityPanelOpen((prev) => {+ if (prev) return prev;+ if (typeof window !== "undefined") {+ window.localStorage.setItem("dt:chat:activity-panel", "1");+ }+ return true;+ });+ }, []);+ const setViewerOpen = useCallback((next: boolean) => {+ setViewerPanelOpen(next);+ if (typeof window !== "undefined") {+ window.localStorage.setItem("dt:chat:viewer-panel", next ? "1" : "0");+ }+ }, []);+ const toggleViewerPanel = useCallback(() => {+ setViewerPanelOpen((prev) => {+ const next = !prev;+ if (typeof window !== "undefined") {+ window.localStorage.setItem(+ "dt:chat:viewer-panel",+ next ? "1" : "0",+ );+ }+ return next;+ });+ }, []);+ // The header's five labelled actions ("Save to Notebook" / "Download+ // Markdown" / "New chat" / "Activity" / "Viewer") need roughly 720 px+ // (label widths + gaps + the capability title) to fit on one row without+ // colliding. Below that we collapse all five to icon-only. We also+ // force-collapse whenever the Viewer panel is open — its squeeze is+ // aggressive enough that labels are guaranteed to overflow.+ const headerCompact = viewerPanelOpen || headerMeasuredWidth < 720;+ const attachmentErrorTimer = useRef<ReturnType<typeof setTimeout> | null>(+ null,+ );+ const [capMenuOpen, setCapMenuOpen] = useState(false);+ const [quizConfig, setQuizConfig] = useState<DeepQuestionFormConfig>({+ ...DEFAULT_QUIZ_CONFIG,+ });+ const [quizPdf, setQuizPdf] = useState<File | null>(null);+ const [mathAnimatorConfig, setMathAnimatorConfig] =+ useState<MathAnimatorFormConfig>({+ ...DEFAULT_MATH_ANIMATOR_CONFIG,+ });+ const [visualizeConfig, setVisualizeConfig] = useState<VisualizeFormConfig>({+ ...DEFAULT_VISUALIZE_CONFIG,+ });+ const [researchConfig, setResearchConfig] = useState<DeepResearchFormConfig>(+ createEmptyResearchConfig(),+ );+ // Capability-config confirmation gate.+ //+ // For capabilities that need explicit configuration (Quiz, Animator,+ // Visualize, Research), the user must click *Confirm* in the right-side+ // Activity panel before sending. Any subsequent edit to the underlying+ // config invalidates the confirmation, so the user re-confirms once+ // they've adjusted settings. Capability switches also reset this flag.+ const [capabilityConfigConfirmed, setCapabilityConfigConfirmed] =+ useState(false);+ const [showSaveModal, setShowSaveModal] = useState(false);+ const [showNotebookPicker, setShowNotebookPicker] = useState(false);+ const [showBookPicker, setShowBookPicker] = useState(false);+ const [showHistoryPicker, setShowHistoryPicker] = useState(false);+ const [showQuestionBankPicker, setShowQuestionBankPicker] = useState(false);+ const [showSkillsPicker, setShowSkillsPicker] = useState(false);+ const [showMemoryPicker, setShowMemoryPicker] = useState(false);+ const [toolMenuOpen, setToolMenuOpen] = useState(false);+ const [spaceMenuOpen, setSpaceMenuOpen] = useState(false);+ const [kbMenuOpen, setKbMenuOpen] = useState(false);+ const [selectedNotebookRecords, setSelectedNotebookRecords] = useState<+ SelectedRecord[]+ >([]);+ const [selectedBookReferences, setSelectedBookReferences] = useState<+ SelectedBookReference[]+ >([]);+ const [selectedHistorySessions, setSelectedHistorySessions] = useState<+ SelectedHistorySession[]+ >([]);+ const [selectedQuestionEntries, setSelectedQuestionEntries] = useState<+ SelectedQuestionEntry[]+ >([]);+ const [selectedSkills, setSelectedSkills] = useState<string[]>([]);+ const [skillsAutoMode, setSkillsAutoMode] = useState(false);+ const [selectedMemoryFiles, setSelectedMemoryFiles] = useState<+ SpaceMemoryFile[]+ >([]);+ const dragCounter = useRef(0);+ const capMenuRef = useRef<HTMLDivElement>(null);+ const capBtnRef = useRef<HTMLButtonElement>(null);+ const toolMenuRef = useRef<HTMLDivElement>(null);+ const toolBtnRef = useRef<HTMLButtonElement>(null);+ const spaceMenuRef = useRef<HTMLDivElement>(null);+ const spaceBtnRef = useRef<HTMLButtonElement>(null);+ const kbMenuRef = useRef<HTMLDivElement>(null);+ const kbBtnRef = useRef<HTMLButtonElement>(null);+ const initialLoadRef = useRef(false);++ const activeCap = useMemo(+ () => getCapability(state.activeCapability),+ [state.activeCapability],+ );+ const isQuizMode = activeCap.value === "deep_question";+ const isMathAnimatorMode = activeCap.value === "math_animator";+ const isVisualizeMode = activeCap.value === "visualize";+ const isResearchMode = activeCap.value === "deep_research";+ const capabilityNeedsConfig =+ isQuizMode || isMathAnimatorMode || isVisualizeMode || isResearchMode;++ // Edit-invalidates-confirm wrappers — flipping any field after the user+ // hit *Confirm* should restore the gate so they re-confirm intentionally.+ // `useCallback` keeps identities stable so the memoized ChatComposer /+ // CapabilityConfigCard don't churn on every keystroke.+ const handleChangeQuizConfig = useCallback(+ (next: DeepQuestionFormConfig) => {+ setQuizConfig(next);+ setCapabilityConfigConfirmed(false);+ },+ [],+ );+ const handleUploadQuizPdf = useCallback((file: File | null) => {+ setQuizPdf(file);+ setCapabilityConfigConfirmed(false);+ }, []);+ const handleChangeMathAnimatorConfig = useCallback(+ (next: MathAnimatorFormConfig) => {+ setMathAnimatorConfig(next);+ setCapabilityConfigConfirmed(false);+ },+ [],+ );+ const handleChangeVisualizeConfig = useCallback(+ (next: VisualizeFormConfig) => {+ setVisualizeConfig(next);+ setCapabilityConfigConfirmed(false);+ },+ [],+ );+ const handleChangeResearchConfig = useCallback(+ (next: DeepResearchFormConfig) => {+ setResearchConfig(next);+ setCapabilityConfigConfirmed(false);+ },+ [],+ );+ const handleConfirmCapabilityConfig = useCallback(() => {+ setCapabilityConfigConfirmed(true);+ }, []);++ /**+ * Auto-open the right-side Activity panel when the user switches into a+ * capability that requires manual configuration (Quiz / Animator /+ * Visualize / Research). We only fire on the transition from "doesn't+ * need config" → "needs config" so we don't fight the user if they+ * close the panel themselves while still in a config-needing mode.+ *+ * Tracking via a ref (instead of deps) avoids re-firing whenever the+ * panel toggles — the open-state flip should be one-shot per cap+ * transition.+ */+ const lastCapabilityNeedsConfigRef = useRef(capabilityNeedsConfig);+ useEffect(() => {+ const prev = lastCapabilityNeedsConfigRef.current;+ lastCapabilityNeedsConfigRef.current = capabilityNeedsConfig;+ if (!prev && capabilityNeedsConfig) {+ ensureActivityPanelOpen();+ }+ }, [capabilityNeedsConfig, ensureActivityPanelOpen]);+ const selectedTools = useMemo(+ () => new Set(state.enabledTools),+ [state.enabledTools],+ );+ const hasMessages = state.messages.length > 0;+ const { ref: composerRef, height: composerHeight } =+ useMeasuredHeight<HTMLDivElement>();+ const visibleTools = useMemo(+ () => ALL_TOOLS.filter((t) => activeCap.allowedTools.includes(t.name)),+ [activeCap.allowedTools],+ );+ const researchValidation = useMemo(+ () => validateResearchConfig(researchConfig),+ [researchConfig],+ );+ const notebookReferenceGroups = useMemo(() => {+ const groups = new Map<string, { notebookName: string; count: number }>();+ selectedNotebookRecords.forEach((record) => {+ const existing = groups.get(record.notebookId);+ if (existing) {+ existing.count += 1;+ } else {+ groups.set(record.notebookId, {+ notebookName: record.notebookName,+ count: 1,+ });+ }+ });+ return Array.from(groups.entries()).map(([notebookId, value]) => ({+ notebookId,+ ...value,+ }));+ }, [selectedNotebookRecords]);+ const notebookReferencesPayload = useMemo(() => {+ const grouped = new Map<string, string[]>();+ selectedNotebookRecords.forEach((record) => {+ const current = grouped.get(record.notebookId) || [];+ current.push(record.id);+ grouped.set(record.notebookId, current);+ });+ return Array.from(grouped.entries()).map(([notebook_id, record_ids]) => ({+ notebook_id,+ record_ids,+ }));+ }, [selectedNotebookRecords]);+ const bookReferencesPayload = useMemo(+ () => selectedBooksToPayload(selectedBookReferences),+ [selectedBookReferences],+ );+ const historyReferencesPayload = useMemo(+ () => selectedHistorySessions.map((session) => session.sessionId),+ [selectedHistorySessions],+ );+ const questionNotebookReferencesPayload = useMemo(+ () => selectedQuestionEntries.map((entry) => entry.id),+ [selectedQuestionEntries],+ );+ const memoryReferencesPayload = useMemo(+ () => [...selectedMemoryFiles],+ [selectedMemoryFiles],+ );+ const chatSaveMessages = useMemo(+ () =>+ state.messages.map((msg) => ({+ role: msg.role,+ content: msg.content,+ capability: msg.capability,+ })),+ [state.messages],+ );+ const chatSavePayload = useMemo(() => {+ if (!state.messages.length) return null;+ const title =+ state.messages+ .find((msg) => msg.role === "user")+ ?.content.trim()+ .slice(0, 80) || "Chat Session";+ return {+ recordType: "chat" as const,+ title,+ // The actual transcript / userQuery are rebuilt inside SaveToNotebookModal+ // from the user's selected subset of messages. We still provide a+ // sensible fallback for non-selection callers.+ userQuery: "",+ output: "",+ metadata: {+ source: "chat",+ capability: state.activeCapability || "chat",+ ui_language: state.language,+ session_id: state.sessionId,+ total_message_count: state.messages.length,+ },+ };+ }, [state.activeCapability, state.language, state.messages, state.sessionId]);+ const lastMessage = state.messages[state.messages.length - 1];+ const {+ containerRef: messagesContainerRef,+ endRef: messagesEndRef,+ shouldAutoScrollRef,+ handleScroll: handleMessagesScroll,+ } = useChatAutoScroll({+ hasMessages,+ isStreaming: state.isStreaming,+ composerHeight,+ messageCount: state.messages.length,+ lastMessageContent: lastMessage?.content,+ lastEventCount: lastMessage?.events?.length,+ });+ const copyAssistantMessage = useCallback(async (content: string) => {+ if (!content.trim()) return;+ try {+ await navigator.clipboard.writeText(content);+ } catch (error) {+ console.error("Failed to copy assistant message:", error);+ }+ }, []);+ const handleAnswerNow = useCallback(+ (+ snapshot?: MessageRequestSnapshot,+ assistantMsg?: { content: string; events?: StreamEvent[] },+ ) => {+ if (!snapshot || !state.isStreaming) return;+ const answerNowEvents = (assistantMsg?.events ?? []).map((event) => ({+ type: event.type,+ stage: event.stage,+ content: event.content,+ metadata: event.metadata ?? {},+ }));+ cancelStreamingTurn();+ // Preserve the original capability — each capability now owns its+ // own answer-now fast-path (deep_solve jumps to writing,+ // deep_question to direct quiz synthesis, math_animator to+ // code-gen + render, etc.). The backend orchestrator only falls+ // back to ``chat`` if the requested capability is missing.+ const answerNowSnapshot: MessageRequestSnapshot = {+ ...snapshot,+ language: appLanguage,+ config: {+ ...(snapshot.config || {}),+ answer_now_context: {+ original_user_message: snapshot.content,+ partial_response: assistantMsg?.content || "",+ events: answerNowEvents,+ },+ },+ };+ window.setTimeout(() => {+ sendMessage(+ answerNowSnapshot.content,+ answerNowSnapshot.attachments,+ answerNowSnapshot.config,+ answerNowSnapshot.notebookReferences,+ answerNowSnapshot.historyReferences,+ {+ displayUserMessage: false,+ persistUserMessage: false,+ requestSnapshotOverride: answerNowSnapshot,+ bookReferences: answerNowSnapshot.bookReferences,+ },+ answerNowSnapshot.questionNotebookReferences,+ answerNowSnapshot.skills,+ answerNowSnapshot.memoryReferences,+ );+ shouldAutoScrollRef.current = true;+ }, 0);+ },+ [+ appLanguage,+ cancelStreamingTurn,+ sendMessage,+ shouldAutoScrollRef,+ state.isStreaming,+ ],+ );++ /* ---- URL-driven session loading ---- */+ useEffect(() => {+ if (initialLoadRef.current) return;+ initialLoadRef.current = true;+ if (sessionIdParam) {+ void loadSession(sessionIdParam).catch(() => {+ router.replace("/chat", { scroll: false });+ });+ } else {+ newSession();+ }+ }, []); // eslint-disable-line react-hooks/exhaustive-deps++ // When URL param changes (sidebar navigation), load the corresponding session+ const prevSessionIdParam = useRef(sessionIdParam);+ useEffect(() => {+ if (sessionIdParam === prevSessionIdParam.current) return;+ prevSessionIdParam.current = sessionIdParam;+ if (sessionIdParam) {+ if (sessionIdParam === state.sessionId) return;+ void loadSession(sessionIdParam).catch(() => {+ router.replace("/chat", { scroll: false });+ });+ } else {+ newSession();+ }+ }, [sessionIdParam, loadSession, newSession, router, state.sessionId]);++ // When a new session_id is assigned by the server, update the URL+ useEffect(() => {+ if (state.sessionId && !sessionIdParam) {+ router.replace(`/chat/${state.sessionId}`, { scroll: false });+ }+ }, [state.sessionId, sessionIdParam, router]);++ useEffect(() => {+ setActiveSessionId(state.sessionId || sessionIdParam || null);+ }, [state.sessionId, sessionIdParam, setActiveSessionId]);++ const refreshKnowledgeBases = useCallback(+ async (options?: { force?: boolean }) => {+ try {+ const list = await listKnowledgeBases({ force: options?.force });+ setKnowledgeBases(list);+ } catch {+ setKnowledgeBases([]);+ }+ },+ [],+ );++ /* Load KBs */+ useEffect(() => {+ void refreshKnowledgeBases({ force: true });+ }, [refreshKnowledgeBases]);++ const refreshLLMOptions = useCallback(async () => {+ setLLMOptionsLoading(true);+ try {+ const payload = await listLLMOptions();+ setLLMOptions(payload.options);+ setActiveLLMDefault(payload.active);+ setLLMOptionsError(false);+ } catch {+ setLLMOptionsError(true);+ setLLMOptions([]);+ setActiveLLMDefault(null);+ } finally {+ setLLMOptionsLoading(false);+ }+ }, []);++ useEffect(() => {+ void refreshLLMOptions();+ }, [refreshLLMOptions]);++ useEffect(() => {+ if (state.llmSelection || !activeLLMDefault) return;+ setLLMSelection(activeLLMDefault);+ }, [activeLLMDefault, setLLMSelection, state.llmSelection]);++ useEffect(() => {+ if (typeof window === "undefined") return;+ const refresh = () => {+ void refreshKnowledgeBases({ force: true });+ void refreshLLMOptions();+ };+ const refreshWhenVisible = () => {+ if (document.visibilityState === "visible") refresh();+ };+ window.addEventListener("focus", refresh);+ window.addEventListener("pageshow", refresh);+ document.addEventListener("visibilitychange", refreshWhenVisible);+ return () => {+ window.removeEventListener("focus", refresh);+ window.removeEventListener("pageshow", refresh);+ document.removeEventListener("visibilitychange", refreshWhenVisible);+ };+ }, [refreshKnowledgeBases, refreshLLMOptions]);++ useEffect(() => {+ setCapabilityConfigs(loadCapabilityPlaygroundConfigs());+ }, []);++ /* URL query params (capability, tool) */+ useEffect(() => {+ if (typeof window === "undefined") return;+ const p = new URLSearchParams(window.location.search);+ const qc = p.get("capability");+ const qt = p.getAll("tool");+ if (qc !== null) handleSelectCapability(qc || "");+ else if (qt.length) {+ const valid = qt.filter((t): t is ToolName =>+ ALL_TOOLS.some((d) => d.name === t),+ );+ if (valid.length) setTools(Array.from(new Set(valid)));+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ useEffect(() => {+ const handler = (e: MouseEvent) => {+ const t = e.target as Node;+ if (+ capMenuRef.current &&+ !capMenuRef.current.contains(t) &&+ capBtnRef.current &&+ !capBtnRef.current.contains(t)+ )+ setCapMenuOpen(false);+ if (+ toolMenuRef.current &&+ !toolMenuRef.current.contains(t) &&+ toolBtnRef.current &&+ !toolBtnRef.current.contains(t)+ )+ setToolMenuOpen(false);+ if (+ spaceMenuRef.current &&+ !spaceMenuRef.current.contains(t) &&+ spaceBtnRef.current &&+ !spaceBtnRef.current.contains(t)+ )+ setSpaceMenuOpen(false);+ if (+ kbMenuRef.current &&+ !kbMenuRef.current.contains(t) &&+ kbBtnRef.current &&+ !kbBtnRef.current.contains(t)+ )+ setKbMenuOpen(false);+ };+ document.addEventListener("mousedown", handler);+ return () => document.removeEventListener("mousedown", handler);+ }, []);++ useEffect(() => {+ const allowed = new Set(visibleTools.map((tool) => tool.name));+ const nextTools = state.enabledTools.filter((tool) =>+ allowed.has(tool as ToolName),+ );+ if (nextTools.length !== state.enabledTools.length) setTools(nextTools);+ }, [setTools, state.enabledTools, visibleTools]);++ /* ---- handlers ---- */++ const handleSelectCapability = useCallback(+ (value: string) => {+ const cap =+ CAPABILITIES.find((c) => c.value === value) ?? CAPABILITIES[0];+ const storageKey = cap.value || "chat";+ const config = resolveCapabilityPlaygroundConfig(+ capabilityConfigs,+ storageKey,+ cap.allowedTools,+ );+ setCapability(cap.value || null);+ setTools(+ config.enabledTools.length > 0 || capabilityConfigs[storageKey]+ ? [...config.enabledTools]+ : [...cap.defaultTools],+ );+ if (config.knowledgeBase) setKBs([config.knowledgeBase]);+ // Switching capability invalidates any prior config confirmation —+ // the new capability has its own form that needs explicit confirm.+ setCapabilityConfigConfirmed(false);+ setCapMenuOpen(false);+ },+ [capabilityConfigs, setCapability, setKBs, setTools],+ );++ const toggleTool = useCallback(+ (tool: string) => {+ if (!activeCap.allowedTools.includes(tool as ToolName)) return;+ if (selectedTools.has(tool)) {+ setTools(state.enabledTools.filter((t) => t !== tool));+ } else {+ setTools([...state.enabledTools, tool]);+ }+ },+ [activeCap.allowedTools, selectedTools, setTools, state.enabledTools],+ );++ const toggleResearchSource = useCallback((source: ResearchSource) => {+ setResearchConfig((current) => ({+ ...current,+ sources: current.sources.includes(source)+ ? current.sources.filter((item) => item !== source)+ : [...current.sources, source],+ }));+ // Toggling sources is part of the Research config — invalidate the+ // confirm so the user can re-verify before sending.+ setCapabilityConfigConfirmed(false);+ }, []);++ const fileToAttachment = useCallback(+ (f: File): Promise<PendingAttachment> =>+ new Promise((resolve, reject) => {+ readFileAsDataUrl(f)+ .then((raw) => {+ // SVG: treat as file (text extraction on server, vision models+ // reject SVG) but keep the data URL so the chip can render a+ // thumbnail via a raw <img> tag.+ const svg = isSvgFilename(f.name) || f.type === "image/svg+xml";+ const isImage = !svg && f.type.startsWith("image/");+ const b64 = extractBase64FromDataUrl(raw);+ resolve({+ type: isImage ? "image" : "file",+ filename: f.name,+ base64: b64,+ previewUrl: isImage || svg ? raw : undefined,+ size: f.size,+ mimeType: f.type || undefined,+ });+ })+ .catch(reject);+ }),+ [],+ );++ const showAttachmentError = useCallback((message: string) => {+ setAttachmentError(message);+ if (attachmentErrorTimer.current) {+ clearTimeout(attachmentErrorTimer.current);+ }+ attachmentErrorTimer.current = setTimeout(() => {+ setAttachmentError(null);+ attachmentErrorTimer.current = null;+ }, 4000);+ }, []);++ const filterAndReportFiles = useCallback(+ (files: File[]): File[] => {+ let runningTotal = attachments.reduce((s, a) => s + (a.size ?? 0), 0);+ const accepted: File[] = [];+ const rejected: {+ name: string;+ reason: "unsupported" | "too_large" | "quota";+ }[] = [];+ for (const f of files) {+ const kind = classifyFile(f);+ if (!kind) {+ rejected.push({ name: f.name, reason: "unsupported" });+ continue;+ }+ if (f.size > MAX_ATTACHMENT_BYTES) {+ rejected.push({ name: f.name, reason: "too_large" });+ continue;+ }+ if (runningTotal + f.size > MAX_TOTAL_ATTACHMENT_BYTES) {+ rejected.push({ name: f.name, reason: "quota" });+ break;+ }+ runningTotal += f.size;+ accepted.push(f);+ }+ if (rejected.length) {+ const first = rejected[0];+ let msg: string;+ if (first.reason === "too_large") {+ msg = t("File too large: {{name}}", { name: first.name });+ } else if (first.reason === "quota") {+ msg = t("Too many files, skipped some");+ } else {+ msg = t("Unsupported file type: {{name}}", { name: first.name });+ }+ showAttachmentError(msg);+ }+ return accepted;+ },+ [attachments, showAttachmentError, t],+ );++ const handlePaste = useCallback(+ async (event: React.ClipboardEvent) => {+ const items = Array.from(event.clipboardData.items);+ const files = items+ .filter((item) => item.kind === "file")+ .map((item) => item.getAsFile())+ .filter((f): f is File => f !== null);+ const accepted = filterAndReportFiles(files);+ if (!accepted.length) return;+ event.preventDefault();+ const next = await Promise.all(accepted.map(fileToAttachment));+ setAttachments((prev) => [...prev, ...next]);+ },+ [fileToAttachment, filterAndReportFiles],+ );++ const removeAttachment = useCallback((index: number) => {+ setAttachments((prev) => prev.filter((_, i) => i !== index));+ }, []);++ const handlePreviewPendingAttachment = useCallback(+ (index: number) => {+ const a = attachments[index];+ if (!a) return;+ setPreviewSource({+ filename: a.filename,+ mimeType: a.mimeType,+ type: a.type,+ base64: a.base64,+ size: a.size,+ });+ },+ [attachments],+ );++ // Fold all messages once per state.messages change to power the+ // SessionActivityPanel on the right (tools, KBs, space refs, attachments).+ const sessionActivity = useMemo(+ () => buildSessionActivity(state.messages),+ [state.messages],+ );++ /**+ * Capability-config card rendered at the bottom of the Activity panel.+ *+ * Returns null for capabilities that don't need explicit configuration+ * (Chat / Solve) — the Activity panel falls back to its standard+ * sections (tools, KBs, space, attachments) plus the empty-state card.+ *+ * For Quiz / Animator / Visualize / Research, we wrap the matching bare+ * ConfigPanel in a `CapabilityConfigCard` that provides the header,+ * Confirm button, and validation-error display. The Confirm gate is+ * wired through `capabilityConfigConfirmed` / `handleConfirmCapabilityConfig`.+ */+ const capabilityConfigSection = useMemo(() => {+ if (!capabilityNeedsConfig) return null;+ if (isQuizMode) {+ return (+ <CapabilityConfigCard+ capability="deep_question"+ confirmed={capabilityConfigConfirmed}+ canConfirm+ onConfirm={handleConfirmCapabilityConfig}+ >+ <QuizConfigPanel+ value={quizConfig}+ onChange={handleChangeQuizConfig}+ uploadedPdf={quizPdf}+ onUploadPdf={handleUploadQuizPdf}+ />+ </CapabilityConfigCard>+ );+ }+ if (isMathAnimatorMode) {+ return (+ <CapabilityConfigCard+ capability="math_animator"+ confirmed={capabilityConfigConfirmed}+ canConfirm+ onConfirm={handleConfirmCapabilityConfig}+ >+ <MathAnimatorConfigPanel+ value={mathAnimatorConfig}+ onChange={handleChangeMathAnimatorConfig}+ />+ </CapabilityConfigCard>+ );+ }+ if (isVisualizeMode) {+ return (+ <CapabilityConfigCard+ capability="visualize"+ confirmed={capabilityConfigConfirmed}+ canConfirm+ onConfirm={handleConfirmCapabilityConfig}+ >+ <VisualizeConfigPanel+ value={visualizeConfig}+ onChange={handleChangeVisualizeConfig}+ />+ </CapabilityConfigCard>+ );+ }+ // Research: forward validation errors so the user sees what's missing+ // before they hit Confirm. `canConfirm` only flips false when there's+ // an actual error (e.g. mode/depth not selected).+ const researchErrorMessages = Object.values(researchValidation.errors);+ return (+ <CapabilityConfigCard+ capability="deep_research"+ confirmed={capabilityConfigConfirmed}+ canConfirm={researchErrorMessages.length === 0}+ validationErrors={researchErrorMessages}+ onConfirm={handleConfirmCapabilityConfig}+ >+ <ResearchConfigPanel+ value={researchConfig}+ errors={researchValidation.errors}+ onChange={handleChangeResearchConfig}+ />+ </CapabilityConfigCard>+ );+ }, [+ capabilityNeedsConfig,+ isQuizMode,+ isMathAnimatorMode,+ isVisualizeMode,+ capabilityConfigConfirmed,+ handleConfirmCapabilityConfig,+ quizConfig,+ quizPdf,+ handleChangeQuizConfig,+ handleUploadQuizPdf,+ mathAnimatorConfig,+ handleChangeMathAnimatorConfig,+ visualizeConfig,+ handleChangeVisualizeConfig,+ researchConfig,+ researchValidation.errors,+ handleChangeResearchConfig,+ ]);++ const viewerPanelRef = useRef<SessionViewerPanelHandle | null>(null);+ // Clicking an attachment (from the Activity panel or from a chat message)+ // routes into the Viewer panel as a new file tab. The viewer auto-opens+ // and the preference is persisted so a follow-up click feels instant.+ const handlePreviewMessageAttachment = useCallback(+ (a: MessageAttachment) => {+ viewerPanelRef.current?.openFileTab(a);+ },+ [],+ );++ // Event-delegated link interception inside the messages container. When+ // the user clicks an http(s) link in an assistant message, we open it as+ // a Viewer tab instead of letting the browser navigate / open a new tab.+ // Cmd/ctrl/shift + click keep their standard meaning (open in browser).+ const handleMessagesClick = useCallback((event: React.MouseEvent) => {+ if (event.defaultPrevented) return;+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)+ return;+ if (event.button !== 0) return;+ const target = event.target as HTMLElement | null;+ if (!target) return;+ const anchor = target.closest<HTMLAnchorElement>("a[href]");+ if (!anchor) return;+ const href = anchor.getAttribute("href");+ if (!href) return;+ if (!/^https?:\/\//i.test(href)) return;+ event.preventDefault();+ viewerPanelRef.current?.openWebTab(href);+ }, []);++ const handleClosePreview = useCallback(() => {+ setPreviewSource(null);+ }, []);++ const handleDragEnter = useCallback((e: React.DragEvent) => {+ e.preventDefault();+ e.stopPropagation();+ dragCounter.current += 1;+ if (e.dataTransfer.types.includes("Files")) setDragging(true);+ }, []);++ const handleDragLeave = useCallback((e: React.DragEvent) => {+ e.preventDefault();+ e.stopPropagation();+ dragCounter.current -= 1;+ if (dragCounter.current === 0) setDragging(false);+ }, []);++ const handleDragOver = useCallback((e: React.DragEvent) => {+ e.preventDefault();+ e.stopPropagation();+ }, []);++ const handleDrop = useCallback(+ async (e: React.DragEvent) => {+ e.preventDefault();+ e.stopPropagation();+ setDragging(false);+ dragCounter.current = 0;+ const accepted = filterAndReportFiles(Array.from(e.dataTransfer.files));+ if (!accepted.length) return;+ const next = await Promise.all(accepted.map(fileToAttachment));+ setAttachments((prev) => [...prev, ...next]);+ },+ [fileToAttachment, filterAndReportFiles],+ );++ const handleAddFiles = useCallback(+ async (files: File[]) => {+ const accepted = filterAndReportFiles(files);+ if (!accepted.length) return;+ const next = await Promise.all(accepted.map(fileToAttachment));+ setAttachments((prev) => [...prev, ...next]);+ },+ [fileToAttachment, filterAndReportFiles],+ );++ const handleSend = useCallback(+ async (content: string) => {+ if (+ (!content &&+ !attachments.length &&+ !selectedBookReferences.length &&+ !selectedNotebookRecords.length &&+ !selectedHistorySessions.length &&+ !selectedQuestionEntries.length &&+ !selectedSkills.length &&+ !skillsAutoMode &&+ !selectedMemoryFiles.length) ||+ state.isStreaming+ )+ return;++ let extraAttachments = attachments.map((a) => ({+ type: a.type,+ filename: a.filename,+ base64: a.base64,+ mime_type: a.mimeType,+ }));+ let config: Record<string, unknown> | undefined;++ if (isQuizMode) {+ config = buildQuizWSConfig(quizConfig);+ if (quizConfig.mode === "mimic" && quizPdf) {+ const b64 = extractBase64FromDataUrl(+ await readFileAsDataUrl(quizPdf),+ );+ extraAttachments = [+ ...extraAttachments,+ {+ type: "pdf",+ filename: quizPdf.name,+ base64: b64,+ mime_type: "application/pdf",+ },+ ];+ }+ }+ if (isMathAnimatorMode)+ config = buildMathAnimatorWSConfig(mathAnimatorConfig);+ if (isVisualizeMode) config = buildVisualizeWSConfig(visualizeConfig);+ if (isResearchMode) config = buildResearchWSConfig(researchConfig);++ const skillsPayload = skillsAutoMode ? ["auto"] : [...selectedSkills];+ const memoryPayload = [...memoryReferencesPayload];+ const messageContent =+ content ||+ (selectedNotebookRecords.length ||+ selectedBookReferences.length ||+ selectedHistorySessions.length ||+ selectedQuestionEntries.length ||+ skillsPayload.length ||+ memoryPayload.length+ ? t("Please use the selected context to help with this request.")+ : "") ||+ (isMathAnimatorMode+ ? attachments.some((a) => a.type === "image")+ ? t(+ "Generate a math animation from the attached reference image(s).",+ )+ : ""+ : attachments.some((a) => a.type === "image")+ ? t("Please analyze the attached image(s).")+ : "");+ sendMessage(+ messageContent,+ extraAttachments,+ config,+ notebookReferencesPayload,+ historyReferencesPayload,+ { bookReferences: bookReferencesPayload },+ questionNotebookReferencesPayload,+ skillsPayload,+ memoryPayload,+ );+ shouldAutoScrollRef.current = true;+ setAttachments([]);+ setSelectedBookReferences([]);+ setSelectedNotebookRecords([]);+ setSelectedHistorySessions([]);+ setSelectedQuestionEntries([]);+ setSelectedSkills([]);+ setSkillsAutoMode(false);+ setSelectedMemoryFiles([]);+ },+ [+ attachments,+ bookReferencesPayload,+ historyReferencesPayload,+ isMathAnimatorMode,+ isQuizMode,+ isResearchMode,+ isVisualizeMode,+ mathAnimatorConfig,+ memoryReferencesPayload,+ notebookReferencesPayload,+ questionNotebookReferencesPayload,+ quizConfig,+ quizPdf,+ researchConfig,+ selectedHistorySessions.length,+ selectedMemoryFiles.length,+ selectedBookReferences.length,+ selectedNotebookRecords.length,+ selectedQuestionEntries.length,+ selectedSkills,+ skillsAutoMode,+ sendMessage,+ shouldAutoScrollRef,+ state.isStreaming,+ t,+ visualizeConfig,+ ],+ );++ const handleConfirmOutline = useCallback(+ (+ outline: OutlineItem[],+ _topic: string,+ originalConfig?: Record<string, unknown> | null,+ ) => {+ const config: Record<string, unknown> = {+ ...(originalConfig ?? {+ mode: researchConfig.mode,+ depth: researchConfig.depth,+ sources: [...researchConfig.sources],+ }),+ confirmed_outline: outline,+ };+ sendMessage(_topic, [], config, undefined, undefined, {+ displayUserMessage: false,+ persistUserMessage: false,+ });+ shouldAutoScrollRef.current = true;+ },+ [researchConfig, sendMessage, shouldAutoScrollRef],+ );++ const handleRegenerateMessage = useCallback(() => {+ regenerateLastMessage();+ }, [regenerateLastMessage]);++ const handleToggleKB = useCallback(+ (name: string) => {+ const current = state.knowledgeBases;+ setKBs(+ current.includes(name)+ ? current.filter((kb) => kb !== name)+ : [...current, name],+ );+ },+ [setKBs, state.knowledgeBases],+ );+ const handleSelectNotebookPicker = useCallback(() => {+ setShowNotebookPicker(true);+ }, []);+ const handleSelectBookPicker = useCallback(() => {+ setShowBookPicker(true);+ }, []);+ const handleSelectHistoryPicker = useCallback(() => {+ setShowHistoryPicker(true);+ }, []);+ const handleSelectQuestionBankPicker = useCallback(() => {+ setShowQuestionBankPicker(true);+ }, []);+ const handleSelectSkillsPicker = useCallback(() => {+ setShowSkillsPicker(true);+ }, []);+ const handleSelectMemoryPicker = useCallback(() => {+ setShowMemoryPicker(true);+ }, []);+ const handleRemoveHistory = useCallback((sessionId: string) => {+ setSelectedHistorySessions((prev) =>+ prev.filter((item) => item.sessionId !== sessionId),+ );+ }, []);+ const handleRemoveNotebook = useCallback((notebookId: string) => {+ setSelectedNotebookRecords((prev) =>+ prev.filter((record) => record.notebookId !== notebookId),+ );+ }, []);+ const handleRemoveBookReference = useCallback((bookId: string) => {+ setSelectedBookReferences((prev) =>+ prev.filter((record) => record.bookId !== bookId),+ );+ }, []);+ const handleRemoveQuestion = useCallback((entryId: number) => {+ setSelectedQuestionEntries((prev) =>+ prev.filter((entry) => entry.id !== entryId),+ );+ }, []);+ const handleToggleSkill = useCallback((name: string) => {+ setSkillsAutoMode(false);+ setSelectedSkills((prev) =>+ prev.includes(name) ? prev.filter((n) => n !== name) : [...prev, name],+ );+ }, []);++ const handleSetSkillsAuto = useCallback((auto: boolean) => {+ setSkillsAutoMode(auto);+ if (auto) setSelectedSkills([]);+ }, []);++ const handleToggleMemoryFile = useCallback((file: SpaceMemoryFile) => {+ setSelectedMemoryFiles((prev) =>+ prev.includes(file)+ ? prev.filter((item) => item !== file)+ : [...prev, file],+ );+ }, []);++ const handleCloseNotebookPicker = useCallback(() => {+ setShowNotebookPicker(false);+ }, []);+ const handleCloseBookPicker = useCallback(() => {+ setShowBookPicker(false);+ }, []);+ const handleApplyBookReferences = useCallback(+ (references: SelectedBookReference[]) => {+ setSelectedBookReferences(references);+ },+ [],+ );+ const handleApplyNotebookRecords = useCallback(+ (records: SelectedRecord[]) => {+ setSelectedNotebookRecords(records);+ },+ [],+ );+ const handleCloseHistoryPicker = useCallback(() => {+ setShowHistoryPicker(false);+ }, []);+ const handleApplyHistorySessions = useCallback(+ (sessions: SelectedHistorySession[]) => {+ setSelectedHistorySessions(sessions);+ },+ [],+ );+ const handleCloseQuestionBankPicker = useCallback(() => {+ setShowQuestionBankPicker(false);+ }, []);+ const handleApplyQuestionEntries = useCallback(+ (entries: SelectedQuestionEntry[]) => {+ setSelectedQuestionEntries(entries);+ },+ [],+ );+ const handleCloseSkillsPicker = useCallback(() => {+ setShowSkillsPicker(false);+ }, []);+ const handleApplySkillsSelection = useCallback(+ (selection: { auto: boolean; skills: string[] }) => {+ setSkillsAutoMode(selection.auto);+ setSelectedSkills(selection.auto ? [] : selection.skills);+ },+ [],+ );+ const handleCloseMemoryPicker = useCallback(() => {+ setShowMemoryPicker(false);+ }, []);+ const handleApplyMemoryFiles = useCallback((files: SpaceMemoryFile[]) => {+ setSelectedMemoryFiles(files);+ }, []);+ const handleCloseSaveModal = useCallback(() => {+ setShowSaveModal(false);+ }, []);++ const handleNewChat = useCallback(() => {+ router.push("/chat");+ }, [router]);++ const handleDownloadMarkdown = useCallback(() => {+ if (!state.messages.length) return;+ const title =+ state.messages+ .find((msg) => msg.role === "user")+ ?.content.trim()+ .slice(0, 80) || "Chat Session";+ downloadChatMarkdown(state.messages, { title });+ }, [state.messages]);++ return (+ <div+ // When the preview drawer is open AND the viewport is wide enough,+ // push the chat content to the left by the drawer's width so the two+ // panels live side-by-side (matches Claude desktop). On smaller+ // screens the drawer overlays — squeezing a phone-width chat into+ // the remaining ~30 px would be useless. The actual padding ++ // transition lives in `chat-preview-shell` (globals.css) so we can+ // hand-tune it without fighting Tailwind's arbitrary-value parser.+ data-preview-open={previewSource ? "true" : "false"}+ data-activity-open={activityPanelOpen ? "true" : "false"}+ data-viewer-open={viewerPanelOpen ? "true" : "false"}+ className="chat-preview-shell flex h-full flex-col overflow-hidden bg-[var(--background)]"+ >+ <div+ ref={headerRef}+ className="mx-auto flex w-full max-w-[960px] flex-wrap items-center justify-between gap-x-3 gap-y-1.5 px-6 pt-3 pb-0"+ >+ <span className="min-w-0 flex-1 truncate text-[15px] font-semibold tracking-[-0.01em] text-[var(--foreground)]">+ {t(activeCap.label)}+ </span>+ <div className="flex shrink-0 flex-wrap items-center gap-1.5">+ <HeaderActionButton+ compact={headerCompact}+ onClick={() => setShowSaveModal(true)}+ disabled={!chatSavePayload}+ icon={BookmarkPlus}+ label={t("Save to Notebook")}+ />+ <HeaderActionButton+ compact={headerCompact}+ onClick={handleDownloadMarkdown}+ disabled={!state.messages.length}+ icon={Download}+ label={t("Download Markdown")}+ title={t("Download chat history as Markdown")}+ />+ <HeaderActionButton+ compact={headerCompact}+ onClick={handleNewChat}+ icon={SquarePen}+ label={t("New chat")}+ />+ <HeaderActionButton+ compact={headerCompact}+ onClick={toggleActivityPanel}+ active={activityPanelOpen}+ icon={PanelRight}+ label={t("Activity")}+ title={t("Session activity")}+ />+ <HeaderActionButton+ compact={headerCompact}+ onClick={toggleViewerPanel}+ active={viewerPanelOpen}+ icon={BookOpen}+ label={t("Viewer")}+ title={t("Open viewer")}+ />+ </div>+ </div>+ <div className="mx-auto flex w-full max-w-[960px] flex-1 min-h-0 flex-col overflow-hidden px-6">+ {!hasMessages ? (+ <div className="flex flex-1 min-h-0 flex-col items-center justify-center animate-fade-in">+ <div className="text-center">+ <h1 className="font-serif text-[36px] font-medium tracking-[-0.01em] text-[var(--foreground)]">+ {t("What would you like to learn?")}+ </h1>+ <p className="mt-4 text-[15px] text-[var(--muted-foreground)]">+ {t("Ask anything — I'm here to help you understand.")}+ </p>+ </div>+ </div>+ ) : (+ <div+ ref={messagesContainerRef}+ data-chat-scroll-root="true"+ onScroll={handleMessagesScroll}+ onClick={handleMessagesClick}+ className={`mx-auto w-full flex-1 min-h-0 space-y-7 overflow-y-auto pr-4 [scrollbar-gutter:stable] ${hasMessages ? "pt-6" : "pt-2 pb-6"}`}+ style={+ hasMessages+ ? (() => {+ // The bottom 40 px of the messages area fades to+ // transparent so content "dissolves" into the composer+ // gutter. Without enough bottom padding, the fade+ // overlaps the last assistant paragraph and looks like+ // a stuck scroll — the user reaches scrollHeight but+ // can still see only a faded sliver of text. paddingBottom+ // is sized so the fade falls over empty space.+ const maskImage =+ "linear-gradient(to bottom, transparent 0px, #000 32px, #000 calc(100% - 40px), transparent 100%)";+ return {+ paddingBottom: "48px",+ WebkitMaskImage: maskImage,+ maskImage,+ };+ })()+ : undefined+ }+ >+ <ChatMessageList+ messages={state.messages}+ isStreaming={state.isStreaming}+ sessionId={state.sessionId}+ language={state.language}+ onAnswerNow={handleAnswerNow}+ onCopyAssistantMessage={copyAssistantMessage}+ onRegenerateMessage={handleRegenerateMessage}+ onConfirmOutline={handleConfirmOutline}+ onPreviewAttachment={handlePreviewMessageAttachment}+ onDeleteTurn={deleteTurn}+ selectedBranches={state.selectedBranches}+ onEditMessage={editMessage}+ onSwitchBranch={switchBranch}+ />+ <div ref={messagesEndRef} className="h-px w-full shrink-0" />+ </div>+ )}++ <ChatComposer+ composerRef={composerRef}+ capMenuRef={capMenuRef}+ capBtnRef={capBtnRef}+ toolMenuRef={toolMenuRef}+ toolBtnRef={toolBtnRef}+ spaceMenuRef={spaceMenuRef}+ spaceBtnRef={spaceBtnRef}+ kbMenuRef={kbMenuRef}+ kbBtnRef={kbBtnRef}+ dragCounter={dragCounter}+ dragging={dragging}+ capMenuOpen={capMenuOpen}+ toolMenuOpen={toolMenuOpen}+ spaceMenuOpen={spaceMenuOpen}+ kbMenuOpen={kbMenuOpen}+ hasMessages={hasMessages}+ attachments={attachments}+ attachmentError={attachmentError}+ activeCap={activeCap}+ visibleTools={visibleTools}+ selectedTools={selectedTools}+ knowledgeBases={knowledgeBases}+ llmOptions={llmOptions}+ activeLLMDefault={activeLLMDefault}+ llmSelection={state.llmSelection}+ llmOptionsLoading={llmOptionsLoading}+ llmOptionsError={llmOptionsError}+ selectedBookReferences={selectedBookReferences}+ selectedNotebookRecords={selectedNotebookRecords}+ selectedHistorySessions={selectedHistorySessions}+ selectedQuestionEntries={selectedQuestionEntries}+ notebookReferenceGroups={notebookReferenceGroups}+ selectedSkills={selectedSkills}+ skillsAutoMode={skillsAutoMode}+ selectedMemoryFiles={selectedMemoryFiles}+ selectedKnowledgeBases={state.knowledgeBases}+ isStreaming={state.isStreaming}+ isResearchMode={isResearchMode}+ isMathAnimatorMode={isMathAnimatorMode}+ isVisualizeMode={isVisualizeMode}+ isAutoMode={false}+ autoEnabledCaps={EMPTY_SET}+ researchConfigSources={researchConfig.sources}+ capabilityNeedsConfig={capabilityNeedsConfig}+ capabilityConfigConfirmed={capabilityConfigConfirmed}+ onRequestConfigConfirm={ensureActivityPanelOpen}+ capabilities={CAPABILITIES}+ researchSources={RESEARCH_SOURCES}+ onSetCapMenuOpen={setCapMenuOpen}+ onSetToolMenuOpen={setToolMenuOpen}+ onSetSpaceMenuOpen={setSpaceMenuOpen}+ onSetKbMenuOpen={setKbMenuOpen}+ onToggleAutoCap={noopToggleAutoCap}+ onToggleKB={handleToggleKB}+ onSelectLLM={setLLMSelection}+ onSelectNotebookPicker={handleSelectNotebookPicker}+ onSelectBookPicker={handleSelectBookPicker}+ onSelectHistoryPicker={handleSelectHistoryPicker}+ onSelectQuestionBankPicker={handleSelectQuestionBankPicker}+ onSelectSkillsPicker={handleSelectSkillsPicker}+ onSelectMemoryPicker={handleSelectMemoryPicker}+ onToggleTool={toggleTool}+ onToggleSkill={handleToggleSkill}+ onSetSkillsAuto={handleSetSkillsAuto}+ onToggleMemoryFile={handleToggleMemoryFile}+ onToggleResearchSource={toggleResearchSource}+ onSend={handleSend}+ onRemoveAttachment={removeAttachment}+ onPreviewAttachment={handlePreviewPendingAttachment}+ onRemoveHistory={handleRemoveHistory}+ onRemoveBookReference={handleRemoveBookReference}+ onRemoveNotebook={handleRemoveNotebook}+ onRemoveQuestion={handleRemoveQuestion}+ onDragEnter={handleDragEnter}+ onDragLeave={handleDragLeave}+ onDragOver={handleDragOver}+ onDrop={handleDrop}+ onPaste={handlePaste}+ onAddFiles={handleAddFiles}+ onSelectCapability={handleSelectCapability}+ onCancelStreaming={cancelStreamingTurn}+ />+ </div>+ <NotebookRecordPicker+ open={showNotebookPicker}+ onClose={handleCloseNotebookPicker}+ onApply={handleApplyNotebookRecords}+ />+ <BookReferencePicker+ open={showBookPicker}+ initialReferences={selectedBookReferences}+ onClose={handleCloseBookPicker}+ onApply={handleApplyBookReferences}+ />+ <HistorySessionPicker+ open={showHistoryPicker}+ onClose={handleCloseHistoryPicker}+ onApply={handleApplyHistorySessions}+ />+ <QuestionBankPicker+ open={showQuestionBankPicker}+ onClose={handleCloseQuestionBankPicker}+ onApply={handleApplyQuestionEntries}+ />+ <SkillsPicker+ open={showSkillsPicker}+ initialAuto={skillsAutoMode}+ initialSkills={selectedSkills}+ onClose={handleCloseSkillsPicker}+ onApply={handleApplySkillsSelection}+ />+ <MemoryPicker+ open={showMemoryPicker}+ initialFiles={selectedMemoryFiles}+ onClose={handleCloseMemoryPicker}+ onApply={handleApplyMemoryFiles}+ />+ <SaveToNotebookModal+ open={showSaveModal}+ payload={chatSavePayload}+ messages={chatSaveMessages}+ onClose={handleCloseSaveModal}+ />+ <FilePreviewDrawer+ open={previewSource !== null}+ source={previewSource}+ onClose={handleClosePreview}+ />+ <SessionActivityPanel+ open={activityPanelOpen && previewSource === null && !viewerPanelOpen}+ activity={sessionActivity}+ onOpenAttachment={handlePreviewMessageAttachment}+ configSection={capabilityConfigSection}+ />+ <SessionViewerPanel+ ref={viewerPanelRef}+ open={viewerPanelOpen && previewSource === null}+ sessionId={state.sessionId}+ onClose={() => setViewerOpen(false)}+ onAutoOpen={() => setViewerOpen(true)}+ />+ </div>+ );+}++/**+ * Header action button that auto-collapses to icon-only when the chat+ * column gets squeezed (Viewer panel open, narrow viewport, etc.). The+ * label stays as the button's `title` so hovering an icon still reveals+ * what it does. Optional `active` flag paints the button with a primary+ * tint, used by the panel-toggle buttons to surface their on/off state.+ */+function HeaderActionButton({+ compact,+ onClick,+ disabled,+ active,+ icon: Icon,+ label,+ title,+}: {+ compact: boolean;+ onClick: () => void;+ disabled?: boolean;+ active?: boolean;+ icon: LucideIcon;+ label: string;+ title?: string;+}) {+ return (+ <button+ onClick={onClick}+ disabled={disabled}+ title={title ?? label}+ aria-label={label}+ aria-pressed={active}+ className={`inline-flex shrink-0 items-center gap-1.5 rounded-lg border text-[12px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-40 ${+ compact ? "px-2 py-1.5" : "px-3 py-1.5"+ } ${+ active+ ? "border-[var(--primary)]/40 bg-[color-mix(in_srgb,var(--primary)_8%,var(--card))] text-[var(--primary)] hover:border-[var(--primary)]/55"+ : "border-[var(--border)]/50 text-[var(--muted-foreground)] hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:hover:border-[var(--border)]/50 disabled:hover:text-[var(--muted-foreground)]"+ }`}+ >+ <Icon size={14} strokeWidth={1.7} className="shrink-0" />+ {compact ? null : <span>{label}</span>}+ </button>+ );+}++"use client";++++import dynamic from "next/dynamic";++import { useCallback, useEffect, useMemo, useRef, useState } from "react";++import { useParams, useRouter } from "next/navigation";++++import {++ BarChart3,++ BrainCircuit,++ Clapperboard,++ Code2,++ Database,++ FileSearch,++ Globe,++ Lightbulb,++ MessageSquare,++ Microscope,++ PenLine,++ Sparkles,++ type LucideIcon,++} from "lucide-react";++import { useTranslation } from "react-i18next";++import type { SelectedRecord } from "@/lib/notebook-selection-types";++import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";++import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";++import ChatComposer from "@/components/chat/home/ChatComposer";++import { ChatMessageList } from "@/components/chat/home/ChatMessages";++// Imported eagerly so the drawer shell is always mounted off-screen —++// clicking a chip becomes a single CSS class flip, no chunk fetch + double++// render. The heavy renderers inside still load lazily.++import FilePreviewDrawer from "@/components/chat/preview/FilePreviewDrawer";++import {++ useUnifiedChat,++ type MessageAttachment,++ type MessageRequestSnapshot,++} from "@/context/UnifiedChatContext";++import { useAppShell } from "@/context/AppShellContext";++import type { FilePreviewSource } from "@/components/chat/preview/previewerFor";++import type { LLMSelection, StreamEvent } from "@/lib/unified-ws";++import {++ extractBase64FromDataUrl,++ readFileAsDataUrl,++} from "@/lib/file-attachments";++import {++ classifyFile,++ isSvgFilename,++ MAX_ATTACHMENT_BYTES,++ MAX_TOTAL_ATTACHMENT_BYTES,++} from "@/lib/doc-attachments";++import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";++import { useMeasuredHeight } from "@/hooks/useMeasuredHeight";++import {++ loadCapabilityPlaygroundConfigs,++ resolveCapabilityPlaygroundConfig,++ type CapabilityPlaygroundConfigMap,++} from "@/lib/playground-config";++import {++ DEFAULT_QUIZ_CONFIG,++ buildQuizWSConfig,++ type DeepQuestionFormConfig,++} from "@/lib/quiz-types";++import {++ DEFAULT_MATH_ANIMATOR_CONFIG,++ buildMathAnimatorWSConfig,++ type MathAnimatorFormConfig,++} from "@/lib/math-animator-types";++import {++ DEFAULT_VISUALIZE_CONFIG,++ buildVisualizeWSConfig,++ type VisualizeFormConfig,++} from "@/lib/visualize-types";++import {++ buildResearchWSConfig,++ createEmptyResearchConfig,++ validateResearchConfig,++ type DeepResearchFormConfig,++ type OutlineItem,++ type ResearchSource,++} from "@/lib/research-types";++import { listKnowledgeBases } from "@/lib/knowledge-api";++import { listLLMOptions, type LLMOption } from "@/lib/llm-options";++import { downloadChatMarkdown } from "@/lib/chat-export";++import type { SpaceMemoryFile } from "@/lib/space-items";++import {++ selectedBooksToPayload,++ type SelectedBookReference,++} from "@/lib/book-references";++++const NotebookRecordPicker = dynamic(++ () => import("@/components/notebook/NotebookRecordPicker"),++ {++ ssr: false,++ },++);++const HistorySessionPicker = dynamic(++ () => import("@/components/chat/HistorySessionPicker"),++ {++ ssr: false,++ },++);++const QuestionBankPicker = dynamic(++ () => import("@/components/chat/QuestionBankPicker"),++ {++ ssr: false,++ },++);++const SkillsPicker = dynamic(() => import("@/components/chat/SkillsPicker"), {++ ssr: false,++});++const MemoryPicker = dynamic(() => import("@/components/chat/MemoryPicker"), {++ ssr: false,++});++const BookReferencePicker = dynamic(++ () => import("@/components/chat/BookReferencePicker"),++ {++ ssr: false,++ },++);++const SaveToNotebookModal = dynamic(++ () => import("@/components/notebook/SaveToNotebookModal"),++ {++ ssr: false,++ },++);++++/* ------------------------------------------------------------------ */++/* Type & data definitions */++/* ------------------------------------------------------------------ */++++type ToolName =++ | "brainstorm"++ | "rag"++ | "web_search"++ | "code_execution"++ | "reason"++ | "paper_search";++++interface ToolDef {++ name: ToolName;++ label: string;++ icon: LucideIcon;++}++++interface ResearchSourceDef {++ name: ResearchSource;++ label: string;++ icon: LucideIcon;++}++++const ALL_TOOLS: ToolDef[] = [++ { name: "brainstorm", label: "Brainstorm", icon: Lightbulb },++ { name: "rag", label: "RAG", icon: Database },++ { name: "web_search", label: "Web Search", icon: Globe },++ { name: "code_execution", label: "Code", icon: Code2 },++ { name: "reason", label: "Reason", icon: Sparkles },++ { name: "paper_search", label: "Arxiv Search", icon: FileSearch },++];++++const RESEARCH_SOURCES: ResearchSourceDef[] = [++ { name: "kb", label: "Knowledge Base", icon: Database },++ { name: "web", label: "Web", icon: Globe },++ { name: "papers", label: "Papers", icon: FileSearch },++];++++interface CapabilityDef {++ value: string;++ label: string;++ description: string;++ icon: LucideIcon;++ allowedTools: ToolName[];++ defaultTools: ToolName[];++}++++const CAPABILITIES: CapabilityDef[] = [++ {++ value: "",++ label: "Chat",++ description: "Flexible conversation with any tool",++ icon: MessageSquare,++ allowedTools: [++ "brainstorm",++ "rag",++ "web_search",++ "code_execution",++ "reason",++ "paper_search",++ ],++ defaultTools: [],++ },++ {++ value: "deep_solve",++ label: "Deep Solve",++ description: "Multi-step reasoning & problem solving",++ icon: BrainCircuit,++ allowedTools: ["rag", "web_search", "code_execution", "reason"],++ defaultTools: ["rag", "web_search", "code_execution", "reason"],++ },++ {++ value: "deep_question",++ label: "Quiz Generation",++ description: "Auto-validated question generation",++ icon: PenLine,++ allowedTools: ["rag", "web_search", "code_execution"],++ defaultTools: ["rag", "web_search", "code_execution"],++ },++ {++ value: "deep_research",++ label: "Deep Research",++ description: "Comprehensive multi-agent research",++ icon: Microscope,++ allowedTools: [],++ defaultTools: [],++ },++ {++ value: "math_animator",++ label: "Math Animator",++ description: "Generate math videos or storyboard images",++ icon: Clapperboard,++ allowedTools: [],++ defaultTools: [],++ },++ {++ value: "visualize",++ label: "Visualize",++ description: "Generate SVG, Chart.js, or Mermaid visualizations",++ icon: BarChart3,++ allowedTools: [],++ defaultTools: [],++ },++];++++interface KnowledgeBase {++ name: string;++ is_default?: boolean;++}++++interface PendingAttachment {++ type: string;++ filename: string;++ base64?: string;++ previewUrl?: string;++ size?: number;++ mimeType?: string;++}++++/* ------------------------------------------------------------------ */++/* Helpers */++/* ------------------------------------------------------------------ */++++function getCapability(value: string | null): CapabilityDef {++ return CAPABILITIES.find((c) => c.value === (value || "")) ?? CAPABILITIES[0];++}++++/* ------------------------------------------------------------------ */++/* Chat page */++/* ------------------------------------------------------------------ */++++export default function ChatPage() {++ const params = useParams<{ sessionId?: string[] }>();++ const router = useRouter();++ const { t } = useTranslation();++ const sessionIdParam = params.sessionId?.[0] ?? null;++ const { setActiveSessionId, language: appLanguage } = useAppShell();++++ const {++ state,++ setTools,++ setCapability,++ setKBs,++ setLLMSelection,++ sendMessage,++ cancelStreamingTurn,++ regenerateLastMessage,++ newSession,++ loadSession,++ } = useUnifiedChat();++++ const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);++ const [llmOptions, setLLMOptions] = useState<LLMOption[]>([]);++ const [activeLLMDefault, setActiveLLMDefault] = useState<LLMSelection | null>(++ null,++ );++ const [llmOptionsLoading, setLLMOptionsLoading] = useState(true);++ const [llmOptionsError, setLLMOptionsError] = useState(false);++ const [capabilityConfigs, setCapabilityConfigs] =++ useState<CapabilityPlaygroundConfigMap>({});++ const [attachments, setAttachments] = useState<PendingAttachment[]>([]);++ const [dragging, setDragging] = useState(false);++ const [attachmentError, setAttachmentError] = useState<string | null>(null);++ const [previewSource, setPreviewSource] = useState<FilePreviewSource | null>(++ null,++ );++ const attachmentErrorTimer = useRef<ReturnType<typeof setTimeout> | null>(++ null,++ );++ const [capMenuOpen, setCapMenuOpen] = useState(false);++ const [quizConfig, setQuizConfig] = useState<DeepQuestionFormConfig>({++ ...DEFAULT_QUIZ_CONFIG,++ });++ const [quizPdf, setQuizPdf] = useState<File | null>(null);++ const [mathAnimatorConfig, setMathAnimatorConfig] =++ useState<MathAnimatorFormConfig>({++ ...DEFAULT_MATH_ANIMATOR_CONFIG,++ });++ const [visualizeConfig, setVisualizeConfig] = useState<VisualizeFormConfig>({++ ...DEFAULT_VISUALIZE_CONFIG,++ });++ const [researchConfig, setResearchConfig] = useState<DeepResearchFormConfig>(++ createEmptyResearchConfig(),++ );++ // Unified collapse state for the capability-specific config panel++ // (Quiz / Math Animator / Visualize / Deep Research). Default collapsed so++ // a fresh Chat / Deep Solve session has the shortest possible composer.++ const [panelCollapsed, setPanelCollapsed] = useState(true);++ const [showSaveModal, setShowSaveModal] = useState(false);++ const [showNotebookPicker, setShowNotebookPicker] = useState(false);++ const [showBookPicker, setShowBookPicker] = useState(false);++ const [showHistoryPicker, setShowHistoryPicker] = useState(false);++ const [showQuestionBankPicker, setShowQuestionBankPicker] = useState(false);++ const [showSkillsPicker, setShowSkillsPicker] = useState(false);++ const [showMemoryPicker, setShowMemoryPicker] = useState(false);++ const [toolMenuOpen, setToolMenuOpen] = useState(false);++ const [spaceMenuOpen, setSpaceMenuOpen] = useState(false);++ const [selectedNotebookRecords, setSelectedNotebookRecords] = useState<++ SelectedRecord[]++ >([]);++ const [selectedBookReferences, setSelectedBookReferences] = useState<++ SelectedBookReference[]++ >([]);++ const [selectedHistorySessions, setSelectedHistorySessions] = useState<++ SelectedHistorySession[]++ >([]);++ const [selectedQuestionEntries, setSelectedQuestionEntries] = useState<++ SelectedQuestionEntry[]++ >([]);++ const [selectedSkills, setSelectedSkills] = useState<string[]>([]);++ const [skillsAutoMode, setSkillsAutoMode] = useState(false);++ const [selectedMemoryFiles, setSelectedMemoryFiles] = useState<++ SpaceMemoryFile[]++ >([]);++ const dragCounter = useRef(0);++ const capMenuRef = useRef<HTMLDivElement>(null);++ const capBtnRef = useRef<HTMLButtonElement>(null);++ const toolMenuRef = useRef<HTMLDivElement>(null);++ const toolBtnRef = useRef<HTMLButtonElement>(null);++ const spaceMenuRef = useRef<HTMLDivElement>(null);++ const spaceBtnRef = useRef<HTMLButtonElement>(null);++ const initialLoadRef = useRef(false);++++ const activeCap = useMemo(++ () => getCapability(state.activeCapability),++ [state.activeCapability],++ );++ const isQuizMode = activeCap.value === "deep_question";++ const isMathAnimatorMode = activeCap.value === "math_animator";++ const isVisualizeMode = activeCap.value === "visualize";++ const isResearchMode = activeCap.value === "deep_research";++ const selectedTools = useMemo(++ () => new Set(state.enabledTools),++ [state.enabledTools],++ );++ const ragActive = isResearchMode++ ? researchConfig.sources.includes("kb")++ : selectedTools.has("rag");++ const hasMessages = state.messages.length > 0;++ const { ref: composerRef, height: composerHeight } =++ useMeasuredHeight<HTMLDivElement>();++ const visibleTools = useMemo(++ () => ALL_TOOLS.filter((t) => activeCap.allowedTools.includes(t.name)),++ [activeCap.allowedTools],++ );++ const researchValidation = useMemo(++ () => validateResearchConfig(researchConfig),++ [researchConfig],++ );++ const notebookReferenceGroups = useMemo(() => {++ const groups = new Map<string, { notebookName: string; count: number }>();++ selectedNotebookRecords.forEach((record) => {++ const existing = groups.get(record.notebookId);++ if (existing) {++ existing.count += 1;++ } else {++ groups.set(record.notebookId, {++ notebookName: record.notebookName,++ count: 1,++ });++ }++ });++ return Array.from(groups.entries()).map(([notebookId, value]) => ({++ notebookId,++ ...value,++ }));++ }, [selectedNotebookRecords]);++ const notebookReferencesPayload = useMemo(() => {++ const grouped = new Map<string, string[]>();++ selectedNotebookRecords.forEach((record) => {++ const current = grouped.get(record.notebookId) || [];++ current.push(record.id);++ grouped.set(record.notebookId, current);++ });++ return Array.from(grouped.entries()).map(([notebook_id, record_ids]) => ({++ notebook_id,++ record_ids,++ }));++ }, [selectedNotebookRecords]);++ const bookReferencesPayload = useMemo(++ () => selectedBooksToPayload(selectedBookReferences),++ [selectedBookReferences],++ );++ const historyReferencesPayload = useMemo(++ () => selectedHistorySessions.map((session) => session.sessionId),++ [selectedHistorySessions],++ );++ const questionNotebookReferencesPayload = useMemo(++ () => selectedQuestionEntries.map((entry) => entry.id),++ [selectedQuestionEntries],++ );++ const memoryReferencesPayload = useMemo(++ () => [...selectedMemoryFiles],++ [selectedMemoryFiles],++ );++ const chatSaveMessages = useMemo(++ () =>++ state.messages.map((msg) => ({++ role: msg.role,++ content: msg.content,++ capability: msg.capability,++ })),++ [state.messages],++ );++ const chatSavePayload = useMemo(() => {++ if (!state.messages.length) return null;++ const title =++ state.messages++ .find((msg) => msg.role === "user")++ ?.content.trim()++ .slice(0, 80) || "Chat Session";++ return {++ recordType: "chat" as const,++ title,++ // The actual transcript / userQuery are rebuilt inside SaveToNotebookModal++ // from the user's selected subset of messages. We still provide a++ // sensible fallback for non-selection callers.++ userQuery: "",++ output: "",++ metadata: {++ source: "chat",++ capability: state.activeCapability || "chat",++ ui_language: state.language,++ session_id: state.sessionId,++ total_message_count: state.messages.length,++ },++ };++ }, [state.activeCapability, state.language, state.messages, state.sessionId]);++ const lastMessage = state.messages[state.messages.length - 1];++ const {++ containerRef: messagesContainerRef,++ endRef: messagesEndRef,++ shouldAutoScrollRef,++ handleScroll: handleMessagesScroll,++ } = useChatAutoScroll({++ hasMessages,++ isStreaming: state.isStreaming,++ composerHeight,++ messageCount: state.messages.length,++ lastMessageContent: lastMessage?.content,++ lastEventCount: lastMessage?.events?.length,++ });++ const copyAssistantMessage = useCallback(async (content: string) => {++ if (!content.trim()) return;++ try {++ await navigator.clipboard.writeText(content);++ } catch (error) {++ console.error("Failed to copy assistant message:", error);++ }++ }, []);++ const handleAnswerNow = useCallback(++ (++ snapshot?: MessageRequestSnapshot,++ assistantMsg?: { content: string; events?: StreamEvent[] },++ ) => {++ if (!snapshot || !state.isStreaming) return;++ const answerNowEvents = (assistantMsg?.events ?? []).map((event) => ({++ type: event.type,++ stage: event.stage,++ content: event.content,++ metadata: event.metadata ?? {},++ }));++ cancelStreamingTurn();++ // Preserve the original capability — each capability now owns its++ // own answer-now fast-path (deep_solve jumps to writing,++ // deep_question to direct quiz synthesis, math_animator to++ // code-gen + render, etc.). The backend orchestrator only falls++ // back to ``chat`` if the requested capability is missing.++ const answerNowSnapshot: MessageRequestSnapshot = {++ ...snapshot,++ language: appLanguage,++ config: {++ ...(snapshot.config || {}),++ answer_now_context: {++ original_user_message: snapshot.content,++ partial_response: assistantMsg?.content || "",++ events: answerNowEvents,++ },++ },++ };++ window.setTimeout(() => {++ sendMessage(++ answerNowSnapshot.content,++ answerNowSnapshot.attachments,++ answerNowSnapshot.config,++ answerNowSnapshot.notebookReferences,++ answerNowSnapshot.historyReferences,++ {++ displayUserMessage: false,++ persistUserMessage: false,++ requestSnapshotOverride: answerNowSnapshot,++ bookReferences: answerNowSnapshot.bookReferences,++ },++ answerNowSnapshot.questionNotebookReferences,++ answerNowSnapshot.skills,++ answerNowSnapshot.memoryReferences,++ );++ shouldAutoScrollRef.current = true;++ }, 0);++ },++ [++ appLanguage,++ cancelStreamingTurn,++ sendMessage,++ shouldAutoScrollRef,++ state.isStreaming,++ ],++ );++++ /* ---- URL-driven session loading ---- */++ useEffect(() => {++ if (initialLoadRef.current) return;++ initialLoadRef.current = true;++ if (sessionIdParam) {++ void loadSession(sessionIdParam).catch(() => {++ router.replace("/chat", { scroll: false });++ });++ } else {++ newSession();++ }++ }, []); // eslint-disable-line react-hooks/exhaustive-deps++++ // When URL param changes (sidebar navigation), load the corresponding session++ const prevSessionIdParam = useRef(sessionIdParam);++ useEffect(() => {++ if (sessionIdParam === prevSessionIdParam.current) return;++ prevSessionIdParam.current = sessionIdParam;++ if (sessionIdParam) {++ if (sessionIdParam === state.sessionId) return;++ void loadSession(sessionIdParam).catch(() => {++ router.replace("/chat", { scroll: false });++ });++ } else {++ newSession();++ }++ }, [sessionIdParam, loadSession, newSession, router, state.sessionId]);++++ // When a new session_id is assigned by the server, update the URL++ useEffect(() => {++ if (state.sessionId && !sessionIdParam) {++ router.replace(`/chat/${state.sessionId}`, { scroll: false });++ }++ }, [state.sessionId, sessionIdParam, router]);++++ useEffect(() => {++ setActiveSessionId(state.sessionId || sessionIdParam || null);++ }, [state.sessionId, sessionIdParam, setActiveSessionId]);++++ const refreshKnowledgeBases = useCallback(++ async (options?: { force?: boolean }) => {++ try {++ const list = await listKnowledgeBases({ force: options?.force });++ setKnowledgeBases(list);++ if (!state.knowledgeBases.length && list.length) {++ const def = list.find((k: KnowledgeBase) => k.is_default);++ setKBs([def?.name || list[0].name]);++ }++ } catch {++ setKnowledgeBases([]);++ }++ },++ [setKBs, state.knowledgeBases.length],++ );++++ /* Load KBs */++ useEffect(() => {++ void refreshKnowledgeBases({ force: true });++ }, [refreshKnowledgeBases]);++++ const refreshLLMOptions = useCallback(async () => {++ setLLMOptionsLoading(true);++ try {++ const payload = await listLLMOptions();++ setLLMOptions(payload.options);++ setActiveLLMDefault(payload.active);++ setLLMOptionsError(false);++ } catch {++ setLLMOptionsError(true);++ setLLMOptions([]);++ setActiveLLMDefault(null);++ } finally {++ setLLMOptionsLoading(false);++ }++ }, []);++++ useEffect(() => {++ void refreshLLMOptions();++ }, [refreshLLMOptions]);++++ useEffect(() => {++ if (state.llmSelection || !activeLLMDefault) return;++ setLLMSelection(activeLLMDefault);++ }, [activeLLMDefault, setLLMSelection, state.llmSelection]);++++ useEffect(() => {++ if (typeof window === "undefined") return;++ const refresh = () => {++ void refreshKnowledgeBases({ force: true });++ void refreshLLMOptions();++ };++ const refreshWhenVisible = () => {++ if (document.visibilityState === "visible") refresh();++ };++ window.addEventListener("focus", refresh);++ window.addEventListener("pageshow", refresh);++ document.addEventListener("visibilitychange", refreshWhenVisible);++ return () => {++ window.removeEventListener("focus", refresh);++ window.removeEventListener("pageshow", refresh);++ document.removeEventListener("visibilitychange", refreshWhenVisible);++ };++ }, [refreshKnowledgeBases, refreshLLMOptions]);++++ useEffect(() => {++ setCapabilityConfigs(loadCapabilityPlaygroundConfigs());++ }, []);++++ /* URL query params (capability, tool) */++ useEffect(() => {++ if (typeof window === "undefined") return;++ const p = new URLSearchParams(window.location.search);++ const qc = p.get("capability");++ const qt = p.getAll("tool");++ if (qc !== null) handleSelectCapability(qc || "");++ else if (qt.length) {++ const valid = qt.filter((t): t is ToolName =>++ ALL_TOOLS.some((d) => d.name === t),++ );++ if (valid.length) setTools(Array.from(new Set(valid)));++ }++ // eslint-disable-next-line react-hooks/exhaustive-deps++ }, []);++++ useEffect(() => {++ const handler = (e: MouseEvent) => {++ const t = e.target as Node;++ if (++ capMenuRef.current &&++ !capMenuRef.current.contains(t) &&++ capBtnRef.current &&++ !capBtnRef.current.contains(t)++ )++ setCapMenuOpen(false);++ if (++ toolMenuRef.current &&++ !toolMenuRef.current.contains(t) &&++ toolBtnRef.current &&++ !toolBtnRef.current.contains(t)++ )++ setToolMenuOpen(false);++ if (++ spaceMenuRef.current &&++ !spaceMenuRef.current.contains(t) &&++ spaceBtnRef.current &&++ !spaceBtnRef.current.contains(t)++ )++ setSpaceMenuOpen(false);++ };++ document.addEventListener("mousedown", handler);++ return () => document.removeEventListener("mousedown", handler);++ }, []);++++ useEffect(() => {++ const allowed = new Set(visibleTools.map((tool) => tool.name));++ const nextTools = state.enabledTools.filter((tool) =>++ allowed.has(tool as ToolName),++ );++ if (nextTools.length !== state.enabledTools.length) setTools(nextTools);++ }, [setTools, state.enabledTools, visibleTools]);++++ /* ---- handlers ---- */++++ const handleSelectCapability = useCallback(++ (value: string) => {++ const cap =++ CAPABILITIES.find((c) => c.value === value) ?? CAPABILITIES[0];++ const storageKey = cap.value || "chat";++ const config = resolveCapabilityPlaygroundConfig(++ capabilityConfigs,++ storageKey,++ cap.allowedTools,++ );++ setCapability(cap.value || null);++ setTools(++ config.enabledTools.length > 0 || capabilityConfigs[storageKey]++ ? [...config.enabledTools]++ : [...cap.defaultTools],++ );++ if (config.enabledTools.includes("rag") && config.knowledgeBase)++ setKBs([config.knowledgeBase]);++ // Default-expand the per-capability settings panel right after a++ // capability switch so users immediately see the form. Sending a++ // message later will auto-collapse it (see handleSend).++ setPanelCollapsed(false);++ setCapMenuOpen(false);++ },++ [capabilityConfigs, setCapability, setKBs, setTools],++ );++++ const toggleTool = useCallback(++ (tool: string) => {++ if (!activeCap.allowedTools.includes(tool as ToolName)) return;++ if (selectedTools.has(tool)) {++ setTools(state.enabledTools.filter((t) => t !== tool));++ } else {++ setTools([...state.enabledTools, tool]);++ }++ },++ [activeCap.allowedTools, selectedTools, setTools, state.enabledTools],++ );++++ const toggleResearchSource = useCallback((source: ResearchSource) => {++ setResearchConfig((current) => ({++ ...current,++ sources: current.sources.includes(source)++ ? current.sources.filter((item) => item !== source)++ : [...current.sources, source],++ }));++ }, []);++++ const fileToAttachment = useCallback(++ (f: File): Promise<PendingAttachment> =>++ new Promise((resolve, reject) => {++ readFileAsDataUrl(f)++ .then((raw) => {++ // SVG: treat as file (text extraction on server, vision models++ // reject SVG) but keep the data URL so the chip can render a++ // thumbnail via a raw <img> tag.++ const svg = isSvgFilename(f.name) || f.type === "image/svg+xml";++ const isImage = !svg && f.type.startsWith("image/");++ const b64 = extractBase64FromDataUrl(raw);++ resolve({++ type: isImage ? "image" : "file",++ filename: f.name,++ base64: b64,++ previewUrl: isImage || svg ? raw : undefined,++ size: f.size,++ mimeType: f.type || undefined,++ });++ })++ .catch(reject);++ }),++ [],++ );++++ const showAttachmentError = useCallback((message: string) => {++ setAttachmentError(message);++ if (attachmentErrorTimer.current) {++ clearTimeout(attachmentErrorTimer.current);++ }++ attachmentErrorTimer.current = setTimeout(() => {++ setAttachmentError(null);++ attachmentErrorTimer.current = null;++ }, 4000);++ }, []);++++ const filterAndReportFiles = useCallback(++ (files: File[]): File[] => {++ let runningTotal = attachments.reduce((s, a) => s + (a.size ?? 0), 0);++ const accepted: File[] = [];++ const rejected: {++ name: string;++ reason: "unsupported" | "too_large" | "quota";++ }[] = [];++ for (const f of files) {++ const kind = classifyFile(f);++ if (!kind) {++ rejected.push({ name: f.name, reason: "unsupported" });++ continue;++ }++ if (f.size > MAX_ATTACHMENT_BYTES) {++ rejected.push({ name: f.name, reason: "too_large" });++ continue;++ }++ if (runningTotal + f.size > MAX_TOTAL_ATTACHMENT_BYTES) {++ rejected.push({ name: f.name, reason: "quota" });++ break;++ }++ runningTotal += f.size;++ accepted.push(f);++ }++ if (rejected.length) {++ const first = rejected[0];++ let msg: string;++ if (first.reason === "too_large") {++ msg = t("File too large: {{name}}", { name: first.name });++ } else if (first.reason === "quota") {++ msg = t("Too many files, skipped some");++ } else {++ msg = t("Unsupported file type: {{name}}", { name: first.name });++ }++ showAttachmentError(msg);++ }++ return accepted;++ },++ [attachments, showAttachmentError, t],++ );++++ const handlePaste = useCallback(++ async (event: React.ClipboardEvent) => {++ const items = Array.from(event.clipboardData.items);++ const files = items++ .filter((item) => item.kind === "file")++ .map((item) => item.getAsFile())++ .filter((f): f is File => f !== null);++ const accepted = filterAndReportFiles(files);++ if (!accepted.length) return;++ event.preventDefault();++ const next = await Promise.all(accepted.map(fileToAttachment));++ setAttachments((prev) => [...prev, ...next]);++ },++ [fileToAttachment, filterAndReportFiles],++ );++++ const removeAttachment = useCallback((index: number) => {++ setAttachments((prev) => prev.filter((_, i) => i !== index));++ }, []);++++ const handlePreviewPendingAttachment = useCallback(++ (index: number) => {++ const a = attachments[index];++ if (!a) return;++ setPreviewSource({++ filename: a.filename,++ mimeType: a.mimeType,++ type: a.type,++ base64: a.base64,++ size: a.size,++ });++ },++ [attachments],++ );++++ const handlePreviewMessageAttachment = useCallback((a: MessageAttachment) => {++ setPreviewSource({++ filename: a.filename || "",++ mimeType: a.mime_type,++ type: a.type,++ url: a.url,++ base64: a.base64,++ extractedText: a.extracted_text,++ id: a.id,++ });++ }, []);++++ const handleClosePreview = useCallback(() => {++ setPreviewSource(null);++ }, []);++++ const handleDragEnter = useCallback((e: React.DragEvent) => {++ e.preventDefault();++ e.stopPropagation();++ dragCounter.current += 1;++ if (e.dataTransfer.types.includes("Files")) setDragging(true);++ }, []);++++ const handleDragLeave = useCallback((e: React.DragEvent) => {++ e.preventDefault();++ e.stopPropagation();++ dragCounter.current -= 1;++ if (dragCounter.current === 0) setDragging(false);++ }, []);++++ const handleDragOver = useCallback((e: React.DragEvent) => {++ e.preventDefault();++ e.stopPropagation();++ }, []);++++ const handleDrop = useCallback(++ async (e: React.DragEvent) => {++ e.preventDefault();++ e.stopPropagation();++ setDragging(false);++ dragCounter.current = 0;++ const accepted = filterAndReportFiles(Array.from(e.dataTransfer.files));++ if (!accepted.length) return;++ const next = await Promise.all(accepted.map(fileToAttachment));++ setAttachments((prev) => [...prev, ...next]);++ },++ [fileToAttachment, filterAndReportFiles],++ );++++ const handleAddFiles = useCallback(++ async (files: File[]) => {++ const accepted = filterAndReportFiles(files);++ if (!accepted.length) return;++ const next = await Promise.all(accepted.map(fileToAttachment));++ setAttachments((prev) => [...prev, ...next]);++ },++ [fileToAttachment, filterAndReportFiles],++ );++++ const handleSend = useCallback(++ async (content: string) => {++ if (++ (!content &&++ !attachments.length &&++ !selectedBookReferences.length &&++ !selectedNotebookRecords.length &&++ !selectedHistorySessions.length &&++ !selectedQuestionEntries.length &&++ !selectedSkills.length &&++ !skillsAutoMode &&++ !selectedMemoryFiles.length) ||++ state.isStreaming++ )++ return;++++ let extraAttachments = attachments.map((a) => ({++ type: a.type,++ filename: a.filename,++ base64: a.base64,++ mime_type: a.mimeType,++ }));++ let config: Record<string, unknown> | undefined;++++ if (isQuizMode) {++ config = buildQuizWSConfig(quizConfig);++ if (quizConfig.mode === "mimic" && quizPdf) {++ const b64 = extractBase64FromDataUrl(++ await readFileAsDataUrl(quizPdf),++ );++ extraAttachments = [++ ...extraAttachments,++ {++ type: "pdf",++ filename: quizPdf.name,++ base64: b64,++ mime_type: "application/pdf",++ },++ ];++ }++ }++ if (isMathAnimatorMode)++ config = buildMathAnimatorWSConfig(mathAnimatorConfig);++ if (isVisualizeMode) config = buildVisualizeWSConfig(visualizeConfig);++ if (isResearchMode) config = buildResearchWSConfig(researchConfig);++++ const skillsPayload = skillsAutoMode ? ["auto"] : [...selectedSkills];++ const memoryPayload = [...memoryReferencesPayload];++ const messageContent =++ content ||++ (selectedNotebookRecords.length ||++ selectedBookReferences.length ||++ selectedHistorySessions.length ||++ selectedQuestionEntries.length ||++ skillsPayload.length ||++ memoryPayload.length++ ? t("Please use the selected context to help with this request.")++ : "") ||++ (isMathAnimatorMode++ ? attachments.some((a) => a.type === "image")++ ? t(++ "Generate a math animation from the attached reference image(s).",++ )++ : ""++ : attachments.some((a) => a.type === "image")++ ? t("Please analyze the attached image(s).")++ : "");++ sendMessage(++ messageContent,++ extraAttachments,++ config,++ notebookReferencesPayload,++ historyReferencesPayload,++ { bookReferences: bookReferencesPayload },++ questionNotebookReferencesPayload,++ skillsPayload,++ memoryPayload,++ );++ shouldAutoScrollRef.current = true;++ // Auto-collapse the per-capability settings panel after sending so the++ // composer stays compact during conversation.++ setPanelCollapsed(true);++ setAttachments([]);++ setSelectedBookReferences([]);++ setSelectedNotebookRecords([]);++ setSelectedHistorySessions([]);++ setSelectedQuestionEntries([]);++ setSelectedSkills([]);++ setSkillsAutoMode(false);++ setSelectedMemoryFiles([]);++ },++ [++ attachments,++ bookReferencesPayload,++ historyReferencesPayload,++ isMathAnimatorMode,++ isQuizMode,++ isResearchMode,++ isVisualizeMode,++ mathAnimatorConfig,++ memoryReferencesPayload,++ notebookReferencesPayload,++ questionNotebookReferencesPayload,++ quizConfig,++ quizPdf,++ researchConfig,++ selectedHistorySessions.length,++ selectedMemoryFiles.length,++ selectedBookReferences.length,++ selectedNotebookRecords.length,++ selectedQuestionEntries.length,++ selectedSkills,++ skillsAutoMode,++ sendMessage,++ shouldAutoScrollRef,++ state.isStreaming,++ t,++ visualizeConfig,++ ],++ );++++ const handleConfirmOutline = useCallback(++ (++ outline: OutlineItem[],++ _topic: string,++ originalConfig?: Record<string, unknown> | null,++ ) => {++ const config: Record<string, unknown> = {++ ...(originalConfig ?? {++ mode: researchConfig.mode,++ depth: researchConfig.depth,++ sources: [...researchConfig.sources],++ }),++ confirmed_outline: outline,++ };++ sendMessage(_topic, [], config, undefined, undefined, {++ displayUserMessage: false,++ persistUserMessage: false,++ });++ shouldAutoScrollRef.current = true;++ },++ [researchConfig, sendMessage, shouldAutoScrollRef],++ );++++ const handleRegenerateMessage = useCallback(() => {++ regenerateLastMessage();++ }, [regenerateLastMessage]);++++ const handleSetKB = useCallback(++ (kb: string) => {++ setKBs(kb ? [kb] : []);++ },++ [setKBs],++ );++ const handleSelectNotebookPicker = useCallback(() => {++ setShowNotebookPicker(true);++ }, []);++ const handleSelectBookPicker = useCallback(() => {++ setShowBookPicker(true);++ }, []);++ const handleSelectHistoryPicker = useCallback(() => {++ setShowHistoryPicker(true);++ }, []);++ const handleSelectQuestionBankPicker = useCallback(() => {++ setShowQuestionBankPicker(true);++ }, []);++ const handleSelectSkillsPicker = useCallback(() => {++ setShowSkillsPicker(true);++ }, []);++ const handleSelectMemoryPicker = useCallback(() => {++ setShowMemoryPicker(true);++ }, []);++ const handleRemoveHistory = useCallback((sessionId: string) => {++ setSelectedHistorySessions((prev) =>++ prev.filter((item) => item.sessionId !== sessionId),++ );++ }, []);++ const handleRemoveNotebook = useCallback((notebookId: string) => {++ setSelectedNotebookRecords((prev) =>++ prev.filter((record) => record.notebookId !== notebookId),++ );++ }, []);++ const handleRemoveBookReference = useCallback((bookId: string) => {++ setSelectedBookReferences((prev) =>++ prev.filter((record) => record.bookId !== bookId),++ );++ }, []);++ const handleRemoveQuestion = useCallback((entryId: number) => {++ setSelectedQuestionEntries((prev) =>++ prev.filter((entry) => entry.id !== entryId),++ );++ }, []);++ const handleToggleSkill = useCallback((name: string) => {++ setSkillsAutoMode(false);++ setSelectedSkills((prev) =>++ prev.includes(name) ? prev.filter((n) => n !== name) : [...prev, name],++ );++ }, []);++++ const handleSetSkillsAuto = useCallback((auto: boolean) => {++ setSkillsAutoMode(auto);++ if (auto) setSelectedSkills([]);++ }, []);++++ const handleToggleMemoryFile = useCallback((file: SpaceMemoryFile) => {++ setSelectedMemoryFiles((prev) =>++ prev.includes(file)++ ? prev.filter((item) => item !== file)++ : [...prev, file],++ );++ }, []);++++ const handleTogglePanelCollapsed = useCallback(() => {++ setPanelCollapsed((prev) => !prev);++ }, []);++ const handleCloseNotebookPicker = useCallback(() => {++ setShowNotebookPicker(false);++ }, []);++ const handleCloseBookPicker = useCallback(() => {++ setShowBookPicker(false);++ }, []);++ const handleApplyBookReferences = useCallback(++ (references: SelectedBookReference[]) => {++ setSelectedBookReferences(references);++ },++ [],++ );++ const handleApplyNotebookRecords = useCallback(++ (records: SelectedRecord[]) => {++ setSelectedNotebookRecords(records);++ },++ [],++ );++ const handleCloseHistoryPicker = useCallback(() => {++ setShowHistoryPicker(false);++ }, []);++ const handleApplyHistorySessions = useCallback(++ (sessions: SelectedHistorySession[]) => {++ setSelectedHistorySessions(sessions);++ },++ [],++ );++ const handleCloseQuestionBankPicker = useCallback(() => {++ setShowQuestionBankPicker(false);++ }, []);++ const handleApplyQuestionEntries = useCallback(++ (entries: SelectedQuestionEntry[]) => {++ setSelectedQuestionEntries(entries);++ },++ [],++ );++ const handleCloseSkillsPicker = useCallback(() => {++ setShowSkillsPicker(false);++ }, []);++ const handleApplySkillsSelection = useCallback(++ (selection: { auto: boolean; skills: string[] }) => {++ setSkillsAutoMode(selection.auto);++ setSelectedSkills(selection.auto ? [] : selection.skills);++ },++ [],++ );++ const handleCloseMemoryPicker = useCallback(() => {++ setShowMemoryPicker(false);++ }, []);++ const handleApplyMemoryFiles = useCallback((files: SpaceMemoryFile[]) => {++ setSelectedMemoryFiles(files);++ }, []);++ const handleCloseSaveModal = useCallback(() => {++ setShowSaveModal(false);++ }, []);++++ const handleNewChat = useCallback(() => {++ cancelStreamingTurn();++ router.push("/chat");++ }, [cancelStreamingTurn, router]);++++ const handleDownloadMarkdown = useCallback(() => {++ if (!state.messages.length) return;++ const title =++ state.messages++ .find((msg) => msg.role === "user")++ ?.content.trim()++ .slice(0, 80) || "Chat Session";++ downloadChatMarkdown(state.messages, { title });++ }, [state.messages]);++++ return (++ <div++ // When the preview drawer is open AND the viewport is wide enough,++ // push the chat content to the left by the drawer's width so the two++ // panels live side-by-side (matches Claude desktop). On smaller++ // screens the drawer overlays — squeezing a phone-width chat into++ // the remaining ~30 px would be useless. The actual padding +++ // transition lives in `chat-preview-shell` (globals.css) so we can++ // hand-tune it without fighting Tailwind's arbitrary-value parser.++ data-preview-open={previewSource ? "true" : "false"}++ className="chat-preview-shell flex h-full flex-col overflow-hidden bg-[var(--background)]"++ >++ <div className="mx-auto flex w-full max-w-[960px] items-center justify-between px-6 pt-3 pb-0">++ <span className="text-[15px] font-semibold tracking-[-0.01em] text-[var(--foreground)]">++ {t(activeCap.label)}++ </span>++ <div className="flex items-center gap-2">++ <button++ onClick={() => setShowSaveModal(true)}++ disabled={!chatSavePayload}++ className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-[var(--border)]/50 disabled:hover:text-[var(--muted-foreground)]"++ >++ {t("Save to Notebook")}++ </button>++ <button++ onClick={handleDownloadMarkdown}++ disabled={!state.messages.length}++ title={t("Download chat history as Markdown")}++ className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-[var(--border)]/50 disabled:hover:text-[var(--muted-foreground)]"++ >++ {t("Download Markdown")}++ </button>++ <button++ onClick={handleNewChat}++ className="rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"++ >++ {t("New chat")}++ </button>++ </div>++ </div>++ <div className="mx-auto flex w-full max-w-[960px] flex-1 min-h-0 flex-col overflow-hidden px-6">++ {!hasMessages ? (++ <div className="flex flex-1 min-h-0 flex-col items-center justify-center animate-fade-in">++ <div className="text-center">++ <h1 className="font-serif text-[36px] font-medium tracking-[-0.01em] text-[var(--foreground)]">++ {t("What would you like to learn?")}++ </h1>++ <p className="mt-4 text-[15px] text-[var(--muted-foreground)]">++ {t("Ask anything — I'm here to help you understand.")}++ </p>++ </div>++ </div>++ ) : (++ <div++ ref={messagesContainerRef}++ data-chat-scroll-root="true"++ onScroll={handleMessagesScroll}++ className={`mx-auto w-full flex-1 min-h-0 space-y-7 overflow-y-auto pr-4 [scrollbar-gutter:stable] ${hasMessages ? "pt-0" : "pt-2 pb-6"}`}++ style={++ hasMessages++ ? (() => {++ const maskImage =++ "linear-gradient(to bottom, transparent 0px, #000 32px, #000 calc(100% - 40px), transparent 100%)";++ return {++ paddingBottom: "4px",++ WebkitMaskImage: maskImage,++ maskImage,++ };++ })()++ : undefined++ }++ >++ <ChatMessageList++ messages={state.messages}++ isStreaming={state.isStreaming}++ sessionId={state.sessionId}++ language={state.language}++ onAnswerNow={handleAnswerNow}++ onCopyAssistantMessage={copyAssistantMessage}++ onRegenerateMessage={handleRegenerateMessage}++ onConfirmOutline={handleConfirmOutline}++ onPreviewAttachment={handlePreviewMessageAttachment}++ />++ <div ref={messagesEndRef} className="h-px w-full shrink-0" />++ </div>++ )}++++ <ChatComposer++ composerRef={composerRef}++ capMenuRef={capMenuRef}++ capBtnRef={capBtnRef}++ toolMenuRef={toolMenuRef}++ toolBtnRef={toolBtnRef}++ spaceMenuRef={spaceMenuRef}++ spaceBtnRef={spaceBtnRef}++ dragCounter={dragCounter}++ dragging={dragging}++ capMenuOpen={capMenuOpen}++ toolMenuOpen={toolMenuOpen}++ spaceMenuOpen={spaceMenuOpen}++ hasMessages={hasMessages}++ attachments={attachments}++ attachmentError={attachmentError}++ activeCap={activeCap}++ visibleTools={visibleTools}++ selectedTools={selectedTools}++ ragActive={ragActive}++ knowledgeBases={knowledgeBases}++ llmOptions={llmOptions}++ activeLLMDefault={activeLLMDefault}++ llmSelection={state.llmSelection}++ llmOptionsLoading={llmOptionsLoading}++ llmOptionsError={llmOptionsError}++ selectedBookReferences={selectedBookReferences}++ selectedNotebookRecords={selectedNotebookRecords}++ selectedHistorySessions={selectedHistorySessions}++ selectedQuestionEntries={selectedQuestionEntries}++ notebookReferenceGroups={notebookReferenceGroups}++ selectedSkills={selectedSkills}++ skillsAutoMode={skillsAutoMode}++ selectedMemoryFiles={selectedMemoryFiles}++ stateKnowledgeBase={state.knowledgeBases[0] || ""}++ isStreaming={state.isStreaming}++ isResearchMode={isResearchMode}++ isQuizMode={isQuizMode}++ isMathAnimatorMode={isMathAnimatorMode}++ isVisualizeMode={isVisualizeMode}++ quizConfig={quizConfig}++ quizPdf={quizPdf}++ mathAnimatorConfig={mathAnimatorConfig}++ visualizeConfig={visualizeConfig}++ researchConfig={researchConfig}++ researchValidationErrors={researchValidation.errors}++ panelCollapsed={panelCollapsed}++ capabilities={CAPABILITIES}++ researchSources={RESEARCH_SOURCES}++ onSetCapMenuOpen={setCapMenuOpen}++ onSetToolMenuOpen={setToolMenuOpen}++ onSetSpaceMenuOpen={setSpaceMenuOpen}++ onSetKB={handleSetKB}++ onSelectLLM={setLLMSelection}++ onSelectNotebookPicker={handleSelectNotebookPicker}++ onSelectBookPicker={handleSelectBookPicker}++ onSelectHistoryPicker={handleSelectHistoryPicker}++ onSelectQuestionBankPicker={handleSelectQuestionBankPicker}++ onSelectSkillsPicker={handleSelectSkillsPicker}++ onSelectMemoryPicker={handleSelectMemoryPicker}++ onToggleTool={toggleTool}++ onToggleSkill={handleToggleSkill}++ onSetSkillsAuto={handleSetSkillsAuto}++ onToggleMemoryFile={handleToggleMemoryFile}++ onToggleResearchSource={toggleResearchSource}++ onSend={handleSend}++ onRemoveAttachment={removeAttachment}++ onPreviewAttachment={handlePreviewPendingAttachment}++ onRemoveHistory={handleRemoveHistory}++ onRemoveBookReference={handleRemoveBookReference}++ onRemoveNotebook={handleRemoveNotebook}++ onRemoveQuestion={handleRemoveQuestion}++ onDragEnter={handleDragEnter}++ onDragLeave={handleDragLeave}++ onDragOver={handleDragOver}++ onDrop={handleDrop}++ onPaste={handlePaste}++ onAddFiles={handleAddFiles}++ onSelectCapability={handleSelectCapability}++ onCancelStreaming={cancelStreamingTurn}++ onChangeQuizConfig={setQuizConfig}++ onUploadQuizPdf={setQuizPdf}++ onChangeMathAnimatorConfig={setMathAnimatorConfig}++ onChangeVisualizeConfig={setVisualizeConfig}++ onChangeResearchConfig={setResearchConfig}++ onTogglePanelCollapsed={handleTogglePanelCollapsed}++ />++ </div>++ <NotebookRecordPicker++ open={showNotebookPicker}++ onClose={handleCloseNotebookPicker}++ onApply={handleApplyNotebookRecords}++ />++ <BookReferencePicker++ open={showBookPicker}++ initialReferences={selectedBookReferences}++ onClose={handleCloseBookPicker}++ onApply={handleApplyBookReferences}++ />++ <HistorySessionPicker++ open={showHistoryPicker}++ onClose={handleCloseHistoryPicker}++ onApply={handleApplyHistorySessions}++ />++ <QuestionBankPicker++ open={showQuestionBankPicker}++ onClose={handleCloseQuestionBankPicker}++ onApply={handleApplyQuestionEntries}++ />++ <SkillsPicker++ open={showSkillsPicker}++ initialAuto={skillsAutoMode}++ initialSkills={selectedSkills}++ onClose={handleCloseSkillsPicker}++ onApply={handleApplySkillsSelection}++ />++ <MemoryPicker++ open={showMemoryPicker}++ initialFiles={selectedMemoryFiles}++ onClose={handleCloseMemoryPicker}++ onApply={handleApplyMemoryFiles}++ />++ <SaveToNotebookModal++ open={showSaveModal}++ payload={chatSavePayload}++ messages={chatSaveMessages}++ onClose={handleCloseSaveModal}++ />++ <FilePreviewDrawer++ open={previewSource !== null}++ source={previewSource}++ onClose={handleClosePreview}++ />++ </div>++ );++}diff --cc web/app/(workspace)/playground/page.tsxindex 9ebfce0b6,5a9cfb15c..93adf55aa--- a/web/app/(workspace)/playground/page.tsx+++ b/web/app/(workspace)/playground/page.tsx@@@ -1,89 -1,89 +1,175 @@@-"use client";--import { useEffect, useMemo, useRef, useState } from "react";-import {- BrainCircuit,- ChevronDown,- Check,- Code2,- Database,- FileText,- FileSearch,- Globe,- Lightbulb,- Loader2,- MessageSquare,- Microscope,- PenLine,- Play,- Sparkles,- Terminal,- Upload,- X,- type LucideIcon,-} from "lucide-react";-import { useTranslation } from "react-i18next";-import { apiUrl } from "@/lib/api";-import AssistantResponse from "@/components/common/AssistantResponse";-import MarkdownRenderer from "@/components/common/MarkdownRenderer";-import ProcessLogs from "@/components/common/ProcessLogs";-import ResearchConfigPanel from "@/components/research/ResearchConfigPanel";-import {- extractBase64FromDataUrl,- readFileAsDataUrl,-} from "@/lib/file-attachments";-import { listKnowledgeBases } from "@/lib/knowledge-api";-import type { StreamEvent } from "@/lib/unified-ws";-import {- filterFrontendTools,- FRONTEND_HIDDEN_TOOLS,- loadCapabilityPlaygroundConfigs,- resolveCapabilityPlaygroundConfig,- saveCapabilityPlaygroundConfig,- type CapabilityPlaygroundConfig,- type CapabilityPlaygroundConfigMap,-} from "@/lib/playground-config";-import {- buildResearchWSConfig,- createEmptyResearchConfig,- normalizeResearchConfig,- validateResearchConfig,- type DeepResearchFormConfig,- type ResearchSource,-} from "@/lib/research-types";--/* ------------------------------------------------------------------ */-/* Icon maps — consistent with chat page */-/* ------------------------------------------------------------------ */--const TOOL_ICONS: Record<string, LucideIcon> = {- brainstorm: Lightbulb,- rag: Database,- web_search: Globe,- code_execution: Code2,- reason: Sparkles,- paper_search: FileSearch,-};--const TOOL_LABELS: Record<string, string> = {- brainstorm: "Brainstorm",- rag: "RAG",- web_search: "Web Search",- code_execution: "Code Execution",- reason: "Reason",- paper_search: "Arxiv Search",-};--const RESEARCH_SOURCE_OPTIONS: Array<{- name: ResearchSource;- label: string;- icon: LucideIcon;-}> = [- { name: "kb", label: "Knowledge Base", icon: Database },- { name: "web", label: "Web", icon: Globe },- { name: "papers", label: "Papers", icon: FileSearch },-];-+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import {+ BrainCircuit,+ ChevronDown,+ Check,+ Code2,+ Database,+ FileText,+ FileSearch,+ Globe,+ Lightbulb,+ Loader2,+ MessageSquare,+ Microscope,+ PenLine,+ Play,+ Sparkles,+ Terminal,+ Upload,+ X,+ type LucideIcon,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import { apiFetch, apiUrl } from "@/lib/api";+import AssistantResponse from "@/components/common/AssistantResponse";+import MarkdownRenderer from "@/components/common/MarkdownRenderer";+import ProcessLogs from "@/components/common/ProcessLogs";+import ResearchConfigPanel from "@/components/research/ResearchConfigPanel";+import {+ extractBase64FromDataUrl,+ readFileAsDataUrl,+} from "@/lib/file-attachments";+import { listKnowledgeBases } from "@/lib/knowledge-api";+import type { StreamEvent } from "@/lib/unified-ws";+import {+ filterFrontendTools,+ FRONTEND_HIDDEN_TOOLS,+ loadCapabilityPlaygroundConfigs,+ resolveCapabilityPlaygroundConfig,+ saveCapabilityPlaygroundConfig,+ type CapabilityPlaygroundConfig,+ type CapabilityPlaygroundConfigMap,+} from "@/lib/playground-config";+import {+ buildResearchWSConfig,+ createEmptyResearchConfig,+ normalizeResearchConfig,+ validateResearchConfig,+ type DeepResearchFormConfig,+ type ResearchSource,+} from "@/lib/research-types";++/* ------------------------------------------------------------------ */+/* Icon maps — consistent with chat page */+/* ------------------------------------------------------------------ */++const TOOL_ICONS: Record<string, LucideIcon> = {+ brainstorm: Lightbulb,+ rag: Database,+ web_search: Globe,+ code_execution: Code2,+ reason: Sparkles,+ paper_search: FileSearch,+};++const TOOL_LABELS: Record<string, string> = {+ brainstorm: "Brainstorm",+ rag: "RAG",+ web_search: "Web Search",+ code_execution: "Code Execution",+ reason: "Reason",+ paper_search: "Arxiv Search",+};++const RESEARCH_SOURCE_OPTIONS: Array<{+ name: ResearchSource;+ label: string;+ icon: LucideIcon;+}> = [+ { name: "kb", label: "Knowledge Base", icon: Database },+ { name: "web", label: "Web", icon: Globe },+ { name: "papers", label: "Papers", icon: FileSearch },+];+++"use client";++++import { useEffect, useMemo, useRef, useState } from "react";++import {++ BrainCircuit,++ ChevronDown,++ Check,++ Code2,++ Database,++ FileText,++ FileSearch,++ Globe,++ Lightbulb,++ Loader2,++ MessageSquare,++ Microscope,++ PenLine,++ Play,++ Sparkles,++ Terminal,++ Upload,++ X,++ type LucideIcon,++} from "lucide-react";++import { useTranslation } from "react-i18next";++import { apiUrl } from "@/lib/api";++import AssistantResponse from "@/components/common/AssistantResponse";++import MarkdownRenderer from "@/components/common/MarkdownRenderer";++import ProcessLogs from "@/components/common/ProcessLogs";++import ResearchConfigPanel from "@/components/research/ResearchConfigPanel";++import {++ extractBase64FromDataUrl,++ readFileAsDataUrl,++} from "@/lib/file-attachments";++import { listKnowledgeBases } from "@/lib/knowledge-api";++import type { StreamEvent } from "@/lib/unified-ws";++import {++ filterFrontendTools,++ FRONTEND_HIDDEN_TOOLS,++ loadCapabilityPlaygroundConfigs,++ resolveCapabilityPlaygroundConfig,++ saveCapabilityPlaygroundConfig,++ type CapabilityPlaygroundConfig,++ type CapabilityPlaygroundConfigMap,++} from "@/lib/playground-config";++import {++ buildResearchWSConfig,++ createEmptyResearchConfig,++ normalizeResearchConfig,++ validateResearchConfig,++ type DeepResearchFormConfig,++ type ResearchSource,++} from "@/lib/research-types";++++/* ------------------------------------------------------------------ */++/* Icon maps — consistent with chat page */++/* ------------------------------------------------------------------ */++++const TOOL_ICONS: Record<string, LucideIcon> = {++ brainstorm: Lightbulb,++ rag: Database,++ web_search: Globe,++ code_execution: Code2,++ reason: Sparkles,++ paper_search: FileSearch,++};++++const TOOL_LABELS: Record<string, string> = {++ brainstorm: "Brainstorm",++ rag: "RAG",++ web_search: "Web Search",++ code_execution: "Code Execution",++ reason: "Reason",++ paper_search: "Arxiv Search",++};++++const RESEARCH_SOURCE_OPTIONS: Array<{++ name: ResearchSource;++ label: string;++ icon: LucideIcon;++}> = [++ { name: "kb", label: "Knowledge Base", icon: Database },++ { name: "web", label: "Web", icon: Globe },++ { name: "papers", label: "Papers", icon: FileSearch },++];++const CAPABILITY_ICONS: Record<string, LucideIcon> = {chat: MessageSquare,deep_solve: BrainCircuit,@@@ -96,2033 -97,2034 +183,4063 @@@ const CAPABILITY_LABELS: Record<stringdeep_solve: "Deep Solve",deep_question: "Quiz Generation",deep_research: "Deep Research",+ guided_learning: "Guided Learning",};--function getToolIcon(name: string): LucideIcon {- return TOOL_ICONS[name] ?? Terminal;-}--function getCapIcon(name: string): LucideIcon {- return CAPABILITY_ICONS[name] ?? Sparkles;-}--function getToolLabel(name: string): string {- return TOOL_LABELS[name] ?? titleCase(name);-}--function getCapabilityLabel(name: string): string {- return CAPABILITY_LABELS[name] ?? titleCase(name);-}--/* ------------------------------------------------------------------ */-/* Types */-/* ------------------------------------------------------------------ */--interface ToolParam {- name: string;- type: string;- description?: string;- required?: boolean;- default?: unknown;- enum?: string[] | null;-}--interface ToolInfo {- name: string;- description: string;- parameters?: ToolParam[];-}--interface CapabilityInfo {- name: string;- description: string;- stages?: string[];- tools_used?: string[];-}--interface ExecResult {- success: boolean;- content: string;- sources: Array<Record<string, string>>;- metadata: Record<string, unknown>;-}--interface CapabilityExecResult {- success: boolean;- data: Record<string, unknown>;- elapsedMs?: number;-}--interface KnowledgeBase {- name: string;- is_default?: boolean;-}--interface TesterMessage {- role: "user" | "assistant";- content: string;- events?: StreamEvent[];- processLogs?: string[];- result?: CapabilityExecResult | null;- error?: string | null;-}--type DeepQuestionMode = "custom" | "mimic";--interface DeepQuestionFormConfig {- mode: DeepQuestionMode;- topic: string;- num_questions: number;- difficulty: string;- question_type: string;- preference: string;- paper_path: string;- max_questions: number;-}--/* ------------------------------------------------------------------ */-/* Helpers */-/* ------------------------------------------------------------------ */--function titleCase(v: string) {- return v.replaceAll("_", " ").replace(/\b\w/g, (c) => c.toUpperCase());-}--const QUERY_PARAM_NAMES = new Set(["query", "intent", "code", "topic"]);--const DEFAULT_DEEP_QUESTION_CONFIG: DeepQuestionFormConfig = {- mode: "custom",- topic: "",- num_questions: 3,- difficulty: "auto",- question_type: "auto",- preference: "",- paper_path: "",- max_questions: 10,-};--function normalizeDeepQuestionConfig(- raw: Record<string, unknown> | undefined,-): DeepQuestionFormConfig {- const mode = raw?.mode === "mimic" ? "mimic" : "custom";- return {- mode,- topic: typeof raw?.topic === "string" ? raw.topic : "",- num_questions:- typeof raw?.num_questions === "number" && raw.num_questions > 0- ? raw.num_questions- : DEFAULT_DEEP_QUESTION_CONFIG.num_questions,- difficulty:- typeof raw?.difficulty === "string" && raw.difficulty- ? raw.difficulty- : DEFAULT_DEEP_QUESTION_CONFIG.difficulty,- question_type:- typeof raw?.question_type === "string" && raw.question_type- ? raw.question_type- : DEFAULT_DEEP_QUESTION_CONFIG.question_type,- preference: typeof raw?.preference === "string" ? raw.preference : "",- paper_path: typeof raw?.paper_path === "string" ? raw.paper_path : "",- max_questions:- typeof raw?.max_questions === "number" && raw.max_questions > 0- ? raw.max_questions- : DEFAULT_DEEP_QUESTION_CONFIG.max_questions,- };-}--/* ------------------------------------------------------------------ */-/* TracePanel */-/* ------------------------------------------------------------------ */--function TracePanel({ events }: { events: StreamEvent[] }) {- const { t } = useTranslation();- if (!events.length) return null;-- const grouped = new Map<string, StreamEvent[]>();- for (const ev of events) {- const key = ev.stage || "session";- const list = grouped.get(key) ?? [];- list.push(ev);- grouped.set(key, list);- }-- return (- <div className="space-y-2">- {Array.from(grouped.entries()).map(([stage, stageEvents]) => {- const renderable = stageEvents.filter((e) =>- [- "thinking",- "progress",- "tool_call",- "tool_result",- "error",- ].includes(e.type),- );- if (!renderable.length) return null;- return (- <details- key={stage}- className="group overflow-hidden rounded-lg border border-[var(--border)] bg-[var(--card)]"- >- <summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-3 py-2 text-[13px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/50">- <span>- {stage === "session" ? t("Details") : titleCase(stage)}- </span>- <ChevronDown- size={13}- className="text-[var(--muted-foreground)] transition-transform group-open:rotate-180"- />- </summary>- <div className="border-t border-[var(--border)] px-3 py-2.5 space-y-1.5">- {renderable.map((ev, i) => {- if (ev.type === "thinking")- return (- <p- key={`${stage}-t-${i}`}- className="text-[12px] italic leading-relaxed text-[var(--muted-foreground)]"- >- {ev.content}- </p>- );- if (ev.type === "progress") {- const cur = Number(ev.metadata?.current ?? 0),- tot = Number(ev.metadata?.total ?? 0);- return (- <div- key={`${stage}-p-${i}`}- className="rounded-md bg-[var(--muted)] px-2.5 py-1.5 text-[12px] text-[var(--muted-foreground)]"- >- <div>{ev.content}</div>- {tot > 0 && (- <div className="mt-1.5 h-1 overflow-hidden rounded-full bg-[var(--border)]">- <div- className="h-full rounded-full bg-[var(--primary)] transition-all duration-300"- style={{- width: `${Math.min(100, (cur / tot) * 100)}%`,- }}- />- </div>- )}- </div>- );- }- if (ev.type === "tool_call" || ev.type === "tool_result")- return (- <div- key={`${stage}-tc-${i}`}- className="rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5"- >- <div className="text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]">- {ev.type === "tool_call"- ? t("Tool call")- : t("Tool result")}- </div>- <div className="mt-0.5 text-[12px] text-[var(--foreground)]">- {ev.content || String(ev.metadata?.tool ?? "")}- </div>- </div>- );- if (ev.type === "error")- return (- <div- key={`${stage}-e-${i}`}- className="rounded-md border border-red-200 bg-red-50 px-2.5 py-1.5 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300"- >- {ev.content}- </div>- );- return null;- })}- </div>- </details>- );- })}- </div>- );-}--/* ------------------------------------------------------------------ */-/* ToolExecutor */-/* ------------------------------------------------------------------ */--function ToolExecutor({- tool,- knowledgeBases,-}: {- tool: ToolInfo;- knowledgeBases: KnowledgeBase[];-}) {- const { t } = useTranslation();- const params = tool.parameters ?? [];- const [values, setValues] = useState<Record<string, string>>({});- const [executing, setExecuting] = useState(false);- const [result, setResult] = useState<ExecResult | null>(null);- const [error, setError] = useState<string | null>(null);- const [processLogs, setProcessLogs] = useState<string[]>([]);- const abortRef = useRef<AbortController | null>(null);-- useEffect(() => {- setValues({});- setResult(null);- setError(null);- setProcessLogs([]);- }, [tool.name]);-- useEffect(- () => () => {- abortRef.current?.abort();- },- [],- );-- const setParam = (name: string, val: string) =>- setValues((p) => ({ ...p, [name]: val }));-- const queryParam = params.find((p) => QUERY_PARAM_NAMES.has(p.name));- const otherParams = params.filter((p) => !QUERY_PARAM_NAMES.has(p.name));-- const execute = async () => {- abortRef.current?.abort();- const controller = new AbortController();- abortRef.current = controller;- setExecuting(true);- setResult(null);- setError(null);- setProcessLogs([]);- try {- const coerced: Record<string, unknown> = {};- for (const p of params) {- const raw = values[p.name];- if (!raw) continue;- if (p.type === "integer") coerced[p.name] = parseInt(raw, 10);- else if (p.type === "number") coerced[p.name] = parseFloat(raw);- else if (p.type === "boolean") coerced[p.name] = raw === "true";- else coerced[p.name] = raw;- }-- const res = await fetch(- apiUrl(`/api/v1/plugins/tools/${tool.name}/execute-stream`),- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ params: coerced }),- signal: controller.signal,- },- );-- if (!res.ok) {- const data = await res.json().catch(() => null);- throw new Error(data?.detail || `HTTP ${res.status}`);- }-- const reader = res.body?.getReader();- if (!reader) throw new Error("No response body");-- const decoder = new TextDecoder();- let buffer = "";-- while (true) {- const { done, value } = await reader.read();- if (done) break;-- buffer += decoder.decode(value, { stream: true });- const parts = buffer.split("\n\n");- buffer = parts.pop() ?? "";-- for (const part of parts) {- if (!part.trim()) continue;- const eventMatch = part.match(/^event:\s*(.+)$/m);- const dataMatch = part.match(/^data:\s*(.+)$/m);- if (!eventMatch || !dataMatch) continue;-- const eventType = eventMatch[1].trim();- let payload: Record<string, unknown>;- try {- payload = JSON.parse(dataMatch[1]);- } catch {- continue;- }-- if (eventType === "process_log") {- const line = (payload.message as string) ?? "";- setProcessLogs((prev) => [...prev, line]);- } else if (eventType === "result") {- setResult({- success: payload.success as boolean,- content: (payload.content as string) ?? "",- sources: (payload.sources as Array<Record<string, string>>) ?? [],- metadata: (payload.metadata as Record<string, unknown>) ?? {},- });- } else if (eventType === "error") {- setError((payload.detail as string) ?? "Unknown error");- }- }- }- } catch (err: unknown) {- if (controller.signal.aborted) return;- setError(err instanceof Error ? err.message : String(err));- } finally {- if (!controller.signal.aborted) setExecuting(false);- }- };-- const isKbNameParam = (p: ToolParam) => p.name === "kb_name";-- const renderParam = (p: ToolParam) => {- if (isKbNameParam(p)) {- return (- <select- value={values[p.name] ?? ""}- onChange={(e) => setParam(p.name, e.target.value)}- className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"- >- <option value="">{t("Select knowledge base...")}</option>- {knowledgeBases.map((kb) => (- <option key={kb.name} value={kb.name}>- {kb.name}- {kb.is_default ? ` (${t("default")})` : ""}- </option>- ))}- </select>- );- }-- if (p.enum) {- return (- <select- value={values[p.name] ?? ""}- onChange={(e) => setParam(p.name, e.target.value)}- className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"- >- <option value="">{t("Select...")}</option>- {p.enum.map((v) => (- <option key={v} value={v}>- {v}- </option>- ))}- </select>- );- }-- return (- <input- type={p.type === "integer" || p.type === "number" ? "number" : "text"}- value={values[p.name] ?? ""}- onChange={(e) => setParam(p.name, e.target.value)}- placeholder={p.description || p.name}- className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"- />- );- };-- return (- <div className="space-y-5">- {/* Config params (non-query) */}- {otherParams.length > 0 && (- <div>- <h4 className="mb-2.5 text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">- {t("Parameters")}- </h4>- <div className="grid gap-3 md:grid-cols-2">- {otherParams.map((p) => (- <div key={`${tool.name}-${p.name}`}>- <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- {p.name}- {p.required !== false && (- <span className="ml-0.5 text-[var(--primary)]">*</span>- )}- <span className="ml-1.5 text-[10px] font-normal uppercase text-[var(--muted-foreground)]">- {p.type}- </span>- </label>- {renderParam(p)}- </div>- ))}- </div>- </div>- )}-- {/* Query input — visually distinct */}- {queryParam && (- <div className="rounded-xl border-2 border-dashed border-[var(--primary)]/30 bg-[var(--primary)]/[0.03] p-4">- <label className="mb-2 flex items-center gap-1.5 text-[12px] font-semibold text-[var(--primary)]">- <Terminal size={13} />- {queryParam.name === "code" ? t("Code input") : t("Query input")}- </label>- {queryParam.name === "code" || queryParam.name === "topic" ? (- <textarea- value={values[queryParam.name] ?? ""}- onChange={(e) => setParam(queryParam.name, e.target.value)}- placeholder={queryParam.description || t("Enter your input...")}- rows={queryParam.name === "topic" ? 5 : 4}- className="w-full resize-none rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 font-mono text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"- />- ) : (- <input- type="text"- value={values[queryParam.name] ?? ""}- onChange={(e) => setParam(queryParam.name, e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter" && !executing) execute();- }}- placeholder={queryParam.description || t("Enter your query...")}- className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"- />- )}- </div>- )}-- {/* Execute button */}- <button- onClick={execute}- disabled={executing}- className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity disabled:opacity-50"- >- {executing ? (- <Loader2 size={14} className="animate-spin" />- ) : (- <Play size={14} />- )}- {executing ? t("Running...") : t("Execute")}- </button>-- {/* Process Logs */}- <ProcessLogs logs={processLogs} executing={executing} />-- {/* Error */}- {error && (- <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">- {error}- </div>- )}-- {/* Result */}- {result && (- <div className="space-y-3">- <div className="flex items-center gap-2">- {result.success ? (- <span className="inline-flex items-center gap-1 rounded-md bg-green-50 px-2 py-0.5 text-[11px] font-medium text-green-700 dark:bg-green-950/30 dark:text-green-400">- <Check size={10} /> {t("Success")}- </span>- ) : (- <span className="inline-flex items-center gap-1 rounded-md bg-red-50 px-2 py-0.5 text-[11px] font-medium text-red-700 dark:bg-red-950/30 dark:text-red-400">- <X size={10} /> {t("Failed")}- </span>- )}- </div>-- {result.content && (- <div className="max-h-[400px] overflow-y-auto rounded-lg border border-[var(--border)] bg-[var(--background)] p-4">- <MarkdownRenderer content={result.content} variant="prose" />- </div>- )}-- {result.sources.length > 0 && (- <details className="group rounded-lg border border-[var(--border)] bg-[var(--card)]">- <summary className="flex cursor-pointer list-none items-center justify-between px-3 py-2 text-[13px] font-medium text-[var(--foreground)]">- {t("Sources")} ({result.sources.length})- <ChevronDown- size={13}- className="text-[var(--muted-foreground)] transition-transform group-open:rotate-180"- />- </summary>- <div className="border-t border-[var(--border)] px-3 py-2.5 space-y-1.5">- {result.sources.map((s, i) => (- <div- key={`src-${i}`}- className="rounded-md bg-[var(--muted)] px-2.5 py-1.5 text-[12px]"- >- <div className="font-medium text-[var(--foreground)]">- {s.title || s.query || s.type || t("Source")}- </div>- {s.url && (- <div className="mt-0.5 break-all text-[11px] text-[var(--muted-foreground)]">- {s.url}- </div>- )}- </div>- ))}- </div>- </details>- )}- </div>- )}- </div>- );-}--/* ------------------------------------------------------------------ */-/* CapabilityResultPanel */-/* ------------------------------------------------------------------ */--function CapabilityResultPanel({- result,-}: {- result: CapabilityExecResult | null | undefined;-}) {- const { t } = useTranslation();- if (!result) return null;-- const response =- typeof result.data.response === "string" ? result.data.response : "";- const extraData = Object.fromEntries(- Object.entries(result.data).filter(([key]) => key !== "response"),- );- const extraKeys = Object.keys(extraData);-- return (- <div className="space-y-3">- <div className="flex items-center gap-2">- {result.success ? (- <span className="inline-flex items-center gap-1 rounded-md bg-green-50 px-2 py-0.5 text-[11px] font-medium text-green-700 dark:bg-green-950/30 dark:text-green-400">- <Check size={10} /> {t("Success")}- </span>- ) : (- <span className="inline-flex items-center gap-1 rounded-md bg-red-50 px-2 py-0.5 text-[11px] font-medium text-red-700 dark:bg-red-950/30 dark:text-red-400">- <X size={10} /> {t("Failed")}- </span>- )}- {typeof result.elapsedMs === "number" && (- <span className="text-[11px] text-[var(--muted-foreground)]">- {result.elapsedMs} ms- </span>- )}- </div>-- {response && (- <div className="max-h-[400px] overflow-y-auto rounded-lg border border-[var(--border)] bg-[var(--background)] p-4">- <MarkdownRenderer content={response} variant="prose" />- </div>- )}-- {!response && extraKeys.length > 0 && (- <div className="rounded-lg border border-[var(--border)] bg-[var(--background)] p-3">- <pre className="overflow-x-auto whitespace-pre-wrap break-all text-[12px] text-[var(--muted-foreground)]">- {JSON.stringify(extraData, null, 2)}- </pre>- </div>- )}-- {extraKeys.length > 0 && response && (- <details className="group rounded-lg border border-[var(--border)] bg-[var(--card)]">- <summary className="flex cursor-pointer list-none items-center justify-between px-3 py-2 text-[13px] font-medium text-[var(--foreground)]">- {t("Metadata")}- <ChevronDown- size={13}- className="text-[var(--muted-foreground)] transition-transform group-open:rotate-180"- />- </summary>- <div className="border-t border-[var(--border)] px-3 py-2.5">- <pre className="overflow-x-auto whitespace-pre-wrap break-all text-[12px] text-[var(--muted-foreground)]">- {JSON.stringify(extraData, null, 2)}- </pre>- </div>- </details>- )}- </div>- );-}--/* ------------------------------------------------------------------ */-/* DeepQuestionTester */-/* ------------------------------------------------------------------ */--function DeepQuestionTester({- capability,- enabledTools,- knowledgeBase,- config,- onConfigChange,-}: {- capability: CapabilityInfo;- enabledTools: string[];- knowledgeBase: string;- config: DeepQuestionFormConfig;- onConfigChange: (next: DeepQuestionFormConfig) => void;-}) {- const { t, i18n } = useTranslation();- const [messages, setMessages] = useState<TesterMessage[]>([]);- const [streaming, setStreaming] = useState(false);- const [uploadedPdf, setUploadedPdf] = useState<File | null>(null);- const abortRef = useRef<AbortController | null>(null);-- useEffect(- () => () => {- abortRef.current?.abort();- },- [],- );-- const updateLastAssistant = (- updater: (msg: TesterMessage) => TesterMessage,- ) => {- setMessages((prev) => {- const msgs = [...prev];- const last = msgs[msgs.length - 1];- if (last?.role !== "assistant") return prev;- msgs[msgs.length - 1] = updater(last);- return msgs;- });- };-- const updateConfig = <K extends keyof DeepQuestionFormConfig>(- key: K,- value: DeepQuestionFormConfig[K],- ) => {- onConfigChange({ ...config, [key]: value });- };-- const fileToAttachment = async (file: File) => {- const dataUrl = await readFileAsDataUrl(file);- return {- type: "pdf",- filename: file.name,- mime_type: file.type || "application/pdf",- base64: extractBase64FromDataUrl(dataUrl),- };- };-- const canRun =- config.mode === "custom"- ? config.topic.trim().length > 0- : Boolean(uploadedPdf) || config.paper_path.trim().length > 0;-- const run = async () => {- if (!canRun || streaming) return;-- abortRef.current?.abort();- const controller = new AbortController();- abortRef.current = controller;-- const userContent =- config.mode === "custom"- ? config.topic.trim()- : uploadedPdf- ? `Mimic questions from uploaded paper: ${uploadedPdf.name}`- : `Mimic questions from parsed paper: ${config.paper_path.trim()}`;-- setMessages((prev) => [- ...prev,- { role: "user", content: userContent },- {- role: "assistant",- content: "",- events: [],- processLogs: [],- result: null,- error: null,- },- ]);- setStreaming(true);-- try {- const attachments =- config.mode === "mimic" && uploadedPdf- ? [await fileToAttachment(uploadedPdf)]- : [];-- const requestConfig =- config.mode === "custom"- ? {- mode: "custom",- topic: config.topic.trim(),- num_questions: config.num_questions,- difficulty: config.difficulty === "auto" ? "" : config.difficulty,- question_type:- config.question_type === "auto" ? "" : config.question_type,- preference: config.preference.trim(),- }- : {- mode: "mimic",- paper_path: uploadedPdf ? "" : config.paper_path.trim(),- max_questions: config.max_questions,- };-- const res = await fetch(- apiUrl(- `/api/v1/plugins/capabilities/${capability.name}/execute-stream`,- ),- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- content: userContent,- tools: enabledTools,- knowledge_bases:- enabledTools.includes("rag") && knowledgeBase- ? [knowledgeBase]- : [],- language: i18n.language,- config: requestConfig,- attachments,- }),- signal: controller.signal,- },- );-- if (!res.ok) {- const data = await res.json().catch(() => null);- throw new Error(data?.detail || `HTTP ${res.status}`);- }-- const reader = res.body?.getReader();- if (!reader) throw new Error("No response body");-- const decoder = new TextDecoder();- let buffer = "";-- while (true) {- const { done, value } = await reader.read();- if (done) break;-- buffer += decoder.decode(value, { stream: true });- const parts = buffer.split("\n\n");- buffer = parts.pop() ?? "";-- for (const part of parts) {- if (!part.trim()) continue;- const eventMatch = part.match(/^event:\s*(.+)$/m);- const dataMatch = part.match(/^data:\s*(.+)$/m);- if (!eventMatch || !dataMatch) continue;-- const eventType = eventMatch[1].trim();- let payload: Record<string, unknown>;- try {- payload = JSON.parse(dataMatch[1]);- } catch {- continue;- }-- if (eventType === "process_log") {- const line = (payload.message as string) ?? "";- updateLastAssistant((last) => ({- ...last,- processLogs: [...(last.processLogs || []), line],- }));- continue;- }-- if (eventType === "stream") {- const event = payload as unknown as StreamEvent;- if (event.type === "session" || event.type === "done") continue;- updateLastAssistant((last) => ({- ...last,- content:- event.type === "content"- ? `${last.content}${event.content}`- : last.content,- events: [...(last.events || []), event],- }));- continue;- }-- if (eventType === "result") {- updateLastAssistant((last) => ({- ...last,- result: {- success: Boolean(payload.success),- data: (payload.data as Record<string, unknown>) ?? {},- elapsedMs:- typeof payload.elapsed_ms === "number"- ? payload.elapsed_ms- : undefined,- },- }));- continue;- }-- if (eventType === "error") {- updateLastAssistant((last) => ({- ...last,- error: (payload.detail as string) ?? "Unknown error",- }));- }- }- }- } catch (err: unknown) {- if (controller.signal.aborted) return;- updateLastAssistant((last) => ({- ...last,- error: err instanceof Error ? err.message : String(err),- }));- } finally {- if (!controller.signal.aborted) setStreaming(false);- }- };-- return (- <div className="space-y-4">- <div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-4">- <div className="mb-3 flex flex-wrap gap-2">- <button- onClick={() => updateConfig("mode", "custom")}- className={`rounded-lg px-3 py-1.5 text-[12px] font-medium transition-colors ${- config.mode === "custom"- ? "bg-[var(--primary)]/10 text-[var(--primary)]"- : "bg-[var(--muted)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"- }`}- >- {t("Custom")}- </button>- <button- onClick={() => updateConfig("mode", "mimic")}- className={`rounded-lg px-3 py-1.5 text-[12px] font-medium transition-colors ${- config.mode === "mimic"- ? "bg-[var(--primary)]/10 text-[var(--primary)]"- : "bg-[var(--muted)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"- }`}- >- {t("Mimic Exam")}- </button>- </div>-- {config.mode === "custom" ? (- <div className="space-y-3">- <div>- <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- {t("Topic")}- </label>- <textarea- value={config.topic}- onChange={(e) => updateConfig("topic", e.target.value)}- rows={3}- placeholder={t("e.g. Gradient Descent Optimization")}- className="w-full resize-none rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"- />- </div>- <div className="grid gap-3 md:grid-cols-3">- <div>- <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- {t("Count")}- </label>- <input- type="number"- min={1}- max={50}- value={config.num_questions}- onChange={(e) =>- updateConfig(- "num_questions",- Math.max(1, Number(e.target.value) || 1),- )- }- className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"- />- </div>- <div>- <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- {t("Difficulty")}- </label>- <select- value={config.difficulty}- onChange={(e) => updateConfig("difficulty", e.target.value)}- className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"- >- <option value="auto">{t("Auto")}</option>- <option value="easy">{t("Easy")}</option>- <option value="medium">{t("Medium")}</option>- <option value="hard">{t("Hard")}</option>- </select>- </div>- <div>- <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- {t("Type")}- </label>- <select- value={config.question_type}- onChange={(e) =>- updateConfig("question_type", e.target.value)- }- className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"- >- <option value="auto">{t("Auto")}</option>- <option value="choice">{t("Multiple Choice")}</option>- <option value="written">{t("Written")}</option>- <option value="coding">{t("Coding")}</option>- </select>- </div>- </div>- <div>- <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- {t("Preference")}- </label>- <textarea- value={config.preference}- onChange={(e) => updateConfig("preference", e.target.value)}- rows={3}- placeholder={t("Extra constraints, style, focus areas...")}- className="w-full resize-none rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"- />- </div>- </div>- ) : (- <div className="space-y-3">- <div>- <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- {t("Upload Exam Paper (PDF)")}- </label>- <label className="flex cursor-pointer items-center justify-center gap-2 rounded-xl border-2 border-dashed border-[var(--border)] bg-[var(--card)] px-4 py-6 text-[13px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--primary)]/40 hover:text-[var(--foreground)]">- <Upload size={16} />- <span>- {uploadedPdf ? uploadedPdf.name : t("Click to upload PDF")}- </span>- <input- type="file"- accept=".pdf,application/pdf"- className="hidden"- onChange={(e) => {- const file = e.target.files?.[0] ?? null;- setUploadedPdf(file);- if (file) updateConfig("paper_path", "");- }}- />- </label>- </div>- <div className="text-center text-[11px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">- {t("Or")}- </div>- <div>- <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- {t("Pre-parsed Directory")}- </label>- <div className="relative">- <FileText- size={14}- className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--muted-foreground)]"- />- <input- type="text"- value={config.paper_path}- onChange={(e) => {- setUploadedPdf(null);- updateConfig("paper_path", e.target.value);- }}- placeholder={t("e.g. 2211asm1")}- className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] py-2 pl-9 pr-3 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"- />- </div>- </div>- <div className="max-w-xs">- <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">- {t("Max Questions")}- </label>- <input- type="number"- min={1}- max={100}- value={config.max_questions}- onChange={(e) =>- updateConfig(- "max_questions",- Math.max(1, Number(e.target.value) || 1),- )- }- className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"- />- </div>- </div>- )}- </div>-- {messages.map((msg, i) => (- <div key={`${msg.role}-${i}`}>- <div className="mb-1 text-[10px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">- {msg.role === "user" ? t("You") : t("Assistant")}- </div>- {msg.role === "user" ? (- <div className="rounded-lg bg-[var(--muted)] px-3 py-2 text-[13px] text-[var(--foreground)]">- {msg.content}- </div>- ) : (- <div className="space-y-2">- <TracePanel events={msg.events || []} />- <ProcessLogs- logs={msg.processLogs || []}- executing={streaming && i === messages.length - 1}- title={t("Process")}- />- {msg.error && (- <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">- {msg.error}- </div>- )}- <AssistantResponse- content={msg.content}- className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2.5"- />- <CapabilityResultPanel result={msg.result} />- </div>- )}- </div>- ))}-- <div className="flex justify-end">- <button- onClick={run}- disabled={!canRun || streaming}- className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40"- >- {streaming ? (- <Loader2 size={13} className="animate-spin" />- ) : (- <Play size={13} />- )}- {streaming ? t("Running...") : t("Generate")}- </button>- </div>- </div>- );-}--function DeepResearchTester({- capability,- enabledTools,- knowledgeBase,- config,- onConfigChange,-}: {- capability: CapabilityInfo;- enabledTools: string[];- knowledgeBase: string;- config: DeepResearchFormConfig;- onConfigChange: (next: DeepResearchFormConfig) => void;-}) {- const { t, i18n } = useTranslation();- const [input, setInput] = useState("");- const [messages, setMessages] = useState<TesterMessage[]>([]);- const [streaming, setStreaming] = useState(false);- const validation = useMemo(() => validateResearchConfig(config), [config]);- const abortRef = useRef<AbortController | null>(null);-- useEffect(- () => () => {- abortRef.current?.abort();- },- [],- );-- const updateLastAssistant = (- updater: (msg: TesterMessage) => TesterMessage,- ) => {- setMessages((prev) => {- const msgs = [...prev];- const last = msgs[msgs.length - 1];- if (last?.role !== "assistant") return prev;- msgs[msgs.length - 1] = updater(last);- return msgs;- });- };-- const run = async () => {- const content = input.trim();- if (!content || streaming || !validation.valid) return;-- abortRef.current?.abort();- const controller = new AbortController();- abortRef.current = controller;-- setMessages((prev) => [- ...prev,- { role: "user", content },- {- role: "assistant",- content: "",- events: [],- processLogs: [],- result: null,- error: null,- },- ]);- setStreaming(true);-- try {- const res = await fetch(- apiUrl(- `/api/v1/plugins/capabilities/${capability.name}/execute-stream`,- ),- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- content,- tools: enabledTools,- knowledge_bases:- config.sources.includes("kb") && knowledgeBase- ? [knowledgeBase]- : [],- language: i18n.language,- config: buildResearchWSConfig(config),- }),- signal: controller.signal,- },- );-- if (!res.ok) {- const data = await res.json().catch(() => null);- throw new Error(data?.detail || `HTTP ${res.status}`);- }-- const reader = res.body?.getReader();- if (!reader) throw new Error("No response body");-- const decoder = new TextDecoder();- let buffer = "";-- while (true) {- const { done, value } = await reader.read();- if (done) break;-- buffer += decoder.decode(value, { stream: true });- const parts = buffer.split("\n\n");- buffer = parts.pop() ?? "";-- for (const part of parts) {- if (!part.trim()) continue;- const eventMatch = part.match(/^event:\s*(.+)$/m);- const dataMatch = part.match(/^data:\s*(.+)$/m);- if (!eventMatch || !dataMatch) continue;-- const eventType = eventMatch[1].trim();- let payload: Record<string, unknown>;- try {- payload = JSON.parse(dataMatch[1]);- } catch {- continue;- }-- if (eventType === "process_log") {- const line = (payload.message as string) ?? "";- updateLastAssistant((last) => ({- ...last,- processLogs: [...(last.processLogs || []), line],- }));- continue;- }-- if (eventType === "stream") {- const event = payload as unknown as StreamEvent;- if (event.type === "session" || event.type === "done") continue;- updateLastAssistant((last) => ({- ...last,- content:- event.type === "content"- ? `${last.content}${event.content}`- : last.content,- events: [...(last.events || []), event],- }));- continue;- }-- if (eventType === "result") {- updateLastAssistant((last) => ({- ...last,- result: {- success: Boolean(payload.success),- data: (payload.data as Record<string, unknown>) ?? {},- elapsedMs:- typeof payload.elapsed_ms === "number"- ? payload.elapsed_ms- : undefined,- },- }));- continue;- }-- if (eventType === "error") {- updateLastAssistant((last) => ({- ...last,- error: (payload.detail as string) ?? "Unknown error",- }));- }- }- }- } catch (err: unknown) {- if (controller.signal.aborted) return;- updateLastAssistant((last) => ({- ...last,- error: err instanceof Error ? err.message : String(err),- }));- } finally {- if (!controller.signal.aborted) setStreaming(false);- }- };-- const toggleSource = (source: ResearchSource) => {- onConfigChange({- ...config,- sources: config.sources.includes(source)- ? config.sources.filter((item) => item !== source)- : [...config.sources, source],- });- };-- return (- <div className="space-y-4">- <ResearchConfigPanel- value={config}- errors={validation.errors}- collapsed={false}- onChange={onConfigChange}- onToggleCollapsed={() => {}}- />- <div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-3">- <div className="mb-2 text-[12px] font-medium text-[var(--foreground)]">- {t("Sources")}- </div>- <div className="flex flex-wrap gap-2">- {RESEARCH_SOURCE_OPTIONS.map((source) => {- const active = config.sources.includes(source.name);- const Icon = source.icon;- return (- <button- key={source.name}- type="button"- onClick={() => toggleSource(source.name)}- className={`inline-flex h-[32px] items-center gap-1.5 rounded-full px-3 text-[12px] font-medium transition-[background-color,color,box-shadow] ${- active- ? "bg-[var(--muted)] text-[var(--foreground)] shadow-[0_1px_2px_rgba(15,23,42,0.05)] ring-1 ring-[var(--border)]/55"- : "text-[var(--muted-foreground)]/75 hover:bg-[var(--muted)]/55 hover:text-[var(--foreground)]"- }`}- >- <Icon size={13} strokeWidth={1.7} />- {t(source.label)}- </button>- );- })}- </div>- <div className="mt-2 text-[11px] text-[var(--muted-foreground)]">- {config.sources.length- ? t("Selected sources will be queried during research.")- : t("No source selected: the run will use llm-only research.")}- </div>- </div>- <div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-3">- <textarea- value={input}- onChange={(e) => setInput(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter" && !e.shiftKey) {- e.preventDefault();- run();- }- }}- rows={3}- placeholder={t("Describe the research topic...")}- className="w-full resize-none bg-transparent text-[13px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"- />- <div className="mt-2 flex justify-end">- <button- onClick={run}- disabled={!input.trim() || streaming || !validation.valid}- className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40"- >- {streaming ? (- <Loader2 size={13} className="animate-spin" />- ) : (- <Play size={13} />- )}- {streaming ? t("Running...") : t("Run Research")}- </button>- </div>- </div>-- {messages.map((msg, i) => (- <div key={`${msg.role}-${i}`}>- <div className="mb-1 text-[10px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">- {msg.role === "user" ? t("You") : t("Assistant")}- </div>- {msg.role === "user" ? (- <div className="rounded-lg bg-[var(--muted)] px-3 py-2 text-[13px] text-[var(--foreground)]">- {msg.content}- </div>- ) : (- <div className="space-y-2">- <TracePanel events={msg.events || []} />- <ProcessLogs- logs={msg.processLogs || []}- executing={streaming && i === messages.length - 1}- title={t("Process")}- />- {msg.error && (- <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">- {msg.error}- </div>- )}- <AssistantResponse- content={msg.content}- className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2.5"- />- <CapabilityResultPanel result={msg.result} />- </div>- )}- </div>- ))}- </div>- );-}--/* ------------------------------------------------------------------ */-/* CapabilityTester */-/* ------------------------------------------------------------------ */--function CapabilityTester({- capability,- enabledTools,- knowledgeBase,-}: {- capability: CapabilityInfo;- enabledTools: string[];- knowledgeBase: string;-}) {- const { t, i18n } = useTranslation();- const [input, setInput] = useState("");- const [messages, setMessages] = useState<TesterMessage[]>([]);- const [streaming, setStreaming] = useState(false);- const abortRef = useRef<AbortController | null>(null);-- useEffect(- () => () => {- abortRef.current?.abort();- },- [],- );-- const updateLastAssistant = (- updater: (msg: TesterMessage) => TesterMessage,- ) => {- setMessages((prev) => {- const msgs = [...prev];- const last = msgs[msgs.length - 1];- if (last?.role !== "assistant") return prev;- msgs[msgs.length - 1] = updater(last);- return msgs;- });- };-- const send = async () => {- const content = input.trim();- if (!content || streaming) return;-- abortRef.current?.abort();- const controller = new AbortController();- abortRef.current = controller;-- setMessages((prev) => [- ...prev,- { role: "user", content },- {- role: "assistant",- content: "",- events: [],- processLogs: [],- result: null,- error: null,- },- ]);- setInput("");- setStreaming(true);-- try {- const res = await fetch(- apiUrl(- `/api/v1/plugins/capabilities/${capability.name}/execute-stream`,- ),- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- content,- tools: enabledTools,- knowledge_bases:- enabledTools.includes("rag") && knowledgeBase- ? [knowledgeBase]- : [],- language: i18n.language,- }),- signal: controller.signal,- },- );-- if (!res.ok) {- const data = await res.json().catch(() => null);- throw new Error(data?.detail || `HTTP ${res.status}`);- }-- const reader = res.body?.getReader();- if (!reader) throw new Error("No response body");-- const decoder = new TextDecoder();- let buffer = "";-- while (true) {- const { done, value } = await reader.read();- if (done) break;-- buffer += decoder.decode(value, { stream: true });- const parts = buffer.split("\n\n");- buffer = parts.pop() ?? "";-- for (const part of parts) {- if (!part.trim()) continue;- const eventMatch = part.match(/^event:\s*(.+)$/m);- const dataMatch = part.match(/^data:\s*(.+)$/m);- if (!eventMatch || !dataMatch) continue;-- const eventType = eventMatch[1].trim();- let payload: Record<string, unknown>;- try {- payload = JSON.parse(dataMatch[1]);- } catch {- continue;- }-- if (eventType === "process_log") {- const line = (payload.message as string) ?? "";- updateLastAssistant((last) => ({- ...last,- processLogs: [...(last.processLogs || []), line],- }));- continue;- }-- if (eventType === "stream") {- const event = payload as unknown as StreamEvent;- if (event.type === "session" || event.type === "done") continue;- updateLastAssistant((last) => ({- ...last,- content:- event.type === "content"- ? `${last.content}${event.content}`- : last.content,- events: [...(last.events || []), event],- }));- continue;- }-- if (eventType === "result") {- updateLastAssistant((last) => ({- ...last,- result: {- success: Boolean(payload.success),- data: (payload.data as Record<string, unknown>) ?? {},- elapsedMs:- typeof payload.elapsed_ms === "number"- ? payload.elapsed_ms- : undefined,- },- }));- continue;- }-- if (eventType === "error") {- updateLastAssistant((last) => ({- ...last,- error: (payload.detail as string) ?? "Unknown error",- }));- }- }- }- } catch (err: unknown) {- if (controller.signal.aborted) return;- updateLastAssistant((last) => ({- ...last,- error: err instanceof Error ? err.message : String(err),- }));- } finally {- if (!controller.signal.aborted) setStreaming(false);- }- };-- return (- <div className="space-y-3">- {messages.map((msg, i) => (- <div key={`${msg.role}-${i}`}>- <div className="mb-1 text-[10px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">- {msg.role === "user" ? t("You") : t("Assistant")}- </div>- {msg.role === "user" ? (- <div className="rounded-lg bg-[var(--muted)] px-3 py-2 text-[13px] text-[var(--foreground)]">- {msg.content}- </div>- ) : (- <div className="space-y-2">- <TracePanel events={msg.events || []} />- <ProcessLogs- logs={msg.processLogs || []}- executing={streaming && i === messages.length - 1}- title={t("Process")}- />- {msg.error && (- <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">- {msg.error}- </div>- )}- <AssistantResponse- content={msg.content}- className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2.5"- />- <CapabilityResultPanel result={msg.result} />- </div>- )}- </div>- ))}- <div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-3">- <textarea- value={input}- onChange={(e) => setInput(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter" && !e.shiftKey) {- e.preventDefault();- send();- }- }}- rows={2}- placeholder={`${t("Try")} ${t(getCapabilityLabel(capability.name))}...`}- className="w-full resize-none bg-transparent text-[13px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"- />- <div className="mt-2 flex justify-end">- <button- onClick={send}- disabled={!input.trim() || streaming}- className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40"- >- {streaming ? (- <Loader2 size={13} className="animate-spin" />- ) : (- <Play size={13} />- )}- {streaming ? t("Running...") : t("Send")}- </button>- </div>- </div>- </div>- );-}--/* ------------------------------------------------------------------ */-/* Main Page */-/* ------------------------------------------------------------------ */--export default function PlaygroundPage() {- const { t } = useTranslation();- const [tools, setToolsList] = useState<ToolInfo[]>([]);- const [capabilities, setCapabilities] = useState<CapabilityInfo[]>([]);- const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);- const [capabilityConfigs, setCapabilityConfigs] =- useState<CapabilityPlaygroundConfigMap>({});- const [activeKind, setActiveKind] = useState<"tool" | "capability">("tool");- const [activeName, setActiveName] = useState<string>("");- const [loading, setLoading] = useState(true);-- useEffect(() => {- (async () => {- setLoading(true);- try {- const [pluginRes, knowledgeBaseList] = await Promise.all([- fetch(apiUrl("/api/v1/plugins/list")),- listKnowledgeBases(),- ]);- const data = await pluginRes.json();- const visibleTools = (data.tools || []).filter(- (tool: ToolInfo) => !FRONTEND_HIDDEN_TOOLS.has(tool.name),- );- const visibleCapabilities = (data.capabilities || []).map(- (cap: CapabilityInfo) => ({- ...cap,- tools_used: filterFrontendTools(cap.tools_used ?? []),- }),- );-- setToolsList(visibleTools);- setCapabilities(visibleCapabilities);- setCapabilityConfigs(loadCapabilityPlaygroundConfigs());- setKnowledgeBases(knowledgeBaseList);-- if (visibleTools.length) {- setActiveKind("tool");- setActiveName(visibleTools[0].name);- } else if (visibleCapabilities.length) {- setActiveKind("capability");- setActiveName(visibleCapabilities[0].name);- }- } finally {- setLoading(false);- }- })();- }, []);-- const capabilityCatalog = capabilities;-- const activeTool = tools.find((t) => t.name === activeName);- const activeCapability = capabilityCatalog.find((c) => c.name === activeName);- const activeCapabilityConfig = useMemo(- () =>- activeCapability- ? resolveCapabilityPlaygroundConfig(- capabilityConfigs,- activeCapability.name,- activeCapability.tools_used ?? [],- )- : null,- [activeCapability, capabilityConfigs],- );- const activeDeepQuestionConfig = useMemo(- () =>- normalizeDeepQuestionConfig(- activeCapabilityConfig?.config as Record<string, unknown> | undefined,- ),- [activeCapabilityConfig?.config],- );- const activeDeepResearchConfig = useMemo(- () =>- normalizeResearchConfig(- activeCapabilityConfig?.config as Record<string, unknown> | undefined,- ),- [activeCapabilityConfig?.config],- );- const listItems = useMemo(- () =>- activeKind === "tool"- ? tools.map((t) => ({ name: t.name, description: t.description }))- : capabilityCatalog.map((c) => ({- name: c.name,- description: c.description,- })),- [activeKind, capabilityCatalog, tools],- );-- const persistCapabilityConfig = (- capabilityName: string,- next: CapabilityPlaygroundConfig,- ) => {- setCapabilityConfigs((prev) =>- saveCapabilityPlaygroundConfig(prev, capabilityName, next),- );- };-- const toggleCapabilityTool = (toolName: string) => {- if (!activeCapability || !activeCapabilityConfig) return;- const allowedTools = filterFrontendTools(activeCapability.tools_used ?? []);- if (!allowedTools.includes(toolName)) return;-- const enabledSet = new Set(activeCapabilityConfig.enabledTools);- if (enabledSet.has(toolName)) enabledSet.delete(toolName);- else enabledSet.add(toolName);-- const defaultKb =- knowledgeBases.find((kb) => kb.is_default)?.name ??- knowledgeBases[0]?.name ??- "";-- persistCapabilityConfig(activeCapability.name, {- enabledTools: allowedTools.filter((name) => enabledSet.has(name)),- knowledgeBase:- activeCapabilityConfig.knowledgeBase ||- (enabledSet.has("rag") ? defaultKb : ""),- config: activeCapabilityConfig.config,- });- };-- const setCapabilityKnowledgeBase = (knowledgeBase: string) => {- if (!activeCapability || !activeCapabilityConfig) return;- persistCapabilityConfig(activeCapability.name, {- enabledTools: activeCapabilityConfig.enabledTools,- knowledgeBase,- config: activeCapabilityConfig.config,- });- };-- const setDeepQuestionConfig = (next: DeepQuestionFormConfig) => {- if (!activeCapability || !activeCapabilityConfig) return;- persistCapabilityConfig(activeCapability.name, {- enabledTools: activeCapabilityConfig.enabledTools,- knowledgeBase: activeCapabilityConfig.knowledgeBase,- config: next as unknown as Record<string, unknown>,- });- };-- const setDeepResearchConfig = (next: DeepResearchFormConfig) => {- if (!activeCapability || !activeCapabilityConfig) return;- persistCapabilityConfig(activeCapability.name, {- enabledTools: activeCapabilityConfig.enabledTools,- knowledgeBase: activeCapabilityConfig.knowledgeBase,- config: next as unknown as Record<string, unknown>,- });- };-- return (- <div className="min-h-screen bg-[var(--background)]">- <div className="mx-auto max-w-5xl px-6 py-8">- <div className="mb-6">- <h1 className="text-2xl font-bold tracking-tight text-[var(--foreground)]">- {t("Playground")}- </h1>- <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">- {t(- "Explore the building blocks of DeepTutor: reusable tools and higher-level capabilities.",- )}- </p>- </div>-- {loading ? (- <div className="flex items-center justify-center py-20">- <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />- </div>- ) : (- <div className="space-y-5">- {/* Tab bar */}- <div className="inline-flex rounded-lg border border-[var(--border)] bg-[var(--muted)] p-0.5">- <button- onClick={() => {- setActiveKind("tool");- if (tools.length) setActiveName(tools[0].name);- }}- className={`rounded-md px-3.5 py-1.5 text-[13px] font-medium transition-all ${activeKind === "tool" ? "bg-[var(--card)] text-[var(--foreground)] shadow-sm" : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"}`}- >- {t("Tools")}- </button>- <button- onClick={() => {- setActiveKind("capability");- if (capabilityCatalog.length)- setActiveName(capabilityCatalog[0].name);- }}- className={`rounded-md px-3.5 py-1.5 text-[13px] font-medium transition-all ${activeKind === "capability" ? "bg-[var(--card)] text-[var(--foreground)] shadow-sm" : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"}`}- >- {t("Capabilities")}- </button>- </div>-- {/* Two-column layout */}- <div className="grid gap-5 lg:grid-cols-[280px_1fr]">- {/* Left: Item list */}- <section className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 shadow-sm">- <div className="mb-3 flex items-center gap-1.5">- {activeKind === "tool" ? (- <Terminal className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />- ) : (- <Sparkles className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />- )}- <h2 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">- {activeKind === "tool" ? t("Tools") : t("Capabilities")}- </h2>- </div>- <div className="space-y-1">- {listItems.map((item) => {- const Icon =- activeKind === "tool"- ? getToolIcon(item.name)- : getCapIcon(item.name);- return (- <button- key={item.name}- onClick={() => setActiveName(item.name)}- className={`w-full rounded-lg border px-3 py-2.5 text-left transition-all ${- activeName === item.name- ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"- : "border-[var(--border)] bg-[var(--background)] text-[var(--foreground)] hover:border-[var(--foreground)]/10 hover:bg-[var(--muted)]"- }`}- >- <div className="flex items-center gap-1.5">- <Icon size={13} strokeWidth={1.7} />- <span className="text-[13px] font-medium">- {activeKind === "tool"- ? t(getToolLabel(item.name))- : t(getCapabilityLabel(item.name))}- </span>- </div>- <div- className={`mt-0.5 line-clamp-2 text-[11px] leading-relaxed ${activeName === item.name ? "text-[var(--primary-foreground)]/70" : "text-[var(--muted-foreground)]"}`}- >- {item.description}- </div>- </button>- );- })}- </div>- </section>-- {/* Right: Detail panel */}- <section className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">- {activeKind === "tool" && activeTool- ? (() => {- const ToolIcon = getToolIcon(activeTool.name);- return (- <div className="space-y-6">- <div>- <div className="flex items-center gap-2 text-[11px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">- <ToolIcon size={13} strokeWidth={1.7} />- {t("Tool")}- </div>- <h2 className="mt-1 text-xl font-bold tracking-tight text-[var(--foreground)]">- {t(getToolLabel(activeTool.name))}- </h2>- <p className="mt-2 max-w-2xl text-[13px] leading-relaxed text-[var(--muted-foreground)]">- {activeTool.description}- </p>- </div>-- <div className="border-t border-[var(--border)] pt-6">- <ToolExecutor- tool={activeTool}- knowledgeBases={knowledgeBases}- />- </div>- </div>- );- })()- : activeCapability- ? (() => {- const CapIcon = getCapIcon(activeCapability.name);- return (- <div className="space-y-6">- <div>- <div className="flex items-center gap-2 text-[11px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">- <CapIcon size={13} strokeWidth={1.7} />- {t("Capability")}- </div>- <h2 className="mt-1 text-xl font-bold tracking-tight text-[var(--foreground)]">- {t(getCapabilityLabel(activeCapability.name))}- </h2>- <p className="mt-2 max-w-2xl text-[13px] leading-relaxed text-[var(--muted-foreground)]">- {activeCapability.description}- </p>- </div>-- <div>- <h3 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">- {t("Enable Tools")}- </h3>- {!!activeCapability.tools_used?.length ? (- <div className="mt-2.5 flex flex-wrap gap-1.5">- {activeCapability.tools_used.map((tool) => {- const TIcon = getToolIcon(tool);- const enabled =- activeCapabilityConfig?.enabledTools.includes(- tool,- ) ?? true;- return (- <button- key={`${activeCapability.name}-${tool}`}- onClick={() =>- toggleCapabilityTool(tool)- }- className={`inline-flex items-center gap-1 rounded-md border px-2.5 py-1 text-[11px] font-medium transition-colors ${- enabled- ? "border-[var(--primary)] bg-[var(--primary)]/10 text-[var(--primary)]"- : "border-[var(--border)] bg-[var(--background)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"- }`}- >- <TIcon size={11} strokeWidth={1.7} />- {t(getToolLabel(tool))}- </button>- );- })}- </div>- ) : (- <p className="mt-2 text-[12px] text-[var(--muted-foreground)]">- {t(- "This capability runs without optional tools.",- )}- </p>- )}- </div>-- {activeCapabilityConfig?.enabledTools.includes(- "rag",- ) && (- <div>- <h3 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">- {t("Knowledge Base")}- </h3>- <div className="mt-2.5 max-w-sm">- <select- value={activeCapabilityConfig.knowledgeBase}- onChange={(e) =>- setCapabilityKnowledgeBase(e.target.value)- }- className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"- >- <option value="">- {t("Select knowledge base...")}- </option>- {knowledgeBases.map((kb) => (- <option key={kb.name} value={kb.name}>- {kb.name}- {kb.is_default- ? ` (${t("default")})`- : ""}- </option>- ))}- </select>- </div>- </div>- )}-- <div className="border-t border-[var(--border)] pt-6">- <div className="mb-3">- <h3 className="text-[14px] font-semibold text-[var(--foreground)]">- {t("Try this capability")}- </h3>- <p className="mt-0.5 text-[12px] text-[var(--muted-foreground)]">- {t(- "Run a focused conversation here without leaving the playground.",- )}- </p>- </div>- {activeCapability.name === "deep_question" ? (- <DeepQuestionTester- key={activeCapability.name}- capability={activeCapability}- enabledTools={- activeCapabilityConfig?.enabledTools ??- activeCapability.tools_used ??- []- }- knowledgeBase={- activeCapabilityConfig?.knowledgeBase ?? ""- }- config={activeDeepQuestionConfig}- onConfigChange={setDeepQuestionConfig}- />- ) : activeCapability.name === "deep_research" ? (- <DeepResearchTester- key={activeCapability.name}- capability={activeCapability}- enabledTools={- activeCapabilityConfig?.enabledTools ??- activeCapability.tools_used ??- []- }- knowledgeBase={- activeCapabilityConfig?.knowledgeBase ?? ""- }- config={activeDeepResearchConfig}- onConfigChange={setDeepResearchConfig}- />- ) : (- <CapabilityTester- key={activeCapability.name}- capability={activeCapability}- enabledTools={- activeCapabilityConfig?.enabledTools ??- activeCapability.tools_used ??- []- }- knowledgeBase={- activeCapabilityConfig?.knowledgeBase ?? ""- }- />- )}- </div>- </div>- );- })()- : null}- </section>- </div>- </div>- )}- </div>- </div>- );-}++function getToolIcon(name: string): LucideIcon {+ return TOOL_ICONS[name] ?? Terminal;+}++function getCapIcon(name: string): LucideIcon {+ return CAPABILITY_ICONS[name] ?? Sparkles;+}++function getToolLabel(name: string): string {+ return TOOL_LABELS[name] ?? titleCase(name);+}++function getCapabilityLabel(name: string): string {+ return CAPABILITY_LABELS[name] ?? titleCase(name);+}++/* ------------------------------------------------------------------ */+/* Types */+/* ------------------------------------------------------------------ */++interface ToolParam {+ name: string;+ type: string;+ description?: string;+ required?: boolean;+ default?: unknown;+ enum?: string[] | null;+}++interface ToolInfo {+ name: string;+ description: string;+ parameters?: ToolParam[];+}++interface CapabilityInfo {+ name: string;+ description: string;+ stages?: string[];+ tools_used?: string[];+}++interface ExecResult {+ success: boolean;+ content: string;+ sources: Array<Record<string, string>>;+ metadata: Record<string, unknown>;+}++interface CapabilityExecResult {+ success: boolean;+ data: Record<string, unknown>;+ elapsedMs?: number;+}++interface KnowledgeBase {+ name: string;+ is_default?: boolean;+}++interface TesterMessage {+ role: "user" | "assistant";+ content: string;+ events?: StreamEvent[];+ processLogs?: string[];+ result?: CapabilityExecResult | null;+ error?: string | null;+}++type DeepQuestionMode = "custom" | "mimic";++interface DeepQuestionFormConfig {+ mode: DeepQuestionMode;+ topic: string;+ num_questions: number;+ difficulty: string;+ question_type: string;+ preference: string;+ paper_path: string;+ max_questions: number;+}++/* ------------------------------------------------------------------ */+/* Helpers */+/* ------------------------------------------------------------------ */++function titleCase(v: string) {+ return v.replaceAll("_", " ").replace(/\b\w/g, (c) => c.toUpperCase());+}++const QUERY_PARAM_NAMES = new Set(["query", "intent", "code", "topic"]);++const DEFAULT_DEEP_QUESTION_CONFIG: DeepQuestionFormConfig = {+ mode: "custom",+ topic: "",+ num_questions: 3,+ difficulty: "auto",+ question_type: "auto",+ preference: "",+ paper_path: "",+ max_questions: 10,+};++function normalizeDeepQuestionConfig(+ raw: Record<string, unknown> | undefined,+): DeepQuestionFormConfig {+ const mode = raw?.mode === "mimic" ? "mimic" : "custom";+ return {+ mode,+ topic: typeof raw?.topic === "string" ? raw.topic : "",+ num_questions:+ typeof raw?.num_questions === "number" && raw.num_questions > 0+ ? raw.num_questions+ : DEFAULT_DEEP_QUESTION_CONFIG.num_questions,+ difficulty:+ typeof raw?.difficulty === "string" && raw.difficulty+ ? raw.difficulty+ : DEFAULT_DEEP_QUESTION_CONFIG.difficulty,+ question_type:+ typeof raw?.question_type === "string" && raw.question_type+ ? raw.question_type+ : DEFAULT_DEEP_QUESTION_CONFIG.question_type,+ preference: typeof raw?.preference === "string" ? raw.preference : "",+ paper_path: typeof raw?.paper_path === "string" ? raw.paper_path : "",+ max_questions:+ typeof raw?.max_questions === "number" && raw.max_questions > 0+ ? raw.max_questions+ : DEFAULT_DEEP_QUESTION_CONFIG.max_questions,+ };+}++/* ------------------------------------------------------------------ */+/* TracePanel */+/* ------------------------------------------------------------------ */++function TracePanel({ events }: { events: StreamEvent[] }) {+ const { t } = useTranslation();+ if (!events.length) return null;++ const grouped = new Map<string, StreamEvent[]>();+ for (const ev of events) {+ const key = ev.stage || "session";+ const list = grouped.get(key) ?? [];+ list.push(ev);+ grouped.set(key, list);+ }++ return (+ <div className="space-y-2">+ {Array.from(grouped.entries()).map(([stage, stageEvents]) => {+ const renderable = stageEvents.filter((e) =>+ [+ "thinking",+ "progress",+ "tool_call",+ "tool_result",+ "error",+ ].includes(e.type),+ );+ if (!renderable.length) return null;+ return (+ <details+ key={stage}+ className="group overflow-hidden rounded-lg border border-[var(--border)] bg-[var(--card)]"+ >+ <summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-3 py-2 text-[13px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/50">+ <span>+ {stage === "session" ? t("Details") : titleCase(stage)}+ </span>+ <ChevronDown+ size={13}+ className="text-[var(--muted-foreground)] transition-transform group-open:rotate-180"+ />+ </summary>+ <div className="border-t border-[var(--border)] px-3 py-2.5 space-y-1.5">+ {renderable.map((ev, i) => {+ if (ev.type === "thinking")+ return (+ <p+ key={`${stage}-t-${i}`}+ className="text-[12px] italic leading-relaxed text-[var(--muted-foreground)]"+ >+ {ev.content}+ </p>+ );+ if (ev.type === "progress") {+ const cur = Number(ev.metadata?.current ?? 0),+ tot = Number(ev.metadata?.total ?? 0);+ return (+ <div+ key={`${stage}-p-${i}`}+ className="rounded-md bg-[var(--muted)] px-2.5 py-1.5 text-[12px] text-[var(--muted-foreground)]"+ >+ <div>{ev.content}</div>+ {tot > 0 && (+ <div className="mt-1.5 h-1 overflow-hidden rounded-full bg-[var(--border)]">+ <div+ className="h-full rounded-full bg-[var(--primary)] transition-all duration-300"+ style={{+ width: `${Math.min(100, (cur / tot) * 100)}%`,+ }}+ />+ </div>+ )}+ </div>+ );+ }+ if (ev.type === "tool_call" || ev.type === "tool_result")+ return (+ <div+ key={`${stage}-tc-${i}`}+ className="rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5"+ >+ <div className="text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]">+ {ev.type === "tool_call"+ ? t("Tool call")+ : t("Tool result")}+ </div>+ <div className="mt-0.5 text-[12px] text-[var(--foreground)]">+ {ev.content || String(ev.metadata?.tool ?? "")}+ </div>+ </div>+ );+ if (ev.type === "error")+ return (+ <div+ key={`${stage}-e-${i}`}+ className="rounded-md border border-red-200 bg-red-50 px-2.5 py-1.5 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300"+ >+ {ev.content}+ </div>+ );+ return null;+ })}+ </div>+ </details>+ );+ })}+ </div>+ );+}++/* ------------------------------------------------------------------ */+/* ToolExecutor */+/* ------------------------------------------------------------------ */++function ToolExecutor({+ tool,+ knowledgeBases,+}: {+ tool: ToolInfo;+ knowledgeBases: KnowledgeBase[];+}) {+ const { t } = useTranslation();+ const params = tool.parameters ?? [];+ const [values, setValues] = useState<Record<string, string>>({});+ const [executing, setExecuting] = useState(false);+ const [result, setResult] = useState<ExecResult | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [processLogs, setProcessLogs] = useState<string[]>([]);+ const abortRef = useRef<AbortController | null>(null);++ useEffect(() => {+ setValues({});+ setResult(null);+ setError(null);+ setProcessLogs([]);+ }, [tool.name]);++ useEffect(+ () => () => {+ abortRef.current?.abort();+ },+ [],+ );++ const setParam = (name: string, val: string) =>+ setValues((p) => ({ ...p, [name]: val }));++ const queryParam = params.find((p) => QUERY_PARAM_NAMES.has(p.name));+ const otherParams = params.filter((p) => !QUERY_PARAM_NAMES.has(p.name));++ const execute = async () => {+ abortRef.current?.abort();+ const controller = new AbortController();+ abortRef.current = controller;+ setExecuting(true);+ setResult(null);+ setError(null);+ setProcessLogs([]);+ try {+ const coerced: Record<string, unknown> = {};+ for (const p of params) {+ const raw = values[p.name];+ if (!raw) continue;+ if (p.type === "integer") coerced[p.name] = parseInt(raw, 10);+ else if (p.type === "number") coerced[p.name] = parseFloat(raw);+ else if (p.type === "boolean") coerced[p.name] = raw === "true";+ else coerced[p.name] = raw;+ }++ const res = await apiFetch(+ apiUrl(`/api/v1/plugins/tools/${tool.name}/execute-stream`),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ params: coerced }),+ signal: controller.signal,+ },+ );++ if (!res.ok) {+ const data = await res.json().catch(() => null);+ throw new Error(data?.detail || `HTTP ${res.status}`);+ }++ const reader = res.body?.getReader();+ if (!reader) throw new Error("No response body");++ const decoder = new TextDecoder();+ let buffer = "";++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ buffer += decoder.decode(value, { stream: true });+ const parts = buffer.split("\n\n");+ buffer = parts.pop() ?? "";++ for (const part of parts) {+ if (!part.trim()) continue;+ const eventMatch = part.match(/^event:\s*(.+)$/m);+ const dataMatch = part.match(/^data:\s*(.+)$/m);+ if (!eventMatch || !dataMatch) continue;++ const eventType = eventMatch[1].trim();+ let payload: Record<string, unknown>;+ try {+ payload = JSON.parse(dataMatch[1]);+ } catch {+ continue;+ }++ if (eventType === "process_log") {+ const line = (payload.message as string) ?? "";+ setProcessLogs((prev) => [...prev, line]);+ } else if (eventType === "result") {+ setResult({+ success: payload.success as boolean,+ content: (payload.content as string) ?? "",+ sources: (payload.sources as Array<Record<string, string>>) ?? [],+ metadata: (payload.metadata as Record<string, unknown>) ?? {},+ });+ } else if (eventType === "error") {+ setError((payload.detail as string) ?? "Unknown error");+ }+ }+ }+ } catch (err: unknown) {+ if (controller.signal.aborted) return;+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ if (!controller.signal.aborted) setExecuting(false);+ }+ };++ const isKbNameParam = (p: ToolParam) => p.name === "kb_name";++ const renderParam = (p: ToolParam) => {+ if (isKbNameParam(p)) {+ return (+ <select+ value={values[p.name] ?? ""}+ onChange={(e) => setParam(p.name, e.target.value)}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"+ >+ <option value="">{t("Select knowledge base...")}</option>+ {knowledgeBases.map((kb) => (+ <option key={kb.name} value={kb.name}>+ {kb.name}+ {kb.is_default ? ` (${t("default")})` : ""}+ </option>+ ))}+ </select>+ );+ }++ if (p.enum) {+ return (+ <select+ value={values[p.name] ?? ""}+ onChange={(e) => setParam(p.name, e.target.value)}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"+ >+ <option value="">{t("Select...")}</option>+ {p.enum.map((v) => (+ <option key={v} value={v}>+ {v}+ </option>+ ))}+ </select>+ );+ }++ return (+ <input+ type={p.type === "integer" || p.type === "number" ? "number" : "text"}+ value={values[p.name] ?? ""}+ onChange={(e) => setParam(p.name, e.target.value)}+ placeholder={p.description || p.name}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"+ />+ );+ };++ return (+ <div className="space-y-5">+ {/* Config params (non-query) */}+ {otherParams.length > 0 && (+ <div>+ <h4 className="mb-2.5 text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">+ {t("Parameters")}+ </h4>+ <div className="grid gap-3 md:grid-cols-2">+ {otherParams.map((p) => (+ <div key={`${tool.name}-${p.name}`}>+ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">+ {p.name}+ {p.required !== false && (+ <span className="ml-0.5 text-[var(--primary)]">*</span>+ )}+ <span className="ml-1.5 text-[10px] font-normal uppercase text-[var(--muted-foreground)]">+ {p.type}+ </span>+ </label>+ {renderParam(p)}+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Query input — visually distinct */}+ {queryParam && (+ <div className="rounded-xl border-2 border-dashed border-[var(--primary)]/30 bg-[var(--primary)]/[0.03] p-4">+ <label className="mb-2 flex items-center gap-1.5 text-[12px] font-semibold text-[var(--primary)]">+ <Terminal size={13} />+ {queryParam.name === "code" ? t("Code input") : t("Query input")}+ </label>+ {queryParam.name === "code" || queryParam.name === "topic" ? (+ <textarea+ value={values[queryParam.name] ?? ""}+ onChange={(e) => setParam(queryParam.name, e.target.value)}+ placeholder={queryParam.description || t("Enter your input...")}+ rows={queryParam.name === "topic" ? 5 : 4}+ className="w-full resize-none rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 font-mono text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"+ />+ ) : (+ <input+ type="text"+ value={values[queryParam.name] ?? ""}+ onChange={(e) => setParam(queryParam.name, e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !executing) execute();+ }}+ placeholder={queryParam.description || t("Enter your query...")}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"+ />+ )}+ </div>+ )}++ {/* Execute button */}+ <button+ onClick={execute}+ disabled={executing}+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity disabled:opacity-50"+ >+ {executing ? (+ <Loader2 size={14} className="animate-spin" />+ ) : (+ <Play size={14} />+ )}+ {executing ? t("Running...") : t("Execute")}+ </button>++ {/* Process Logs */}+ <ProcessLogs logs={processLogs} executing={executing} />++ {/* Error */}+ {error && (+ <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">+ {error}+ </div>+ )}++ {/* Result */}+ {result && (+ <div className="space-y-3">+ <div className="flex items-center gap-2">+ {result.success ? (+ <span className="inline-flex items-center gap-1 rounded-md bg-green-50 px-2 py-0.5 text-[11px] font-medium text-green-700 dark:bg-green-950/30 dark:text-green-400">+ <Check size={10} /> {t("Success")}+ </span>+ ) : (+ <span className="inline-flex items-center gap-1 rounded-md bg-red-50 px-2 py-0.5 text-[11px] font-medium text-red-700 dark:bg-red-950/30 dark:text-red-400">+ <X size={10} /> {t("Failed")}+ </span>+ )}+ </div>++ {result.content && (+ <div className="max-h-[400px] overflow-y-auto rounded-lg border border-[var(--border)] bg-[var(--background)] p-4">+ <MarkdownRenderer content={result.content} variant="prose" />+ </div>+ )}++ {result.sources.length > 0 && (+ <details className="group rounded-lg border border-[var(--border)] bg-[var(--card)]">+ <summary className="flex cursor-pointer list-none items-center justify-between px-3 py-2 text-[13px] font-medium text-[var(--foreground)]">+ {t("Sources")} ({result.sources.length})+ <ChevronDown+ size={13}+ className="text-[var(--muted-foreground)] transition-transform group-open:rotate-180"+ />+ </summary>+ <div className="border-t border-[var(--border)] px-3 py-2.5 space-y-1.5">+ {result.sources.map((s, i) => (+ <div+ key={`src-${i}`}+ className="rounded-md bg-[var(--muted)] px-2.5 py-1.5 text-[12px]"+ >+ <div className="font-medium text-[var(--foreground)]">+ {s.title || s.query || s.type || t("Source")}+ </div>+ {s.url && (+ <div className="mt-0.5 break-all text-[11px] text-[var(--muted-foreground)]">+ {s.url}+ </div>+ )}+ </div>+ ))}+ </div>+ </details>+ )}+ </div>+ )}+ </div>+ );+}++/* ------------------------------------------------------------------ */+/* CapabilityResultPanel */+/* ------------------------------------------------------------------ */++function CapabilityResultPanel({+ result,+}: {+ result: CapabilityExecResult | null | undefined;+}) {+ const { t } = useTranslation();+ if (!result) return null;++ const response =+ typeof result.data.response === "string" ? result.data.response : "";+ const extraData = Object.fromEntries(+ Object.entries(result.data).filter(([key]) => key !== "response"),+ );+ const extraKeys = Object.keys(extraData);++ return (+ <div className="space-y-3">+ <div className="flex items-center gap-2">+ {result.success ? (+ <span className="inline-flex items-center gap-1 rounded-md bg-green-50 px-2 py-0.5 text-[11px] font-medium text-green-700 dark:bg-green-950/30 dark:text-green-400">+ <Check size={10} /> {t("Success")}+ </span>+ ) : (+ <span className="inline-flex items-center gap-1 rounded-md bg-red-50 px-2 py-0.5 text-[11px] font-medium text-red-700 dark:bg-red-950/30 dark:text-red-400">+ <X size={10} /> {t("Failed")}+ </span>+ )}+ {typeof result.elapsedMs === "number" && (+ <span className="text-[11px] text-[var(--muted-foreground)]">+ {result.elapsedMs} ms+ </span>+ )}+ </div>++ {response && (+ <div className="max-h-[400px] overflow-y-auto rounded-lg border border-[var(--border)] bg-[var(--background)] p-4">+ <MarkdownRenderer content={response} variant="prose" />+ </div>+ )}++ {!response && extraKeys.length > 0 && (+ <div className="rounded-lg border border-[var(--border)] bg-[var(--background)] p-3">+ <pre className="overflow-x-auto whitespace-pre-wrap break-all text-[12px] text-[var(--muted-foreground)]">+ {JSON.stringify(extraData, null, 2)}+ </pre>+ </div>+ )}++ {extraKeys.length > 0 && response && (+ <details className="group rounded-lg border border-[var(--border)] bg-[var(--card)]">+ <summary className="flex cursor-pointer list-none items-center justify-between px-3 py-2 text-[13px] font-medium text-[var(--foreground)]">+ {t("Metadata")}+ <ChevronDown+ size={13}+ className="text-[var(--muted-foreground)] transition-transform group-open:rotate-180"+ />+ </summary>+ <div className="border-t border-[var(--border)] px-3 py-2.5">+ <pre className="overflow-x-auto whitespace-pre-wrap break-all text-[12px] text-[var(--muted-foreground)]">+ {JSON.stringify(extraData, null, 2)}+ </pre>+ </div>+ </details>+ )}+ </div>+ );+}++/* ------------------------------------------------------------------ */+/* DeepQuestionTester */+/* ------------------------------------------------------------------ */++function DeepQuestionTester({+ capability,+ enabledTools,+ knowledgeBase,+ config,+ onConfigChange,+}: {+ capability: CapabilityInfo;+ enabledTools: string[];+ knowledgeBase: string;+ config: DeepQuestionFormConfig;+ onConfigChange: (next: DeepQuestionFormConfig) => void;+}) {+ const { t, i18n } = useTranslation();+ const [messages, setMessages] = useState<TesterMessage[]>([]);+ const [streaming, setStreaming] = useState(false);+ const [uploadedPdf, setUploadedPdf] = useState<File | null>(null);+ const abortRef = useRef<AbortController | null>(null);++ useEffect(+ () => () => {+ abortRef.current?.abort();+ },+ [],+ );++ const updateLastAssistant = (+ updater: (msg: TesterMessage) => TesterMessage,+ ) => {+ setMessages((prev) => {+ const msgs = [...prev];+ const last = msgs[msgs.length - 1];+ if (last?.role !== "assistant") return prev;+ msgs[msgs.length - 1] = updater(last);+ return msgs;+ });+ };++ const updateConfig = <K extends keyof DeepQuestionFormConfig>(+ key: K,+ value: DeepQuestionFormConfig[K],+ ) => {+ onConfigChange({ ...config, [key]: value });+ };++ const fileToAttachment = async (file: File) => {+ const dataUrl = await readFileAsDataUrl(file);+ return {+ type: "pdf",+ filename: file.name,+ mime_type: file.type || "application/pdf",+ base64: extractBase64FromDataUrl(dataUrl),+ };+ };++ const canRun =+ config.mode === "custom"+ ? config.topic.trim().length > 0+ : Boolean(uploadedPdf) || config.paper_path.trim().length > 0;++ const run = async () => {+ if (!canRun || streaming) return;++ abortRef.current?.abort();+ const controller = new AbortController();+ abortRef.current = controller;++ const userContent =+ config.mode === "custom"+ ? config.topic.trim()+ : uploadedPdf+ ? `Mimic questions from uploaded paper: ${uploadedPdf.name}`+ : `Mimic questions from parsed paper: ${config.paper_path.trim()}`;++ setMessages((prev) => [+ ...prev,+ { role: "user", content: userContent },+ {+ role: "assistant",+ content: "",+ events: [],+ processLogs: [],+ result: null,+ error: null,+ },+ ]);+ setStreaming(true);++ try {+ const attachments =+ config.mode === "mimic" && uploadedPdf+ ? [await fileToAttachment(uploadedPdf)]+ : [];++ const requestConfig =+ config.mode === "custom"+ ? {+ mode: "custom",+ topic: config.topic.trim(),+ num_questions: config.num_questions,+ difficulty: config.difficulty === "auto" ? "" : config.difficulty,+ question_type:+ config.question_type === "auto" ? "" : config.question_type,+ preference: config.preference.trim(),+ }+ : {+ mode: "mimic",+ paper_path: uploadedPdf ? "" : config.paper_path.trim(),+ max_questions: config.max_questions,+ };++ const res = await apiFetch(+ apiUrl(+ `/api/v1/plugins/capabilities/${capability.name}/execute-stream`,+ ),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ content: userContent,+ tools: enabledTools,+ knowledge_bases:+ enabledTools.includes("rag") && knowledgeBase+ ? [knowledgeBase]+ : [],+ language: i18n.language,+ config: requestConfig,+ attachments,+ }),+ signal: controller.signal,+ },+ );++ if (!res.ok) {+ const data = await res.json().catch(() => null);+ throw new Error(data?.detail || `HTTP ${res.status}`);+ }++ const reader = res.body?.getReader();+ if (!reader) throw new Error("No response body");++ const decoder = new TextDecoder();+ let buffer = "";++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ buffer += decoder.decode(value, { stream: true });+ const parts = buffer.split("\n\n");+ buffer = parts.pop() ?? "";++ for (const part of parts) {+ if (!part.trim()) continue;+ const eventMatch = part.match(/^event:\s*(.+)$/m);+ const dataMatch = part.match(/^data:\s*(.+)$/m);+ if (!eventMatch || !dataMatch) continue;++ const eventType = eventMatch[1].trim();+ let payload: Record<string, unknown>;+ try {+ payload = JSON.parse(dataMatch[1]);+ } catch {+ continue;+ }++ if (eventType === "process_log") {+ const line = (payload.message as string) ?? "";+ updateLastAssistant((last) => ({+ ...last,+ processLogs: [...(last.processLogs || []), line],+ }));+ continue;+ }++ if (eventType === "stream") {+ const event = payload as unknown as StreamEvent;+ if (event.type === "session" || event.type === "done") continue;+ updateLastAssistant((last) => ({+ ...last,+ content:+ event.type === "content"+ ? `${last.content}${event.content}`+ : last.content,+ events: [...(last.events || []), event],+ }));+ continue;+ }++ if (eventType === "result") {+ updateLastAssistant((last) => ({+ ...last,+ result: {+ success: Boolean(payload.success),+ data: (payload.data as Record<string, unknown>) ?? {},+ elapsedMs:+ typeof payload.elapsed_ms === "number"+ ? payload.elapsed_ms+ : undefined,+ },+ }));+ continue;+ }++ if (eventType === "error") {+ updateLastAssistant((last) => ({+ ...last,+ error: (payload.detail as string) ?? "Unknown error",+ }));+ }+ }+ }+ } catch (err: unknown) {+ if (controller.signal.aborted) return;+ updateLastAssistant((last) => ({+ ...last,+ error: err instanceof Error ? err.message : String(err),+ }));+ } finally {+ if (!controller.signal.aborted) setStreaming(false);+ }+ };++ return (+ <div className="space-y-4">+ <div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-4">+ <div className="mb-3 flex flex-wrap gap-2">+ <button+ onClick={() => updateConfig("mode", "custom")}+ className={`rounded-lg px-3 py-1.5 text-[12px] font-medium transition-colors ${+ config.mode === "custom"+ ? "bg-[var(--primary)]/10 text-[var(--primary)]"+ : "bg-[var(--muted)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ {t("Custom")}+ </button>+ <button+ onClick={() => updateConfig("mode", "mimic")}+ className={`rounded-lg px-3 py-1.5 text-[12px] font-medium transition-colors ${+ config.mode === "mimic"+ ? "bg-[var(--primary)]/10 text-[var(--primary)]"+ : "bg-[var(--muted)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ {t("Mimic Exam")}+ </button>+ </div>++ {config.mode === "custom" ? (+ <div className="space-y-3">+ <div>+ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">+ {t("Topic")}+ </label>+ <textarea+ value={config.topic}+ onChange={(e) => updateConfig("topic", e.target.value)}+ rows={3}+ placeholder={t("e.g. Gradient Descent Optimization")}+ className="w-full resize-none rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"+ />+ </div>+ <div className="grid gap-3 md:grid-cols-3">+ <div>+ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">+ {t("Count")}+ </label>+ <input+ type="number"+ min={1}+ max={50}+ value={config.num_questions}+ onChange={(e) =>+ updateConfig(+ "num_questions",+ Math.max(1, Number(e.target.value) || 1),+ )+ }+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"+ />+ </div>+ <div>+ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">+ {t("Difficulty")}+ </label>+ <select+ value={config.difficulty}+ onChange={(e) => updateConfig("difficulty", e.target.value)}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"+ >+ <option value="auto">{t("Auto")}</option>+ <option value="easy">{t("Easy")}</option>+ <option value="medium">{t("Medium")}</option>+ <option value="hard">{t("Hard")}</option>+ </select>+ </div>+ <div>+ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">+ {t("Type")}+ </label>+ <select+ value={config.question_type}+ onChange={(e) =>+ updateConfig("question_type", e.target.value)+ }+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"+ >+ <option value="auto">{t("Auto")}</option>+ <option value="choice">{t("Multiple Choice")}</option>+ <option value="written">{t("Written")}</option>+ <option value="coding">{t("Coding")}</option>+ </select>+ </div>+ </div>+ <div>+ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">+ {t("Preference")}+ </label>+ <textarea+ value={config.preference}+ onChange={(e) => updateConfig("preference", e.target.value)}+ rows={3}+ placeholder={t("Extra constraints, style, focus areas...")}+ className="w-full resize-none rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"+ />+ </div>+ </div>+ ) : (+ <div className="space-y-3">+ <div>+ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">+ {t("Upload Exam Paper (PDF)")}+ </label>+ <label className="flex cursor-pointer items-center justify-center gap-2 rounded-xl border-2 border-dashed border-[var(--border)] bg-[var(--card)] px-4 py-6 text-[13px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--primary)]/40 hover:text-[var(--foreground)]">+ <Upload size={16} />+ <span>+ {uploadedPdf ? uploadedPdf.name : t("Click to upload PDF")}+ </span>+ <input+ type="file"+ accept=".pdf,application/pdf"+ className="hidden"+ onChange={(e) => {+ const file = e.target.files?.[0] ?? null;+ setUploadedPdf(file);+ if (file) updateConfig("paper_path", "");+ }}+ />+ </label>+ </div>+ <div className="text-center text-[11px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">+ {t("Or")}+ </div>+ <div>+ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">+ {t("Pre-parsed Directory")}+ </label>+ <div className="relative">+ <FileText+ size={14}+ className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--muted-foreground)]"+ />+ <input+ type="text"+ value={config.paper_path}+ onChange={(e) => {+ setUploadedPdf(null);+ updateConfig("paper_path", e.target.value);+ }}+ placeholder={t("e.g. 2211asm1")}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] py-2 pl-9 pr-3 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"+ />+ </div>+ </div>+ <div className="max-w-xs">+ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">+ {t("Max Questions")}+ </label>+ <input+ type="number"+ min={1}+ max={100}+ value={config.max_questions}+ onChange={(e) =>+ updateConfig(+ "max_questions",+ Math.max(1, Number(e.target.value) || 1),+ )+ }+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"+ />+ </div>+ </div>+ )}+ </div>++ {messages.map((msg, i) => (+ <div key={`${msg.role}-${i}`}>+ <div className="mb-1 text-[10px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">+ {msg.role === "user" ? t("You") : t("Assistant")}+ </div>+ {msg.role === "user" ? (+ <div className="rounded-lg bg-[var(--muted)] px-3 py-2 text-[13px] text-[var(--foreground)]">+ {msg.content}+ </div>+ ) : (+ <div className="space-y-2">+ <TracePanel events={msg.events || []} />+ <ProcessLogs+ logs={msg.processLogs || []}+ executing={streaming && i === messages.length - 1}+ title={t("Process")}+ />+ {msg.error && (+ <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">+ {msg.error}+ </div>+ )}+ <AssistantResponse+ content={msg.content}+ className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2.5"+ />+ <CapabilityResultPanel result={msg.result} />+ </div>+ )}+ </div>+ ))}++ <div className="flex justify-end">+ <button+ onClick={run}+ disabled={!canRun || streaming}+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40"+ >+ {streaming ? (+ <Loader2 size={13} className="animate-spin" />+ ) : (+ <Play size={13} />+ )}+ {streaming ? t("Running...") : t("Generate")}+ </button>+ </div>+ </div>+ );+}++function DeepResearchTester({+ capability,+ enabledTools,+ knowledgeBase,+ config,+ onConfigChange,+}: {+ capability: CapabilityInfo;+ enabledTools: string[];+ knowledgeBase: string;+ config: DeepResearchFormConfig;+ onConfigChange: (next: DeepResearchFormConfig) => void;+}) {+ const { t, i18n } = useTranslation();+ const [input, setInput] = useState("");+ const [messages, setMessages] = useState<TesterMessage[]>([]);+ const [streaming, setStreaming] = useState(false);+ const validation = useMemo(() => validateResearchConfig(config), [config]);+ const abortRef = useRef<AbortController | null>(null);++ useEffect(+ () => () => {+ abortRef.current?.abort();+ },+ [],+ );++ const updateLastAssistant = (+ updater: (msg: TesterMessage) => TesterMessage,+ ) => {+ setMessages((prev) => {+ const msgs = [...prev];+ const last = msgs[msgs.length - 1];+ if (last?.role !== "assistant") return prev;+ msgs[msgs.length - 1] = updater(last);+ return msgs;+ });+ };++ const run = async () => {+ const content = input.trim();+ if (!content || streaming || !validation.valid) return;++ abortRef.current?.abort();+ const controller = new AbortController();+ abortRef.current = controller;++ setMessages((prev) => [+ ...prev,+ { role: "user", content },+ {+ role: "assistant",+ content: "",+ events: [],+ processLogs: [],+ result: null,+ error: null,+ },+ ]);+ setStreaming(true);++ try {+ const res = await apiFetch(+ apiUrl(+ `/api/v1/plugins/capabilities/${capability.name}/execute-stream`,+ ),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ content,+ tools: enabledTools,+ knowledge_bases:+ config.sources.includes("kb") && knowledgeBase+ ? [knowledgeBase]+ : [],+ language: i18n.language,+ config: buildResearchWSConfig(config),+ }),+ signal: controller.signal,+ },+ );++ if (!res.ok) {+ const data = await res.json().catch(() => null);+ throw new Error(data?.detail || `HTTP ${res.status}`);+ }++ const reader = res.body?.getReader();+ if (!reader) throw new Error("No response body");++ const decoder = new TextDecoder();+ let buffer = "";++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ buffer += decoder.decode(value, { stream: true });+ const parts = buffer.split("\n\n");+ buffer = parts.pop() ?? "";++ for (const part of parts) {+ if (!part.trim()) continue;+ const eventMatch = part.match(/^event:\s*(.+)$/m);+ const dataMatch = part.match(/^data:\s*(.+)$/m);+ if (!eventMatch || !dataMatch) continue;++ const eventType = eventMatch[1].trim();+ let payload: Record<string, unknown>;+ try {+ payload = JSON.parse(dataMatch[1]);+ } catch {+ continue;+ }++ if (eventType === "process_log") {+ const line = (payload.message as string) ?? "";+ updateLastAssistant((last) => ({+ ...last,+ processLogs: [...(last.processLogs || []), line],+ }));+ continue;+ }++ if (eventType === "stream") {+ const event = payload as unknown as StreamEvent;+ if (event.type === "session" || event.type === "done") continue;+ updateLastAssistant((last) => ({+ ...last,+ content:+ event.type === "content"+ ? `${last.content}${event.content}`+ : last.content,+ events: [...(last.events || []), event],+ }));+ continue;+ }++ if (eventType === "result") {+ updateLastAssistant((last) => ({+ ...last,+ result: {+ success: Boolean(payload.success),+ data: (payload.data as Record<string, unknown>) ?? {},+ elapsedMs:+ typeof payload.elapsed_ms === "number"+ ? payload.elapsed_ms+ : undefined,+ },+ }));+ continue;+ }++ if (eventType === "error") {+ updateLastAssistant((last) => ({+ ...last,+ error: (payload.detail as string) ?? "Unknown error",+ }));+ }+ }+ }+ } catch (err: unknown) {+ if (controller.signal.aborted) return;+ updateLastAssistant((last) => ({+ ...last,+ error: err instanceof Error ? err.message : String(err),+ }));+ } finally {+ if (!controller.signal.aborted) setStreaming(false);+ }+ };++ const toggleSource = (source: ResearchSource) => {+ onConfigChange({+ ...config,+ sources: config.sources.includes(source)+ ? config.sources.filter((item) => item !== source)+ : [...config.sources, source],+ });+ };++ return (+ <div className="space-y-4">+ <ResearchConfigPanel+ value={config}+ errors={validation.errors}+ collapsed={false}+ onChange={onConfigChange}+ onToggleCollapsed={() => {}}+ />+ <div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-3">+ <div className="mb-2 text-[12px] font-medium text-[var(--foreground)]">+ {t("Sources")}+ </div>+ <div className="flex flex-wrap gap-2">+ {RESEARCH_SOURCE_OPTIONS.map((source) => {+ const active = config.sources.includes(source.name);+ const Icon = source.icon;+ return (+ <button+ key={source.name}+ type="button"+ onClick={() => toggleSource(source.name)}+ className={`inline-flex h-[32px] items-center gap-1.5 rounded-full px-3 text-[12px] font-medium transition-[background-color,color,box-shadow] ${+ active+ ? "bg-[var(--muted)] text-[var(--foreground)] shadow-[0_1px_2px_rgba(15,23,42,0.05)] ring-1 ring-[var(--border)]/55"+ : "text-[var(--muted-foreground)]/75 hover:bg-[var(--muted)]/55 hover:text-[var(--foreground)]"+ }`}+ >+ <Icon size={13} strokeWidth={1.7} />+ {t(source.label)}+ </button>+ );+ })}+ </div>+ <div className="mt-2 text-[11px] text-[var(--muted-foreground)]">+ {config.sources.length+ ? t("Selected sources will be queried during research.")+ : t("No source selected: the run will use llm-only research.")}+ </div>+ </div>+ <div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-3">+ <textarea+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ run();+ }+ }}+ rows={3}+ placeholder={t("Describe the research topic...")}+ className="w-full resize-none bg-transparent text-[13px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"+ />+ <div className="mt-2 flex justify-end">+ <button+ onClick={run}+ disabled={!input.trim() || streaming || !validation.valid}+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40"+ >+ {streaming ? (+ <Loader2 size={13} className="animate-spin" />+ ) : (+ <Play size={13} />+ )}+ {streaming ? t("Running...") : t("Run Research")}+ </button>+ </div>+ </div>++ {messages.map((msg, i) => (+ <div key={`${msg.role}-${i}`}>+ <div className="mb-1 text-[10px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">+ {msg.role === "user" ? t("You") : t("Assistant")}+ </div>+ {msg.role === "user" ? (+ <div className="rounded-lg bg-[var(--muted)] px-3 py-2 text-[13px] text-[var(--foreground)]">+ {msg.content}+ </div>+ ) : (+ <div className="space-y-2">+ <TracePanel events={msg.events || []} />+ <ProcessLogs+ logs={msg.processLogs || []}+ executing={streaming && i === messages.length - 1}+ title={t("Process")}+ />+ {msg.error && (+ <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">+ {msg.error}+ </div>+ )}+ <AssistantResponse+ content={msg.content}+ className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2.5"+ />+ <CapabilityResultPanel result={msg.result} />+ </div>+ )}+ </div>+ ))}+ </div>+ );+}++/* ------------------------------------------------------------------ */+/* CapabilityTester */+/* ------------------------------------------------------------------ */++function CapabilityTester({+ capability,+ enabledTools,+ knowledgeBase,+}: {+ capability: CapabilityInfo;+ enabledTools: string[];+ knowledgeBase: string;+}) {+ const { t, i18n } = useTranslation();+ const [input, setInput] = useState("");+ const [messages, setMessages] = useState<TesterMessage[]>([]);+ const [streaming, setStreaming] = useState(false);+ const abortRef = useRef<AbortController | null>(null);++ useEffect(+ () => () => {+ abortRef.current?.abort();+ },+ [],+ );++ const updateLastAssistant = (+ updater: (msg: TesterMessage) => TesterMessage,+ ) => {+ setMessages((prev) => {+ const msgs = [...prev];+ const last = msgs[msgs.length - 1];+ if (last?.role !== "assistant") return prev;+ msgs[msgs.length - 1] = updater(last);+ return msgs;+ });+ };++ const send = async () => {+ const content = input.trim();+ if (!content || streaming) return;++ abortRef.current?.abort();+ const controller = new AbortController();+ abortRef.current = controller;++ setMessages((prev) => [+ ...prev,+ { role: "user", content },+ {+ role: "assistant",+ content: "",+ events: [],+ processLogs: [],+ result: null,+ error: null,+ },+ ]);+ setInput("");+ setStreaming(true);++ try {+ const res = await apiFetch(+ apiUrl(+ `/api/v1/plugins/capabilities/${capability.name}/execute-stream`,+ ),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ content,+ tools: enabledTools,+ knowledge_bases:+ enabledTools.includes("rag") && knowledgeBase+ ? [knowledgeBase]+ : [],+ language: i18n.language,+ }),+ signal: controller.signal,+ },+ );++ if (!res.ok) {+ const data = await res.json().catch(() => null);+ throw new Error(data?.detail || `HTTP ${res.status}`);+ }++ const reader = res.body?.getReader();+ if (!reader) throw new Error("No response body");++ const decoder = new TextDecoder();+ let buffer = "";++ while (true) {+ const { done, value } = await reader.read();+ if (done) break;++ buffer += decoder.decode(value, { stream: true });+ const parts = buffer.split("\n\n");+ buffer = parts.pop() ?? "";++ for (const part of parts) {+ if (!part.trim()) continue;+ const eventMatch = part.match(/^event:\s*(.+)$/m);+ const dataMatch = part.match(/^data:\s*(.+)$/m);+ if (!eventMatch || !dataMatch) continue;++ const eventType = eventMatch[1].trim();+ let payload: Record<string, unknown>;+ try {+ payload = JSON.parse(dataMatch[1]);+ } catch {+ continue;+ }++ if (eventType === "process_log") {+ const line = (payload.message as string) ?? "";+ updateLastAssistant((last) => ({+ ...last,+ processLogs: [...(last.processLogs || []), line],+ }));+ continue;+ }++ if (eventType === "stream") {+ const event = payload as unknown as StreamEvent;+ if (event.type === "session" || event.type === "done") continue;+ updateLastAssistant((last) => ({+ ...last,+ content:+ event.type === "content"+ ? `${last.content}${event.content}`+ : last.content,+ events: [...(last.events || []), event],+ }));+ continue;+ }++ if (eventType === "result") {+ updateLastAssistant((last) => ({+ ...last,+ result: {+ success: Boolean(payload.success),+ data: (payload.data as Record<string, unknown>) ?? {},+ elapsedMs:+ typeof payload.elapsed_ms === "number"+ ? payload.elapsed_ms+ : undefined,+ },+ }));+ continue;+ }++ if (eventType === "error") {+ updateLastAssistant((last) => ({+ ...last,+ error: (payload.detail as string) ?? "Unknown error",+ }));+ }+ }+ }+ } catch (err: unknown) {+ if (controller.signal.aborted) return;+ updateLastAssistant((last) => ({+ ...last,+ error: err instanceof Error ? err.message : String(err),+ }));+ } finally {+ if (!controller.signal.aborted) setStreaming(false);+ }+ };++ return (+ <div className="space-y-3">+ {messages.map((msg, i) => (+ <div key={`${msg.role}-${i}`}>+ <div className="mb-1 text-[10px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">+ {msg.role === "user" ? t("You") : t("Assistant")}+ </div>+ {msg.role === "user" ? (+ <div className="rounded-lg bg-[var(--muted)] px-3 py-2 text-[13px] text-[var(--foreground)]">+ {msg.content}+ </div>+ ) : (+ <div className="space-y-2">+ <TracePanel events={msg.events || []} />+ <ProcessLogs+ logs={msg.processLogs || []}+ executing={streaming && i === messages.length - 1}+ title={t("Process")}+ />+ {msg.error && (+ <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">+ {msg.error}+ </div>+ )}+ <AssistantResponse+ content={msg.content}+ className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2.5"+ />+ <CapabilityResultPanel result={msg.result} />+ </div>+ )}+ </div>+ ))}+ <div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-3">+ <textarea+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ send();+ }+ }}+ rows={2}+ placeholder={`${t("Try")} ${t(getCapabilityLabel(capability.name))}...`}+ className="w-full resize-none bg-transparent text-[13px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"+ />+ <div className="mt-2 flex justify-end">+ <button+ onClick={send}+ disabled={!input.trim() || streaming}+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40"+ >+ {streaming ? (+ <Loader2 size={13} className="animate-spin" />+ ) : (+ <Play size={13} />+ )}+ {streaming ? t("Running...") : t("Send")}+ </button>+ </div>+ </div>+ </div>+ );+}++/* ------------------------------------------------------------------ */+/* Main Page */+/* ------------------------------------------------------------------ */++export default function PlaygroundPage() {+ const { t } = useTranslation();+ const [tools, setToolsList] = useState<ToolInfo[]>([]);+ const [capabilities, setCapabilities] = useState<CapabilityInfo[]>([]);+ const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);+ const [capabilityConfigs, setCapabilityConfigs] =+ useState<CapabilityPlaygroundConfigMap>({});+ const [activeKind, setActiveKind] = useState<"tool" | "capability">("tool");+ const [activeName, setActiveName] = useState<string>("");+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ (async () => {+ setLoading(true);+ try {+ const [pluginRes, knowledgeBaseList] = await Promise.all([+ apiFetch(apiUrl("/api/v1/plugins/list")),+ listKnowledgeBases(),+ ]);+ const data = await pluginRes.json();+ const visibleTools = (data.tools || []).filter(+ (tool: ToolInfo) => !FRONTEND_HIDDEN_TOOLS.has(tool.name),+ );+ const visibleCapabilities = (data.capabilities || []).map(+ (cap: CapabilityInfo) => ({+ ...cap,+ tools_used: filterFrontendTools(cap.tools_used ?? []),+ }),+ );++ setToolsList(visibleTools);+ setCapabilities(visibleCapabilities);+ setCapabilityConfigs(loadCapabilityPlaygroundConfigs());+ setKnowledgeBases(knowledgeBaseList);++ if (visibleTools.length) {++ setActiveKind("tool");++ setActiveName(visibleTools[0].name);++ } else if (visibleCapabilities.length) {++ setActiveKind("capability");++ setActiveName(visibleCapabilities[0].name);++ }++ } finally {++ setLoading(false);++ }++ })();++ }, []);++++ const capabilityCatalog = capabilities;++++ const activeTool = tools.find((t) => t.name === activeName);++ const activeCapability = capabilityCatalog.find((c) => c.name === activeName);++ const activeCapabilityConfig = useMemo(++ () =>++ activeCapability++ ? resolveCapabilityPlaygroundConfig(++ capabilityConfigs,++ activeCapability.name,++ activeCapability.tools_used ?? [],++ )++ : null,++ [activeCapability, capabilityConfigs],++ );++ const activeDeepQuestionConfig = useMemo(++ () =>++ normalizeDeepQuestionConfig(++ activeCapabilityConfig?.config as Record<string, unknown> | undefined,++ ),++ [activeCapabilityConfig?.config],++ );++ const activeDeepResearchConfig = useMemo(++ () =>++ normalizeResearchConfig(++ activeCapabilityConfig?.config as Record<string, unknown> | undefined,++ ),++ [activeCapabilityConfig?.config],++ );++ const listItems = useMemo(++ () =>++ activeKind === "tool"++ ? tools.map((t) => ({ name: t.name, description: t.description }))++ : capabilityCatalog.map((c) => ({++ name: c.name,++ description: c.description,++ })),++ [activeKind, capabilityCatalog, tools],++ );++++ const persistCapabilityConfig = (++ capabilityName: string,++ next: CapabilityPlaygroundConfig,++ ) => {++ setCapabilityConfigs((prev) =>++ saveCapabilityPlaygroundConfig(prev, capabilityName, next),++ );++ };++++ const toggleCapabilityTool = (toolName: string) => {++ if (!activeCapability || !activeCapabilityConfig) return;++ const allowedTools = filterFrontendTools(activeCapability.tools_used ?? []);++ if (!allowedTools.includes(toolName)) return;++++ const enabledSet = new Set(activeCapabilityConfig.enabledTools);++ if (enabledSet.has(toolName)) enabledSet.delete(toolName);++ else enabledSet.add(toolName);++++ const defaultKb =++ knowledgeBases.find((kb) => kb.is_default)?.name ??++ knowledgeBases[0]?.name ??++ "";++++ persistCapabilityConfig(activeCapability.name, {++ enabledTools: allowedTools.filter((name) => enabledSet.has(name)),++ knowledgeBase:++ activeCapabilityConfig.knowledgeBase ||++ (enabledSet.has("rag") ? defaultKb : ""),++ config: activeCapabilityConfig.config,++ });++ };++++ const setCapabilityKnowledgeBase = (knowledgeBase: string) => {++ if (!activeCapability || !activeCapabilityConfig) return;++ persistCapabilityConfig(activeCapability.name, {++ enabledTools: activeCapabilityConfig.enabledTools,++ knowledgeBase,++ config: activeCapabilityConfig.config,++ });++ };++++ const setDeepQuestionConfig = (next: DeepQuestionFormConfig) => {++ if (!activeCapability || !activeCapabilityConfig) return;++ persistCapabilityConfig(activeCapability.name, {++ enabledTools: activeCapabilityConfig.enabledTools,++ knowledgeBase: activeCapabilityConfig.knowledgeBase,++ config: next as unknown as Record<string, unknown>,++ });++ };++++ const setDeepResearchConfig = (next: DeepResearchFormConfig) => {++ if (!activeCapability || !activeCapabilityConfig) return;++ persistCapabilityConfig(activeCapability.name, {++ enabledTools: activeCapabilityConfig.enabledTools,++ knowledgeBase: activeCapabilityConfig.knowledgeBase,++ config: next as unknown as Record<string, unknown>,++ });++ };++++ return (++ <div className="min-h-screen bg-[var(--background)]">++ <div className="mx-auto max-w-5xl px-6 py-8">++ <div className="mb-6">++ <h1 className="text-2xl font-bold tracking-tight text-[var(--foreground)]">++ {t("Playground")}++ </h1>++ <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">++ {t(++ "Explore the building blocks of DeepTutor: reusable tools and higher-level capabilities.",++ )}++ </p>++ </div>++++ {loading ? (++ <div className="flex items-center justify-center py-20">++ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />++ </div>++ ) : (++ <div className="space-y-5">++ {/* Tab bar */}++ <div className="inline-flex rounded-lg border border-[var(--border)] bg-[var(--muted)] p-0.5">++ <button++ onClick={() => {++ setActiveKind("tool");++ if (tools.length) setActiveName(tools[0].name);++ }}++ className={`rounded-md px-3.5 py-1.5 text-[13px] font-medium transition-all ${activeKind === "tool" ? "bg-[var(--card)] text-[var(--foreground)] shadow-sm" : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"}`}++ >++ {t("Tools")}++ </button>++ <button++ onClick={() => {++ setActiveKind("capability");++ if (capabilityCatalog.length)++ setActiveName(capabilityCatalog[0].name);++ }}++ className={`rounded-md px-3.5 py-1.5 text-[13px] font-medium transition-all ${activeKind === "capability" ? "bg-[var(--card)] text-[var(--foreground)] shadow-sm" : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"}`}++ >++ {t("Capabilities")}++ </button>++ </div>++++ {/* Two-column layout */}++ <div className="grid gap-5 lg:grid-cols-[280px_1fr]">++ {/* Left: Item list */}++ <section className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 shadow-sm">++ <div className="mb-3 flex items-center gap-1.5">++ {activeKind === "tool" ? (++ <Terminal className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />++ ) : (++ <Sparkles className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />++ )}++ <h2 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">++ {activeKind === "tool" ? t("Tools") : t("Capabilities")}++ </h2>++ </div>++ <div className="space-y-1">++ {listItems.map((item) => {++ const Icon =++ activeKind === "tool"++ ? getToolIcon(item.name)++ : getCapIcon(item.name);++ return (++ <button++ key={item.name}++ onClick={() => setActiveName(item.name)}++ className={`w-full rounded-lg border px-3 py-2.5 text-left transition-all ${++ activeName === item.name++ ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"++ : "border-[var(--border)] bg-[var(--background)] text-[var(--foreground)] hover:border-[var(--foreground)]/10 hover:bg-[var(--muted)]"++ }`}++ >++ <div className="flex items-center gap-1.5">++ <Icon size={13} strokeWidth={1.7} />++ <span className="text-[13px] font-medium">++ {activeKind === "tool"++ ? t(getToolLabel(item.name))++ : t(getCapabilityLabel(item.name))}++ </span>++ </div>++ <div++ className={`mt-0.5 line-clamp-2 text-[11px] leading-relaxed ${activeName === item.name ? "text-[var(--primary-foreground)]/70" : "text-[var(--muted-foreground)]"}`}++ >++ {item.description}++ </div>++ </button>++ );++ })}++ </div>++ </section>++++ {/* Right: Detail panel */}++ <section className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">++ {activeKind === "tool" && activeTool++ ? (() => {++ const ToolIcon = getToolIcon(activeTool.name);++ return (++ <div className="space-y-6">++ <div>++ <div className="flex items-center gap-2 text-[11px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">++ <ToolIcon size={13} strokeWidth={1.7} />++ {t("Tool")}++ </div>++ <h2 className="mt-1 text-xl font-bold tracking-tight text-[var(--foreground)]">++ {t(getToolLabel(activeTool.name))}++ </h2>++ <p className="mt-2 max-w-2xl text-[13px] leading-relaxed text-[var(--muted-foreground)]">++ {activeTool.description}++ </p>++ </div>++++ <div className="border-t border-[var(--border)] pt-6">++ <ToolExecutor++ tool={activeTool}++ knowledgeBases={knowledgeBases}++ />++ </div>++ </div>++ );++ })()++ : activeCapability++ ? (() => {++ const CapIcon = getCapIcon(activeCapability.name);++ return (++ <div className="space-y-6">++ <div>++ <div className="flex items-center gap-2 text-[11px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">++ <CapIcon size={13} strokeWidth={1.7} />++ {t("Capability")}++ </div>++ <h2 className="mt-1 text-xl font-bold tracking-tight text-[var(--foreground)]">++ {t(getCapabilityLabel(activeCapability.name))}++ </h2>++ <p className="mt-2 max-w-2xl text-[13px] leading-relaxed text-[var(--muted-foreground)]">++ {activeCapability.description}++ </p>++ </div>++++ <div>++ <h3 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">++ {t("Enable Tools")}++ </h3>++ {!!activeCapability.tools_used?.length ? (++ <div className="mt-2.5 flex flex-wrap gap-1.5">++ {activeCapability.tools_used.map((tool) => {++ const TIcon = getToolIcon(tool);++ const enabled =++ activeCapabilityConfig?.enabledTools.includes(++ tool,++ ) ?? true;++ return (++ <button++ key={`${activeCapability.name}-${tool}`}++ onClick={() =>++ toggleCapabilityTool(tool)++ }++ className={`inline-flex items-center gap-1 rounded-md border px-2.5 py-1 text-[11px] font-medium transition-colors ${++ enabled++ ? "border-[var(--primary)] bg-[var(--primary)]/10 text-[var(--primary)]"++ : "border-[var(--border)] bg-[var(--background)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"++ }`}++ >++ <TIcon size={11} strokeWidth={1.7} />++ {t(getToolLabel(tool))}++ </button>++ );++ })}++ </div>++ ) : (++ <p className="mt-2 text-[12px] text-[var(--muted-foreground)]">++ {t(++ "This capability runs without optional tools.",++ )}++ </p>++ )}++ </div>++++ {activeCapabilityConfig?.enabledTools.includes(++ "rag",++ ) && (++ <div>++ <h3 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">++ {t("Knowledge Base")}++ </h3>++ <div className="mt-2.5 max-w-sm">++ <select++ value={activeCapabilityConfig.knowledgeBase}++ onChange={(e) =>++ setCapabilityKnowledgeBase(e.target.value)++ }++ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"++ >++ <option value="">++ {t("Select knowledge base...")}++ </option>++ {knowledgeBases.map((kb) => (++ <option key={kb.name} value={kb.name}>++ {kb.name}++ {kb.is_default++ ? ` (${t("default")})`++ : ""}++ </option>++ ))}++ </select>++ </div>++ </div>++ )}++++ <div className="border-t border-[var(--border)] pt-6">++ <div className="mb-3">++ <h3 className="text-[14px] font-semibold text-[var(--foreground)]">++ {t("Try this capability")}++ </h3>++ <p className="mt-0.5 text-[12px] text-[var(--muted-foreground)]">++ {t(++ "Run a focused conversation here without leaving the playground.",++ )}++ </p>++ </div>++ {activeCapability.name === "deep_question" ? (++ <DeepQuestionTester++ key={activeCapability.name}++ capability={activeCapability}++ enabledTools={++ activeCapabilityConfig?.enabledTools ??++ activeCapability.tools_used ??++ []++ }++ knowledgeBase={++ activeCapabilityConfig?.knowledgeBase ?? ""++ }++ config={activeDeepQuestionConfig}++ onConfigChange={setDeepQuestionConfig}++ />++ ) : activeCapability.name === "deep_research" ? (++ <DeepResearchTester++ key={activeCapability.name}++ capability={activeCapability}++ enabledTools={++ activeCapabilityConfig?.enabledTools ??++ activeCapability.tools_used ??++ []++ }++ knowledgeBase={++ activeCapabilityConfig?.knowledgeBase ?? ""++ }++ config={activeDeepResearchConfig}++ onConfigChange={setDeepResearchConfig}++ />++ ) : (++ <CapabilityTester++ key={activeCapability.name}++ capability={activeCapability}++ enabledTools={++ activeCapabilityConfig?.enabledTools ??++ activeCapability.tools_used ??++ []++ }++ knowledgeBase={++ activeCapabilityConfig?.knowledgeBase ?? ""++ }++ />++ )}++ </div>++ </div>++ );++ })()++ : null}++ </section>++ </div>++ </div>++ )}++ </div>++ </div>++ );++}++++function getToolIcon(name: string): LucideIcon {++ return TOOL_ICONS[name] ?? Terminal;++}++++function getCapIcon(name: string): LucideIcon {++ return CAPABILITY_ICONS[name] ?? Sparkles;++}++++function getToolLabel(name: string): string {++ return TOOL_LABELS[name] ?? titleCase(name);++}++++function getCapabilityLabel(name: string): string {++ return CAPABILITY_LABELS[name] ?? titleCase(name);++}++++/* ------------------------------------------------------------------ */++/* Types */++/* ------------------------------------------------------------------ */++++interface ToolParam {++ name: string;++ type: string;++ description?: string;++ required?: boolean;++ default?: unknown;++ enum?: string[] | null;++}++++interface ToolInfo {++ name: string;++ description: string;++ parameters?: ToolParam[];++}++++interface CapabilityInfo {++ name: string;++ description: string;++ stages?: string[];++ tools_used?: string[];++}++++interface ExecResult {++ success: boolean;++ content: string;++ sources: Array<Record<string, string>>;++ metadata: Record<string, unknown>;++}++++interface CapabilityExecResult {++ success: boolean;++ data: Record<string, unknown>;++ elapsedMs?: number;++}++++interface KnowledgeBase {++ name: string;++ is_default?: boolean;++}++++interface TesterMessage {++ role: "user" | "assistant";++ content: string;++ events?: StreamEvent[];++ processLogs?: string[];++ result?: CapabilityExecResult | null;++ error?: string | null;++}++++type DeepQuestionMode = "custom" | "mimic";++++interface DeepQuestionFormConfig {++ mode: DeepQuestionMode;++ topic: string;++ num_questions: number;++ difficulty: string;++ question_type: string;++ preference: string;++ paper_path: string;++ max_questions: number;++}++++/* ------------------------------------------------------------------ */++/* Helpers */++/* ------------------------------------------------------------------ */++++function titleCase(v: string) {++ return v.replaceAll("_", " ").replace(/\b\w/g, (c) => c.toUpperCase());++}++++const QUERY_PARAM_NAMES = new Set(["query", "intent", "code", "topic"]);++++const DEFAULT_DEEP_QUESTION_CONFIG: DeepQuestionFormConfig = {++ mode: "custom",++ topic: "",++ num_questions: 3,++ difficulty: "auto",++ question_type: "auto",++ preference: "",++ paper_path: "",++ max_questions: 10,++};++++function normalizeDeepQuestionConfig(++ raw: Record<string, unknown> | undefined,++): DeepQuestionFormConfig {++ const mode = raw?.mode === "mimic" ? "mimic" : "custom";++ return {++ mode,++ topic: typeof raw?.topic === "string" ? raw.topic : "",++ num_questions:++ typeof raw?.num_questions === "number" && raw.num_questions > 0++ ? raw.num_questions++ : DEFAULT_DEEP_QUESTION_CONFIG.num_questions,++ difficulty:++ typeof raw?.difficulty === "string" && raw.difficulty++ ? raw.difficulty++ : DEFAULT_DEEP_QUESTION_CONFIG.difficulty,++ question_type:++ typeof raw?.question_type === "string" && raw.question_type++ ? raw.question_type++ : DEFAULT_DEEP_QUESTION_CONFIG.question_type,++ preference: typeof raw?.preference === "string" ? raw.preference : "",++ paper_path: typeof raw?.paper_path === "string" ? raw.paper_path : "",++ max_questions:++ typeof raw?.max_questions === "number" && raw.max_questions > 0++ ? raw.max_questions++ : DEFAULT_DEEP_QUESTION_CONFIG.max_questions,++ };++}++++/* ------------------------------------------------------------------ */++/* TracePanel */++/* ------------------------------------------------------------------ */++++function TracePanel({ events }: { events: StreamEvent[] }) {++ const { t } = useTranslation();++ if (!events.length) return null;++++ const grouped = new Map<string, StreamEvent[]>();++ for (const ev of events) {++ const key = ev.stage || "session";++ const list = grouped.get(key) ?? [];++ list.push(ev);++ grouped.set(key, list);++ }++++ return (++ <div className="space-y-2">++ {Array.from(grouped.entries()).map(([stage, stageEvents]) => {++ const renderable = stageEvents.filter((e) =>++ [++ "thinking",++ "progress",++ "tool_call",++ "tool_result",++ "error",++ ].includes(e.type),++ );++ if (!renderable.length) return null;++ return (++ <details++ key={stage}++ className="group overflow-hidden rounded-lg border border-[var(--border)] bg-[var(--card)]"++ >++ <summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-3 py-2 text-[13px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]/50">++ <span>++ {stage === "session" ? t("Details") : titleCase(stage)}++ </span>++ <ChevronDown++ size={13}++ className="text-[var(--muted-foreground)] transition-transform group-open:rotate-180"++ />++ </summary>++ <div className="border-t border-[var(--border)] px-3 py-2.5 space-y-1.5">++ {renderable.map((ev, i) => {++ if (ev.type === "thinking")++ return (++ <p++ key={`${stage}-t-${i}`}++ className="text-[12px] italic leading-relaxed text-[var(--muted-foreground)]"++ >++ {ev.content}++ </p>++ );++ if (ev.type === "progress") {++ const cur = Number(ev.metadata?.current ?? 0),++ tot = Number(ev.metadata?.total ?? 0);++ return (++ <div++ key={`${stage}-p-${i}`}++ className="rounded-md bg-[var(--muted)] px-2.5 py-1.5 text-[12px] text-[var(--muted-foreground)]"++ >++ <div>{ev.content}</div>++ {tot > 0 && (++ <div className="mt-1.5 h-1 overflow-hidden rounded-full bg-[var(--border)]">++ <div++ className="h-full rounded-full bg-[var(--primary)] transition-all duration-300"++ style={{++ width: `${Math.min(100, (cur / tot) * 100)}%`,++ }}++ />++ </div>++ )}++ </div>++ );++ }++ if (ev.type === "tool_call" || ev.type === "tool_result")++ return (++ <div++ key={`${stage}-tc-${i}`}++ className="rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1.5"++ >++ <div className="text-[10px] uppercase tracking-wider text-[var(--muted-foreground)]">++ {ev.type === "tool_call"++ ? t("Tool call")++ : t("Tool result")}++ </div>++ <div className="mt-0.5 text-[12px] text-[var(--foreground)]">++ {ev.content || String(ev.metadata?.tool ?? "")}++ </div>++ </div>++ );++ if (ev.type === "error")++ return (++ <div++ key={`${stage}-e-${i}`}++ className="rounded-md border border-red-200 bg-red-50 px-2.5 py-1.5 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300"++ >++ {ev.content}++ </div>++ );++ return null;++ })}++ </div>++ </details>++ );++ })}++ </div>++ );++}++++/* ------------------------------------------------------------------ */++/* ToolExecutor */++/* ------------------------------------------------------------------ */++++function ToolExecutor({++ tool,++ knowledgeBases,++}: {++ tool: ToolInfo;++ knowledgeBases: KnowledgeBase[];++}) {++ const { t } = useTranslation();++ const params = tool.parameters ?? [];++ const [values, setValues] = useState<Record<string, string>>({});++ const [executing, setExecuting] = useState(false);++ const [result, setResult] = useState<ExecResult | null>(null);++ const [error, setError] = useState<string | null>(null);++ const [processLogs, setProcessLogs] = useState<string[]>([]);++ const abortRef = useRef<AbortController | null>(null);++++ useEffect(() => {++ setValues({});++ setResult(null);++ setError(null);++ setProcessLogs([]);++ }, [tool.name]);++++ useEffect(++ () => () => {++ abortRef.current?.abort();++ },++ [],++ );++++ const setParam = (name: string, val: string) =>++ setValues((p) => ({ ...p, [name]: val }));++++ const queryParam = params.find((p) => QUERY_PARAM_NAMES.has(p.name));++ const otherParams = params.filter((p) => !QUERY_PARAM_NAMES.has(p.name));++++ const execute = async () => {++ abortRef.current?.abort();++ const controller = new AbortController();++ abortRef.current = controller;++ setExecuting(true);++ setResult(null);++ setError(null);++ setProcessLogs([]);++ try {++ const coerced: Record<string, unknown> = {};++ for (const p of params) {++ const raw = values[p.name];++ if (!raw) continue;++ if (p.type === "integer") coerced[p.name] = parseInt(raw, 10);++ else if (p.type === "number") coerced[p.name] = parseFloat(raw);++ else if (p.type === "boolean") coerced[p.name] = raw === "true";++ else coerced[p.name] = raw;++ }++++ const res = await fetch(++ apiUrl(`/api/v1/plugins/tools/${tool.name}/execute-stream`),++ {++ method: "POST",++ headers: { "Content-Type": "application/json" },++ body: JSON.stringify({ params: coerced }),++ signal: controller.signal,++ },++ );++++ if (!res.ok) {++ const data = await res.json().catch(() => null);++ throw new Error(data?.detail || `HTTP ${res.status}`);++ }++++ const reader = res.body?.getReader();++ if (!reader) throw new Error("No response body");++++ const decoder = new TextDecoder();++ let buffer = "";++++ while (true) {++ const { done, value } = await reader.read();++ if (done) break;++++ buffer += decoder.decode(value, { stream: true });++ const parts = buffer.split("\n\n");++ buffer = parts.pop() ?? "";++++ for (const part of parts) {++ if (!part.trim()) continue;++ const eventMatch = part.match(/^event:\s*(.+)$/m);++ const dataMatch = part.match(/^data:\s*(.+)$/m);++ if (!eventMatch || !dataMatch) continue;++++ const eventType = eventMatch[1].trim();++ let payload: Record<string, unknown>;++ try {++ payload = JSON.parse(dataMatch[1]);++ } catch {++ continue;++ }++++ if (eventType === "process_log") {++ const line = (payload.message as string) ?? "";++ setProcessLogs((prev) => [...prev, line]);++ } else if (eventType === "result") {++ setResult({++ success: payload.success as boolean,++ content: (payload.content as string) ?? "",++ sources: (payload.sources as Array<Record<string, string>>) ?? [],++ metadata: (payload.metadata as Record<string, unknown>) ?? {},++ });++ } else if (eventType === "error") {++ setError((payload.detail as string) ?? "Unknown error");++ }++ }++ }++ } catch (err: unknown) {++ if (controller.signal.aborted) return;++ setError(err instanceof Error ? err.message : String(err));++ } finally {++ if (!controller.signal.aborted) setExecuting(false);++ }++ };++++ const isKbNameParam = (p: ToolParam) => p.name === "kb_name";++++ const renderParam = (p: ToolParam) => {++ if (isKbNameParam(p)) {++ return (++ <select++ value={values[p.name] ?? ""}++ onChange={(e) => setParam(p.name, e.target.value)}++ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"++ >++ <option value="">{t("Select knowledge base...")}</option>++ {knowledgeBases.map((kb) => (++ <option key={kb.name} value={kb.name}>++ {kb.name}++ {kb.is_default ? ` (${t("default")})` : ""}++ </option>++ ))}++ </select>++ );++ }++++ if (p.enum) {++ return (++ <select++ value={values[p.name] ?? ""}++ onChange={(e) => setParam(p.name, e.target.value)}++ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"++ >++ <option value="">{t("Select...")}</option>++ {p.enum.map((v) => (++ <option key={v} value={v}>++ {v}++ </option>++ ))}++ </select>++ );++ }++++ return (++ <input++ type={p.type === "integer" || p.type === "number" ? "number" : "text"}++ value={values[p.name] ?? ""}++ onChange={(e) => setParam(p.name, e.target.value)}++ placeholder={p.description || p.name}++ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"++ />++ );++ };++++ return (++ <div className="space-y-5">++ {/* Config params (non-query) */}++ {otherParams.length > 0 && (++ <div>++ <h4 className="mb-2.5 text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">++ {t("Parameters")}++ </h4>++ <div className="grid gap-3 md:grid-cols-2">++ {otherParams.map((p) => (++ <div key={`${tool.name}-${p.name}`}>++ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">++ {p.name}++ {p.required !== false && (++ <span className="ml-0.5 text-[var(--primary)]">*</span>++ )}++ <span className="ml-1.5 text-[10px] font-normal uppercase text-[var(--muted-foreground)]">++ {p.type}++ </span>++ </label>++ {renderParam(p)}++ </div>++ ))}++ </div>++ </div>++ )}++++ {/* Query input — visually distinct */}++ {queryParam && (++ <div className="rounded-xl border-2 border-dashed border-[var(--primary)]/30 bg-[var(--primary)]/[0.03] p-4">++ <label className="mb-2 flex items-center gap-1.5 text-[12px] font-semibold text-[var(--primary)]">++ <Terminal size={13} />++ {queryParam.name === "code" ? t("Code input") : t("Query input")}++ </label>++ {queryParam.name === "code" || queryParam.name === "topic" ? (++ <textarea++ value={values[queryParam.name] ?? ""}++ onChange={(e) => setParam(queryParam.name, e.target.value)}++ placeholder={queryParam.description || t("Enter your input...")}++ rows={queryParam.name === "topic" ? 5 : 4}++ className="w-full resize-none rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 font-mono text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"++ />++ ) : (++ <input++ type="text"++ value={values[queryParam.name] ?? ""}++ onChange={(e) => setParam(queryParam.name, e.target.value)}++ onKeyDown={(e) => {++ if (e.key === "Enter" && !executing) execute();++ }}++ placeholder={queryParam.description || t("Enter your query...")}++ className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"++ />++ )}++ </div>++ )}++++ {/* Execute button */}++ <button++ onClick={execute}++ disabled={executing}++ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-4 py-2 text-[13px] font-medium text-[var(--primary-foreground)] transition-opacity disabled:opacity-50"++ >++ {executing ? (++ <Loader2 size={14} className="animate-spin" />++ ) : (++ <Play size={14} />++ )}++ {executing ? t("Running...") : t("Execute")}++ </button>++++ {/* Process Logs */}++ <ProcessLogs logs={processLogs} executing={executing} />++++ {/* Error */}++ {error && (++ <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">++ {error}++ </div>++ )}++++ {/* Result */}++ {result && (++ <div className="space-y-3">++ <div className="flex items-center gap-2">++ {result.success ? (++ <span className="inline-flex items-center gap-1 rounded-md bg-green-50 px-2 py-0.5 text-[11px] font-medium text-green-700 dark:bg-green-950/30 dark:text-green-400">++ <Check size={10} /> {t("Success")}++ </span>++ ) : (++ <span className="inline-flex items-center gap-1 rounded-md bg-red-50 px-2 py-0.5 text-[11px] font-medium text-red-700 dark:bg-red-950/30 dark:text-red-400">++ <X size={10} /> {t("Failed")}++ </span>++ )}++ </div>++++ {result.content && (++ <div className="max-h-[400px] overflow-y-auto rounded-lg border border-[var(--border)] bg-[var(--background)] p-4">++ <MarkdownRenderer content={result.content} variant="prose" />++ </div>++ )}++++ {result.sources.length > 0 && (++ <details className="group rounded-lg border border-[var(--border)] bg-[var(--card)]">++ <summary className="flex cursor-pointer list-none items-center justify-between px-3 py-2 text-[13px] font-medium text-[var(--foreground)]">++ {t("Sources")} ({result.sources.length})++ <ChevronDown++ size={13}++ className="text-[var(--muted-foreground)] transition-transform group-open:rotate-180"++ />++ </summary>++ <div className="border-t border-[var(--border)] px-3 py-2.5 space-y-1.5">++ {result.sources.map((s, i) => (++ <div++ key={`src-${i}`}++ className="rounded-md bg-[var(--muted)] px-2.5 py-1.5 text-[12px]"++ >++ <div className="font-medium text-[var(--foreground)]">++ {s.title || s.query || s.type || t("Source")}++ </div>++ {s.url && (++ <div className="mt-0.5 break-all text-[11px] text-[var(--muted-foreground)]">++ {s.url}++ </div>++ )}++ </div>++ ))}++ </div>++ </details>++ )}++ </div>++ )}++ </div>++ );++}++++/* ------------------------------------------------------------------ */++/* CapabilityResultPanel */++/* ------------------------------------------------------------------ */++++function CapabilityResultPanel({++ result,++}: {++ result: CapabilityExecResult | null | undefined;++}) {++ const { t } = useTranslation();++ if (!result) return null;++++ const response =++ typeof result.data.response === "string" ? result.data.response : "";++ const extraData = Object.fromEntries(++ Object.entries(result.data).filter(([key]) => key !== "response"),++ );++ const extraKeys = Object.keys(extraData);++++ return (++ <div className="space-y-3">++ <div className="flex items-center gap-2">++ {result.success ? (++ <span className="inline-flex items-center gap-1 rounded-md bg-green-50 px-2 py-0.5 text-[11px] font-medium text-green-700 dark:bg-green-950/30 dark:text-green-400">++ <Check size={10} /> {t("Success")}++ </span>++ ) : (++ <span className="inline-flex items-center gap-1 rounded-md bg-red-50 px-2 py-0.5 text-[11px] font-medium text-red-700 dark:bg-red-950/30 dark:text-red-400">++ <X size={10} /> {t("Failed")}++ </span>++ )}++ {typeof result.elapsedMs === "number" && (++ <span className="text-[11px] text-[var(--muted-foreground)]">++ {result.elapsedMs} ms++ </span>++ )}++ </div>++++ {response && (++ <div className="max-h-[400px] overflow-y-auto rounded-lg border border-[var(--border)] bg-[var(--background)] p-4">++ <MarkdownRenderer content={response} variant="prose" />++ </div>++ )}++++ {!response && extraKeys.length > 0 && (++ <div className="rounded-lg border border-[var(--border)] bg-[var(--background)] p-3">++ <pre className="overflow-x-auto whitespace-pre-wrap break-all text-[12px] text-[var(--muted-foreground)]">++ {JSON.stringify(extraData, null, 2)}++ </pre>++ </div>++ )}++++ {extraKeys.length > 0 && response && (++ <details className="group rounded-lg border border-[var(--border)] bg-[var(--card)]">++ <summary className="flex cursor-pointer list-none items-center justify-between px-3 py-2 text-[13px] font-medium text-[var(--foreground)]">++ {t("Metadata")}++ <ChevronDown++ size={13}++ className="text-[var(--muted-foreground)] transition-transform group-open:rotate-180"++ />++ </summary>++ <div className="border-t border-[var(--border)] px-3 py-2.5">++ <pre className="overflow-x-auto whitespace-pre-wrap break-all text-[12px] text-[var(--muted-foreground)]">++ {JSON.stringify(extraData, null, 2)}++ </pre>++ </div>++ </details>++ )}++ </div>++ );++}++++/* ------------------------------------------------------------------ */++/* DeepQuestionTester */++/* ------------------------------------------------------------------ */++++function DeepQuestionTester({++ capability,++ enabledTools,++ knowledgeBase,++ config,++ onConfigChange,++}: {++ capability: CapabilityInfo;++ enabledTools: string[];++ knowledgeBase: string;++ config: DeepQuestionFormConfig;++ onConfigChange: (next: DeepQuestionFormConfig) => void;++}) {++ const { t, i18n } = useTranslation();++ const [messages, setMessages] = useState<TesterMessage[]>([]);++ const [streaming, setStreaming] = useState(false);++ const [uploadedPdf, setUploadedPdf] = useState<File | null>(null);++ const abortRef = useRef<AbortController | null>(null);++++ useEffect(++ () => () => {++ abortRef.current?.abort();++ },++ [],++ );++++ const updateLastAssistant = (++ updater: (msg: TesterMessage) => TesterMessage,++ ) => {++ setMessages((prev) => {++ const msgs = [...prev];++ const last = msgs[msgs.length - 1];++ if (last?.role !== "assistant") return prev;++ msgs[msgs.length - 1] = updater(last);++ return msgs;++ });++ };++++ const updateConfig = <K extends keyof DeepQuestionFormConfig>(++ key: K,++ value: DeepQuestionFormConfig[K],++ ) => {++ onConfigChange({ ...config, [key]: value });++ };++++ const fileToAttachment = async (file: File) => {++ const dataUrl = await readFileAsDataUrl(file);++ return {++ type: "pdf",++ filename: file.name,++ mime_type: file.type || "application/pdf",++ base64: extractBase64FromDataUrl(dataUrl),++ };++ };++++ const canRun =++ config.mode === "custom"++ ? config.topic.trim().length > 0++ : Boolean(uploadedPdf) || config.paper_path.trim().length > 0;++++ const run = async () => {++ if (!canRun || streaming) return;++++ abortRef.current?.abort();++ const controller = new AbortController();++ abortRef.current = controller;++++ const userContent =++ config.mode === "custom"++ ? config.topic.trim()++ : uploadedPdf++ ? `Mimic questions from uploaded paper: ${uploadedPdf.name}`++ : `Mimic questions from parsed paper: ${config.paper_path.trim()}`;++++ setMessages((prev) => [++ ...prev,++ { role: "user", content: userContent },++ {++ role: "assistant",++ content: "",++ events: [],++ processLogs: [],++ result: null,++ error: null,++ },++ ]);++ setStreaming(true);++++ try {++ const attachments =++ config.mode === "mimic" && uploadedPdf++ ? [await fileToAttachment(uploadedPdf)]++ : [];++++ const requestConfig =++ config.mode === "custom"++ ? {++ mode: "custom",++ topic: config.topic.trim(),++ num_questions: config.num_questions,++ difficulty: config.difficulty === "auto" ? "" : config.difficulty,++ question_type:++ config.question_type === "auto" ? "" : config.question_type,++ preference: config.preference.trim(),++ }++ : {++ mode: "mimic",++ paper_path: uploadedPdf ? "" : config.paper_path.trim(),++ max_questions: config.max_questions,++ };++++ const res = await fetch(++ apiUrl(++ `/api/v1/plugins/capabilities/${capability.name}/execute-stream`,++ ),++ {++ method: "POST",++ headers: { "Content-Type": "application/json" },++ body: JSON.stringify({++ content: userContent,++ tools: enabledTools,++ knowledge_bases:++ enabledTools.includes("rag") && knowledgeBase++ ? [knowledgeBase]++ : [],++ language: i18n.language,++ config: requestConfig,++ attachments,++ }),++ signal: controller.signal,++ },++ );++++ if (!res.ok) {++ const data = await res.json().catch(() => null);++ throw new Error(data?.detail || `HTTP ${res.status}`);++ }++++ const reader = res.body?.getReader();++ if (!reader) throw new Error("No response body");++++ const decoder = new TextDecoder();++ let buffer = "";++++ while (true) {++ const { done, value } = await reader.read();++ if (done) break;++++ buffer += decoder.decode(value, { stream: true });++ const parts = buffer.split("\n\n");++ buffer = parts.pop() ?? "";++++ for (const part of parts) {++ if (!part.trim()) continue;++ const eventMatch = part.match(/^event:\s*(.+)$/m);++ const dataMatch = part.match(/^data:\s*(.+)$/m);++ if (!eventMatch || !dataMatch) continue;++++ const eventType = eventMatch[1].trim();++ let payload: Record<string, unknown>;++ try {++ payload = JSON.parse(dataMatch[1]);++ } catch {++ continue;++ }++++ if (eventType === "process_log") {++ const line = (payload.message as string) ?? "";++ updateLastAssistant((last) => ({++ ...last,++ processLogs: [...(last.processLogs || []), line],++ }));++ continue;++ }++++ if (eventType === "stream") {++ const event = payload as unknown as StreamEvent;++ if (event.type === "session" || event.type === "done") continue;++ updateLastAssistant((last) => ({++ ...last,++ content:++ event.type === "content"++ ? `${last.content}${event.content}`++ : last.content,++ events: [...(last.events || []), event],++ }));++ continue;++ }++++ if (eventType === "result") {++ updateLastAssistant((last) => ({++ ...last,++ result: {++ success: Boolean(payload.success),++ data: (payload.data as Record<string, unknown>) ?? {},++ elapsedMs:++ typeof payload.elapsed_ms === "number"++ ? payload.elapsed_ms++ : undefined,++ },++ }));++ continue;++ }++++ if (eventType === "error") {++ updateLastAssistant((last) => ({++ ...last,++ error: (payload.detail as string) ?? "Unknown error",++ }));++ }++ }++ }++ } catch (err: unknown) {++ if (controller.signal.aborted) return;++ updateLastAssistant((last) => ({++ ...last,++ error: err instanceof Error ? err.message : String(err),++ }));++ } finally {++ if (!controller.signal.aborted) setStreaming(false);++ }++ };++++ return (++ <div className="space-y-4">++ <div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-4">++ <div className="mb-3 flex flex-wrap gap-2">++ <button++ onClick={() => updateConfig("mode", "custom")}++ className={`rounded-lg px-3 py-1.5 text-[12px] font-medium transition-colors ${++ config.mode === "custom"++ ? "bg-[var(--primary)]/10 text-[var(--primary)]"++ : "bg-[var(--muted)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"++ }`}++ >++ {t("Custom")}++ </button>++ <button++ onClick={() => updateConfig("mode", "mimic")}++ className={`rounded-lg px-3 py-1.5 text-[12px] font-medium transition-colors ${++ config.mode === "mimic"++ ? "bg-[var(--primary)]/10 text-[var(--primary)]"++ : "bg-[var(--muted)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"++ }`}++ >++ {t("Mimic Exam")}++ </button>++ </div>++++ {config.mode === "custom" ? (++ <div className="space-y-3">++ <div>++ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">++ {t("Topic")}++ </label>++ <textarea++ value={config.topic}++ onChange={(e) => updateConfig("topic", e.target.value)}++ rows={3}++ placeholder={t("e.g. Gradient Descent Optimization")}++ className="w-full resize-none rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"++ />++ </div>++ <div className="grid gap-3 md:grid-cols-3">++ <div>++ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">++ {t("Count")}++ </label>++ <input++ type="number"++ min={1}++ max={50}++ value={config.num_questions}++ onChange={(e) =>++ updateConfig(++ "num_questions",++ Math.max(1, Number(e.target.value) || 1),++ )++ }++ className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"++ />++ </div>++ <div>++ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">++ {t("Difficulty")}++ </label>++ <select++ value={config.difficulty}++ onChange={(e) => updateConfig("difficulty", e.target.value)}++ className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"++ >++ <option value="auto">{t("Auto")}</option>++ <option value="easy">{t("Easy")}</option>++ <option value="medium">{t("Medium")}</option>++ <option value="hard">{t("Hard")}</option>++ </select>++ </div>++ <div>++ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">++ {t("Type")}++ </label>++ <select++ value={config.question_type}++ onChange={(e) =>++ updateConfig("question_type", e.target.value)++ }++ className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"++ >++ <option value="auto">{t("Auto")}</option>++ <option value="choice">{t("Multiple Choice")}</option>++ <option value="written">{t("Written")}</option>++ <option value="coding">{t("Coding")}</option>++ </select>++ </div>++ </div>++ <div>++ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">++ {t("Preference")}++ </label>++ <textarea++ value={config.preference}++ onChange={(e) => updateConfig("preference", e.target.value)}++ rows={3}++ placeholder={t("Extra constraints, style, focus areas...")}++ className="w-full resize-none rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2.5 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"++ />++ </div>++ </div>++ ) : (++ <div className="space-y-3">++ <div>++ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">++ {t("Upload Exam Paper (PDF)")}++ </label>++ <label className="flex cursor-pointer items-center justify-center gap-2 rounded-xl border-2 border-dashed border-[var(--border)] bg-[var(--card)] px-4 py-6 text-[13px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--primary)]/40 hover:text-[var(--foreground)]">++ <Upload size={16} />++ <span>++ {uploadedPdf ? uploadedPdf.name : t("Click to upload PDF")}++ </span>++ <input++ type="file"++ accept=".pdf,application/pdf"++ className="hidden"++ onChange={(e) => {++ const file = e.target.files?.[0] ?? null;++ setUploadedPdf(file);++ if (file) updateConfig("paper_path", "");++ }}++ />++ </label>++ </div>++ <div className="text-center text-[11px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">++ {t("Or")}++ </div>++ <div>++ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">++ {t("Pre-parsed Directory")}++ </label>++ <div className="relative">++ <FileText++ size={14}++ className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--muted-foreground)]"++ />++ <input++ type="text"++ value={config.paper_path}++ onChange={(e) => {++ setUploadedPdf(null);++ updateConfig("paper_path", e.target.value);++ }}++ placeholder={t("e.g. 2211asm1")}++ className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] py-2 pl-9 pr-3 text-[13px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--primary)]/40 placeholder:text-[var(--muted-foreground)]"++ />++ </div>++ </div>++ <div className="max-w-xs">++ <label className="mb-1 block text-[12px] font-medium text-[var(--foreground)]">++ {t("Max Questions")}++ </label>++ <input++ type="number"++ min={1}++ max={100}++ value={config.max_questions}++ onChange={(e) =>++ updateConfig(++ "max_questions",++ Math.max(1, Number(e.target.value) || 1),++ )++ }++ className="w-full rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"++ />++ </div>++ </div>++ )}++ </div>++++ {messages.map((msg, i) => (++ <div key={`${msg.role}-${i}`}>++ <div className="mb-1 text-[10px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">++ {msg.role === "user" ? t("You") : t("Assistant")}++ </div>++ {msg.role === "user" ? (++ <div className="rounded-lg bg-[var(--muted)] px-3 py-2 text-[13px] text-[var(--foreground)]">++ {msg.content}++ </div>++ ) : (++ <div className="space-y-2">++ <TracePanel events={msg.events || []} />++ <ProcessLogs++ logs={msg.processLogs || []}++ executing={streaming && i === messages.length - 1}++ title={t("Process")}++ />++ {msg.error && (++ <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">++ {msg.error}++ </div>++ )}++ <AssistantResponse++ content={msg.content}++ className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2.5"++ />++ <CapabilityResultPanel result={msg.result} />++ </div>++ )}++ </div>++ ))}++++ <div className="flex justify-end">++ <button++ onClick={run}++ disabled={!canRun || streaming}++ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40"++ >++ {streaming ? (++ <Loader2 size={13} className="animate-spin" />++ ) : (++ <Play size={13} />++ )}++ {streaming ? t("Running...") : t("Generate")}++ </button>++ </div>++ </div>++ );++}++++function DeepResearchTester({++ capability,++ enabledTools,++ knowledgeBase,++ config,++ onConfigChange,++}: {++ capability: CapabilityInfo;++ enabledTools: string[];++ knowledgeBase: string;++ config: DeepResearchFormConfig;++ onConfigChange: (next: DeepResearchFormConfig) => void;++}) {++ const { t, i18n } = useTranslation();++ const [input, setInput] = useState("");++ const [messages, setMessages] = useState<TesterMessage[]>([]);++ const [streaming, setStreaming] = useState(false);++ const validation = useMemo(() => validateResearchConfig(config), [config]);++ const abortRef = useRef<AbortController | null>(null);++++ useEffect(++ () => () => {++ abortRef.current?.abort();++ },++ [],++ );++++ const updateLastAssistant = (++ updater: (msg: TesterMessage) => TesterMessage,++ ) => {++ setMessages((prev) => {++ const msgs = [...prev];++ const last = msgs[msgs.length - 1];++ if (last?.role !== "assistant") return prev;++ msgs[msgs.length - 1] = updater(last);++ return msgs;++ });++ };++++ const run = async () => {++ const content = input.trim();++ if (!content || streaming || !validation.valid) return;++++ abortRef.current?.abort();++ const controller = new AbortController();++ abortRef.current = controller;++++ setMessages((prev) => [++ ...prev,++ { role: "user", content },++ {++ role: "assistant",++ content: "",++ events: [],++ processLogs: [],++ result: null,++ error: null,++ },++ ]);++ setStreaming(true);++++ try {++ const res = await fetch(++ apiUrl(++ `/api/v1/plugins/capabilities/${capability.name}/execute-stream`,++ ),++ {++ method: "POST",++ headers: { "Content-Type": "application/json" },++ body: JSON.stringify({++ content,++ tools: enabledTools,++ knowledge_bases:++ config.sources.includes("kb") && knowledgeBase++ ? [knowledgeBase]++ : [],++ language: i18n.language,++ config: buildResearchWSConfig(config),++ }),++ signal: controller.signal,++ },++ );++++ if (!res.ok) {++ const data = await res.json().catch(() => null);++ throw new Error(data?.detail || `HTTP ${res.status}`);++ }++++ const reader = res.body?.getReader();++ if (!reader) throw new Error("No response body");++++ const decoder = new TextDecoder();++ let buffer = "";++++ while (true) {++ const { done, value } = await reader.read();++ if (done) break;++++ buffer += decoder.decode(value, { stream: true });++ const parts = buffer.split("\n\n");++ buffer = parts.pop() ?? "";++++ for (const part of parts) {++ if (!part.trim()) continue;++ const eventMatch = part.match(/^event:\s*(.+)$/m);++ const dataMatch = part.match(/^data:\s*(.+)$/m);++ if (!eventMatch || !dataMatch) continue;++++ const eventType = eventMatch[1].trim();++ let payload: Record<string, unknown>;++ try {++ payload = JSON.parse(dataMatch[1]);++ } catch {++ continue;++ }++++ if (eventType === "process_log") {++ const line = (payload.message as string) ?? "";++ updateLastAssistant((last) => ({++ ...last,++ processLogs: [...(last.processLogs || []), line],++ }));++ continue;++ }++++ if (eventType === "stream") {++ const event = payload as unknown as StreamEvent;++ if (event.type === "session" || event.type === "done") continue;++ updateLastAssistant((last) => ({++ ...last,++ content:++ event.type === "content"++ ? `${last.content}${event.content}`++ : last.content,++ events: [...(last.events || []), event],++ }));++ continue;++ }++++ if (eventType === "result") {++ updateLastAssistant((last) => ({++ ...last,++ result: {++ success: Boolean(payload.success),++ data: (payload.data as Record<string, unknown>) ?? {},++ elapsedMs:++ typeof payload.elapsed_ms === "number"++ ? payload.elapsed_ms++ : undefined,++ },++ }));++ continue;++ }++++ if (eventType === "error") {++ updateLastAssistant((last) => ({++ ...last,++ error: (payload.detail as string) ?? "Unknown error",++ }));++ }++ }++ }++ } catch (err: unknown) {++ if (controller.signal.aborted) return;++ updateLastAssistant((last) => ({++ ...last,++ error: err instanceof Error ? err.message : String(err),++ }));++ } finally {++ if (!controller.signal.aborted) setStreaming(false);++ }++ };++++ const toggleSource = (source: ResearchSource) => {++ onConfigChange({++ ...config,++ sources: config.sources.includes(source)++ ? config.sources.filter((item) => item !== source)++ : [...config.sources, source],++ });++ };++++ return (++ <div className="space-y-4">++ <ResearchConfigPanel++ value={config}++ errors={validation.errors}++ collapsed={false}++ onChange={onConfigChange}++ onToggleCollapsed={() => {}}++ />++ <div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-3">++ <div className="mb-2 text-[12px] font-medium text-[var(--foreground)]">++ {t("Sources")}++ </div>++ <div className="flex flex-wrap gap-2">++ {RESEARCH_SOURCE_OPTIONS.map((source) => {++ const active = config.sources.includes(source.name);++ const Icon = source.icon;++ return (++ <button++ key={source.name}++ type="button"++ onClick={() => toggleSource(source.name)}++ className={`inline-flex h-[32px] items-center gap-1.5 rounded-full px-3 text-[12px] font-medium transition-[background-color,color,box-shadow] ${++ active++ ? "bg-[var(--muted)] text-[var(--foreground)] shadow-[0_1px_2px_rgba(15,23,42,0.05)] ring-1 ring-[var(--border)]/55"++ : "text-[var(--muted-foreground)]/75 hover:bg-[var(--muted)]/55 hover:text-[var(--foreground)]"++ }`}++ >++ <Icon size={13} strokeWidth={1.7} />++ {t(source.label)}++ </button>++ );++ })}++ </div>++ <div className="mt-2 text-[11px] text-[var(--muted-foreground)]">++ {config.sources.length++ ? t("Selected sources will be queried during research.")++ : t("No source selected: the run will use llm-only research.")}++ </div>++ </div>++ <div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-3">++ <textarea++ value={input}++ onChange={(e) => setInput(e.target.value)}++ onKeyDown={(e) => {++ if (e.key === "Enter" && !e.shiftKey) {++ e.preventDefault();++ run();++ }++ }}++ rows={3}++ placeholder={t("Describe the research topic...")}++ className="w-full resize-none bg-transparent text-[13px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"++ />++ <div className="mt-2 flex justify-end">++ <button++ onClick={run}++ disabled={!input.trim() || streaming || !validation.valid}++ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40"++ >++ {streaming ? (++ <Loader2 size={13} className="animate-spin" />++ ) : (++ <Play size={13} />++ )}++ {streaming ? t("Running...") : t("Run Research")}++ </button>++ </div>++ </div>++++ {messages.map((msg, i) => (++ <div key={`${msg.role}-${i}`}>++ <div className="mb-1 text-[10px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">++ {msg.role === "user" ? t("You") : t("Assistant")}++ </div>++ {msg.role === "user" ? (++ <div className="rounded-lg bg-[var(--muted)] px-3 py-2 text-[13px] text-[var(--foreground)]">++ {msg.content}++ </div>++ ) : (++ <div className="space-y-2">++ <TracePanel events={msg.events || []} />++ <ProcessLogs++ logs={msg.processLogs || []}++ executing={streaming && i === messages.length - 1}++ title={t("Process")}++ />++ {msg.error && (++ <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">++ {msg.error}++ </div>++ )}++ <AssistantResponse++ content={msg.content}++ className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2.5"++ />++ <CapabilityResultPanel result={msg.result} />++ </div>++ )}++ </div>++ ))}++ </div>++ );++}++++/* ------------------------------------------------------------------ */++/* CapabilityTester */++/* ------------------------------------------------------------------ */++++function CapabilityTester({++ capability,++ enabledTools,++ knowledgeBase,++}: {++ capability: CapabilityInfo;++ enabledTools: string[];++ knowledgeBase: string;++}) {++ const { t, i18n } = useTranslation();++ const [input, setInput] = useState("");++ const [messages, setMessages] = useState<TesterMessage[]>([]);++ const [streaming, setStreaming] = useState(false);++ const abortRef = useRef<AbortController | null>(null);++++ useEffect(++ () => () => {++ abortRef.current?.abort();++ },++ [],++ );++++ const updateLastAssistant = (++ updater: (msg: TesterMessage) => TesterMessage,++ ) => {++ setMessages((prev) => {++ const msgs = [...prev];++ const last = msgs[msgs.length - 1];++ if (last?.role !== "assistant") return prev;++ msgs[msgs.length - 1] = updater(last);++ return msgs;++ });++ };++++ const send = async () => {++ const content = input.trim();++ if (!content || streaming) return;++++ abortRef.current?.abort();++ const controller = new AbortController();++ abortRef.current = controller;++++ setMessages((prev) => [++ ...prev,++ { role: "user", content },++ {++ role: "assistant",++ content: "",++ events: [],++ processLogs: [],++ result: null,++ error: null,++ },++ ]);++ setInput("");++ setStreaming(true);++++ try {++ const res = await fetch(++ apiUrl(++ `/api/v1/plugins/capabilities/${capability.name}/execute-stream`,++ ),++ {++ method: "POST",++ headers: { "Content-Type": "application/json" },++ body: JSON.stringify({++ content,++ tools: enabledTools,++ knowledge_bases:++ enabledTools.includes("rag") && knowledgeBase++ ? [knowledgeBase]++ : [],++ language: i18n.language,++ }),++ signal: controller.signal,++ },++ );++++ if (!res.ok) {++ const data = await res.json().catch(() => null);++ throw new Error(data?.detail || `HTTP ${res.status}`);++ }++++ const reader = res.body?.getReader();++ if (!reader) throw new Error("No response body");++++ const decoder = new TextDecoder();++ let buffer = "";++++ while (true) {++ const { done, value } = await reader.read();++ if (done) break;++++ buffer += decoder.decode(value, { stream: true });++ const parts = buffer.split("\n\n");++ buffer = parts.pop() ?? "";++++ for (const part of parts) {++ if (!part.trim()) continue;++ const eventMatch = part.match(/^event:\s*(.+)$/m);++ const dataMatch = part.match(/^data:\s*(.+)$/m);++ if (!eventMatch || !dataMatch) continue;++++ const eventType = eventMatch[1].trim();++ let payload: Record<string, unknown>;++ try {++ payload = JSON.parse(dataMatch[1]);++ } catch {++ continue;++ }++++ if (eventType === "process_log") {++ const line = (payload.message as string) ?? "";++ updateLastAssistant((last) => ({++ ...last,++ processLogs: [...(last.processLogs || []), line],++ }));++ continue;++ }++++ if (eventType === "stream") {++ const event = payload as unknown as StreamEvent;++ if (event.type === "session" || event.type === "done") continue;++ updateLastAssistant((last) => ({++ ...last,++ content:++ event.type === "content"++ ? `${last.content}${event.content}`++ : last.content,++ events: [...(last.events || []), event],++ }));++ continue;++ }++++ if (eventType === "result") {++ updateLastAssistant((last) => ({++ ...last,++ result: {++ success: Boolean(payload.success),++ data: (payload.data as Record<string, unknown>) ?? {},++ elapsedMs:++ typeof payload.elapsed_ms === "number"++ ? payload.elapsed_ms++ : undefined,++ },++ }));++ continue;++ }++++ if (eventType === "error") {++ updateLastAssistant((last) => ({++ ...last,++ error: (payload.detail as string) ?? "Unknown error",++ }));++ }++ }++ }++ } catch (err: unknown) {++ if (controller.signal.aborted) return;++ updateLastAssistant((last) => ({++ ...last,++ error: err instanceof Error ? err.message : String(err),++ }));++ } finally {++ if (!controller.signal.aborted) setStreaming(false);++ }++ };++++ return (++ <div className="space-y-3">++ {messages.map((msg, i) => (++ <div key={`${msg.role}-${i}`}>++ <div className="mb-1 text-[10px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">++ {msg.role === "user" ? t("You") : t("Assistant")}++ </div>++ {msg.role === "user" ? (++ <div className="rounded-lg bg-[var(--muted)] px-3 py-2 text-[13px] text-[var(--foreground)]">++ {msg.content}++ </div>++ ) : (++ <div className="space-y-2">++ <TracePanel events={msg.events || []} />++ <ProcessLogs++ logs={msg.processLogs || []}++ executing={streaming && i === messages.length - 1}++ title={t("Process")}++ />++ {msg.error && (++ <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-[13px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">++ {msg.error}++ </div>++ )}++ <AssistantResponse++ content={msg.content}++ className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2.5"++ />++ <CapabilityResultPanel result={msg.result} />++ </div>++ )}++ </div>++ ))}++ <div className="rounded-xl border border-[var(--border)] bg-[var(--background)] p-3">++ <textarea++ value={input}++ onChange={(e) => setInput(e.target.value)}++ onKeyDown={(e) => {++ if (e.key === "Enter" && !e.shiftKey) {++ e.preventDefault();++ send();++ }++ }}++ rows={2}++ placeholder={`${t("Try")} ${t(getCapabilityLabel(capability.name))}...`}++ className="w-full resize-none bg-transparent text-[13px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]"++ />++ <div className="mt-2 flex justify-end">++ <button++ onClick={send}++ disabled={!input.trim() || streaming}++ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40"++ >++ {streaming ? (++ <Loader2 size={13} className="animate-spin" />++ ) : (++ <Play size={13} />++ )}++ {streaming ? t("Running...") : t("Send")}++ </button>++ </div>++ </div>++ </div>++ );++}++++/* ------------------------------------------------------------------ */++/* Main Page */++/* ------------------------------------------------------------------ */++++export default function PlaygroundPage() {++ const { t } = useTranslation();++ const [tools, setToolsList] = useState<ToolInfo[]>([]);++ const [capabilities, setCapabilities] = useState<CapabilityInfo[]>([]);++ const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);++ const [capabilityConfigs, setCapabilityConfigs] =++ useState<CapabilityPlaygroundConfigMap>({});++ const [activeKind, setActiveKind] = useState<"tool" | "capability">("tool");++ const [activeName, setActiveName] = useState<string>("");++ const [loading, setLoading] = useState(true);++++ useEffect(() => {++ (async () => {++ setLoading(true);++ try {++ const [pluginRes, knowledgeBaseList] = await Promise.all([++ fetch(apiUrl("/api/v1/plugins/list")),++ listKnowledgeBases(),++ ]);++ const data = await pluginRes.json();++ const visibleTools = (data.tools || []).filter(++ (tool: ToolInfo) => !FRONTEND_HIDDEN_TOOLS.has(tool.name),++ );++ const visibleCapabilities = (data.capabilities || []).map(++ (cap: CapabilityInfo) => ({++ ...cap,++ tools_used: filterFrontendTools(cap.tools_used ?? []),++ }),++ );++++ setToolsList(visibleTools);++ setCapabilities(visibleCapabilities);++ setCapabilityConfigs(loadCapabilityPlaygroundConfigs());++ setKnowledgeBases(knowledgeBaseList);++++ if (visibleTools.length) {+ setActiveKind("tool");+ setActiveName(visibleTools[0].name);+ } else if (visibleCapabilities.length) {+ setActiveKind("capability");+ setActiveName(visibleCapabilities[0].name);+ }+ } finally {+ setLoading(false);+ }+ })();+ }, []);++ const capabilityCatalog = capabilities;++ const activeTool = tools.find((t) => t.name === activeName);+ const activeCapability = capabilityCatalog.find((c) => c.name === activeName);+ const activeCapabilityConfig = useMemo(+ () =>+ activeCapability+ ? resolveCapabilityPlaygroundConfig(+ capabilityConfigs,+ activeCapability.name,+ activeCapability.tools_used ?? [],+ )+ : null,+ [activeCapability, capabilityConfigs],+ );+ const activeDeepQuestionConfig = useMemo(+ () =>+ normalizeDeepQuestionConfig(+ activeCapabilityConfig?.config as Record<string, unknown> | undefined,+ ),+ [activeCapabilityConfig?.config],+ );+ const activeDeepResearchConfig = useMemo(+ () =>+ normalizeResearchConfig(+ activeCapabilityConfig?.config as Record<string, unknown> | undefined,+ ),+ [activeCapabilityConfig?.config],+ );+ const listItems = useMemo(+ () =>+ activeKind === "tool"+ ? tools.map((t) => ({ name: t.name, description: t.description }))+ : capabilityCatalog.map((c) => ({+ name: c.name,+ description: c.description,+ })),+ [activeKind, capabilityCatalog, tools],+ );++ const persistCapabilityConfig = (+ capabilityName: string,+ next: CapabilityPlaygroundConfig,+ ) => {+ setCapabilityConfigs((prev) =>+ saveCapabilityPlaygroundConfig(prev, capabilityName, next),+ );+ };++ const toggleCapabilityTool = (toolName: string) => {+ if (!activeCapability || !activeCapabilityConfig) return;+ const allowedTools = filterFrontendTools(activeCapability.tools_used ?? []);+ if (!allowedTools.includes(toolName)) return;++ const enabledSet = new Set(activeCapabilityConfig.enabledTools);+ if (enabledSet.has(toolName)) enabledSet.delete(toolName);+ else enabledSet.add(toolName);++ const defaultKb =+ knowledgeBases.find((kb) => kb.is_default)?.name ??+ knowledgeBases[0]?.name ??+ "";++ persistCapabilityConfig(activeCapability.name, {+ enabledTools: allowedTools.filter((name) => enabledSet.has(name)),+ knowledgeBase:+ activeCapabilityConfig.knowledgeBase ||+ (enabledSet.has("rag") ? defaultKb : ""),+ config: activeCapabilityConfig.config,+ });+ };++ const setCapabilityKnowledgeBase = (knowledgeBase: string) => {+ if (!activeCapability || !activeCapabilityConfig) return;+ persistCapabilityConfig(activeCapability.name, {+ enabledTools: activeCapabilityConfig.enabledTools,+ knowledgeBase,+ config: activeCapabilityConfig.config,+ });+ };++ const setDeepQuestionConfig = (next: DeepQuestionFormConfig) => {+ if (!activeCapability || !activeCapabilityConfig) return;+ persistCapabilityConfig(activeCapability.name, {+ enabledTools: activeCapabilityConfig.enabledTools,+ knowledgeBase: activeCapabilityConfig.knowledgeBase,+ config: next as unknown as Record<string, unknown>,+ });+ };++ const setDeepResearchConfig = (next: DeepResearchFormConfig) => {+ if (!activeCapability || !activeCapabilityConfig) return;+ persistCapabilityConfig(activeCapability.name, {+ enabledTools: activeCapabilityConfig.enabledTools,+ knowledgeBase: activeCapabilityConfig.knowledgeBase,+ config: next as unknown as Record<string, unknown>,+ });+ };++ return (+ <div className="min-h-screen bg-[var(--background)]">+ <div className="mx-auto max-w-5xl px-6 py-8">+ <div className="mb-6">+ <h1 className="text-2xl font-bold tracking-tight text-[var(--foreground)]">+ {t("Playground")}+ </h1>+ <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">+ {t(+ "Explore the building blocks of DeepTutor: reusable tools and higher-level capabilities.",+ )}+ </p>+ </div>++ {loading ? (+ <div className="flex items-center justify-center py-20">+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />+ </div>+ ) : (+ <div className="space-y-5">+ {/* Tab bar */}+ <div className="inline-flex rounded-lg border border-[var(--border)] bg-[var(--muted)] p-0.5">+ <button+ onClick={() => {+ setActiveKind("tool");+ if (tools.length) setActiveName(tools[0].name);+ }}+ className={`rounded-md px-3.5 py-1.5 text-[13px] font-medium transition-all ${activeKind === "tool" ? "bg-[var(--card)] text-[var(--foreground)] shadow-sm" : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"}`}+ >+ {t("Tools")}+ </button>+ <button+ onClick={() => {+ setActiveKind("capability");+ if (capabilityCatalog.length)+ setActiveName(capabilityCatalog[0].name);+ }}+ className={`rounded-md px-3.5 py-1.5 text-[13px] font-medium transition-all ${activeKind === "capability" ? "bg-[var(--card)] text-[var(--foreground)] shadow-sm" : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"}`}+ >+ {t("Capabilities")}+ </button>+ </div>++ {/* Two-column layout */}+ <div className="grid gap-5 lg:grid-cols-[280px_1fr]">+ {/* Left: Item list */}+ <section className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 shadow-sm">+ <div className="mb-3 flex items-center gap-1.5">+ {activeKind === "tool" ? (+ <Terminal className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />+ ) : (+ <Sparkles className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />+ )}+ <h2 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">+ {activeKind === "tool" ? t("Tools") : t("Capabilities")}+ </h2>+ </div>+ <div className="space-y-1">+ {listItems.map((item) => {+ const Icon =+ activeKind === "tool"+ ? getToolIcon(item.name)+ : getCapIcon(item.name);+ return (+ <button+ key={item.name}+ onClick={() => setActiveName(item.name)}+ className={`w-full rounded-lg border px-3 py-2.5 text-left transition-all ${+ activeName === item.name+ ? "border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]"+ : "border-[var(--border)] bg-[var(--background)] text-[var(--foreground)] hover:border-[var(--foreground)]/10 hover:bg-[var(--muted)]"+ }`}+ >+ <div className="flex items-center gap-1.5">+ <Icon size={13} strokeWidth={1.7} />+ <span className="text-[13px] font-medium">+ {activeKind === "tool"+ ? t(getToolLabel(item.name))+ : t(getCapabilityLabel(item.name))}+ </span>+ </div>+ <div+ className={`mt-0.5 line-clamp-2 text-[11px] leading-relaxed ${activeName === item.name ? "text-[var(--primary-foreground)]/70" : "text-[var(--muted-foreground)]"}`}+ >+ {item.description}+ </div>+ </button>+ );+ })}+ </div>+ </section>++ {/* Right: Detail panel */}+ <section className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">+ {activeKind === "tool" && activeTool+ ? (() => {+ const ToolIcon = getToolIcon(activeTool.name);+ return (+ <div className="space-y-6">+ <div>+ <div className="flex items-center gap-2 text-[11px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">+ <ToolIcon size={13} strokeWidth={1.7} />+ {t("Tool")}+ </div>+ <h2 className="mt-1 text-xl font-bold tracking-tight text-[var(--foreground)]">+ {t(getToolLabel(activeTool.name))}+ </h2>+ <p className="mt-2 max-w-2xl text-[13px] leading-relaxed text-[var(--muted-foreground)]">+ {activeTool.description}+ </p>+ </div>++ <div className="border-t border-[var(--border)] pt-6">+ <ToolExecutor+ tool={activeTool}+ knowledgeBases={knowledgeBases}+ />+ </div>+ </div>+ );+ })()+ : activeCapability+ ? (() => {+ const CapIcon = getCapIcon(activeCapability.name);+ return (+ <div className="space-y-6">+ <div>+ <div className="flex items-center gap-2 text-[11px] uppercase tracking-[0.12em] text-[var(--muted-foreground)]">+ <CapIcon size={13} strokeWidth={1.7} />+ {t("Capability")}+ </div>+ <h2 className="mt-1 text-xl font-bold tracking-tight text-[var(--foreground)]">+ {t(getCapabilityLabel(activeCapability.name))}+ </h2>+ <p className="mt-2 max-w-2xl text-[13px] leading-relaxed text-[var(--muted-foreground)]">+ {activeCapability.description}+ </p>+ </div>++ <div>+ <h3 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">+ {t("Enable Tools")}+ </h3>+ {!!activeCapability.tools_used?.length ? (+ <div className="mt-2.5 flex flex-wrap gap-1.5">+ {activeCapability.tools_used.map((tool) => {+ const TIcon = getToolIcon(tool);+ const enabled =+ activeCapabilityConfig?.enabledTools.includes(+ tool,+ ) ?? true;+ return (+ <button+ key={`${activeCapability.name}-${tool}`}+ onClick={() =>+ toggleCapabilityTool(tool)+ }+ className={`inline-flex items-center gap-1 rounded-md border px-2.5 py-1 text-[11px] font-medium transition-colors ${+ enabled+ ? "border-[var(--primary)] bg-[var(--primary)]/10 text-[var(--primary)]"+ : "border-[var(--border)] bg-[var(--background)] text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ <TIcon size={11} strokeWidth={1.7} />+ {t(getToolLabel(tool))}+ </button>+ );+ })}+ </div>+ ) : (+ <p className="mt-2 text-[12px] text-[var(--muted-foreground)]">+ {t(+ "This capability runs without optional tools.",+ )}+ </p>+ )}+ </div>++ {activeCapabilityConfig?.enabledTools.includes(+ "rag",+ ) && (+ <div>+ <h3 className="text-[11px] font-semibold uppercase tracking-[0.12em] text-[var(--muted-foreground)]">+ {t("Knowledge Base")}+ </h3>+ <div className="mt-2.5 max-w-sm">+ <select+ value={activeCapabilityConfig.knowledgeBase}+ onChange={(e) =>+ setCapabilityKnowledgeBase(e.target.value)+ }+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]/40"+ >+ <option value="">+ {t("Select knowledge base...")}+ </option>+ {knowledgeBases.map((kb) => (+ <option key={kb.name} value={kb.name}>+ {kb.name}+ {kb.is_default+ ? ` (${t("default")})`+ : ""}+ </option>+ ))}+ </select>+ </div>+ </div>+ )}++ <div className="border-t border-[var(--border)] pt-6">+ <div className="mb-3">+ <h3 className="text-[14px] font-semibold text-[var(--foreground)]">+ {t("Try this capability")}+ </h3>+ <p className="mt-0.5 text-[12px] text-[var(--muted-foreground)]">+ {t(+ "Run a focused conversation here without leaving the playground.",+ )}+ </p>+ </div>+ {activeCapability.name === "deep_question" ? (+ <DeepQuestionTester+ key={activeCapability.name}+ capability={activeCapability}+ enabledTools={+ activeCapabilityConfig?.enabledTools ??+ activeCapability.tools_used ??+ []+ }+ knowledgeBase={+ activeCapabilityConfig?.knowledgeBase ?? ""+ }+ config={activeDeepQuestionConfig}+ onConfigChange={setDeepQuestionConfig}+ />+ ) : activeCapability.name === "deep_research" ? (+ <DeepResearchTester+ key={activeCapability.name}+ capability={activeCapability}+ enabledTools={+ activeCapabilityConfig?.enabledTools ??+ activeCapability.tools_used ??+ []+ }+ knowledgeBase={+ activeCapabilityConfig?.knowledgeBase ?? ""+ }+ config={activeDeepResearchConfig}+ onConfigChange={setDeepResearchConfig}+ />+ ) : (+ <CapabilityTester+ key={activeCapability.name}+ capability={activeCapability}+ enabledTools={+ activeCapabilityConfig?.enabledTools ??+ activeCapability.tools_used ??+ []+ }+ knowledgeBase={+ activeCapabilityConfig?.knowledgeBase ?? ""+ }+ />+ )}+ </div>+ </div>+ );+ })()+ : null}+ </section>+ </div>+ </div>+ )}+ </div>+ </div>+ );+}diff --cc web/components/chat/home/ChatMessages.tsxindex 9b0aedcb3,893e9824f..4ea45ba65--- a/web/components/chat/home/ChatMessages.tsx+++ b/web/components/chat/home/ChatMessages.tsx@@@ -1,1113 -1,845 +1,1958 @@@-"use client";--import dynamic from "next/dynamic";-import { memo, useCallback, useMemo, useState } from "react";-import {- BookOpen,- Brain,- ClipboardList,- Coins,- Copy,- MessageSquare,- RefreshCcw,- Wand2,- X,- Zap,- type LucideIcon,-} from "lucide-react";-import { useTranslation } from "react-i18next";-import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";-import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";-import AssistantResponse from "@/components/common/AssistantResponse";-import type {- MessageAttachment,- MessageRequestSnapshot,-} from "@/context/UnifiedChatContext";-import { apiUrl } from "@/lib/api";-import { docIconFor } from "@/lib/doc-attachments";-import { extractMathAnimatorResult } from "@/lib/math-animator-types";-import { extractQuizQuestions } from "@/lib/quiz-types";-import { extractVisualizeResult } from "@/lib/visualize-types";-import type { StreamEvent } from "@/lib/unified-ws";-import { hasVisibleMarkdownContent } from "@/lib/markdown-display";-import type { SelectedBookReference } from "@/lib/book-references";-import type { SpaceMemoryFile } from "@/lib/space-items";-import { CallTracePanel } from "./TracePanels";--const MathAnimatorViewer = dynamic(- () => import("@/components/math-animator/MathAnimatorViewer"),- { ssr: false },-);-const QuizViewer = dynamic(() => import("@/components/quiz/QuizViewer"), {- ssr: false,-});-const ResearchOutlineEditor = dynamic(- () => import("@/components/research/ResearchOutlineEditor"),- { ssr: false },-);-const VisualizationViewer = dynamic(- () => import("@/components/visualize/VisualizationViewer"),- { ssr: false },-);--interface ChatMessageItem {- role: "user" | "assistant" | "system";- content: string;- capability?: string;- events?: StreamEvent[];- attachments?: MessageAttachment[];- requestSnapshot?: MessageRequestSnapshot;-}--interface NotebookReferenceGroup {- notebookId: string;- notebookName: string;- count: number;-}--// Returns the i18n key (and a sensible fallback) for the capability badge-// shown above the user's message. Callers must run `t(...)` on the result.-function getModeBadgeLabel(capability?: string | null): string {- if (!capability || capability === "chat") return "Chat";- if (capability === "deep_solve") return "Deep Solve";- if (capability === "deep_question") return "Quiz Generation";- if (capability === "deep_research") return "Deep Research";- if (capability === "math_animator") return "Math Animator";+"use client";++import dynamic from "next/dynamic";+import { memo, useCallback, useMemo, useState } from "react";+import {+ BookOpen,+ Brain,+ ChevronLeft,+ ChevronRight,+ ClipboardList,+ Coins,+ Copy,+ MessageSquare,+ Pencil,+ RefreshCcw,+ Wand2,+ X,+ Trash2,+ Zap,+ type LucideIcon,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";+import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";+import AssistantResponse from "@/components/common/AssistantResponse";+import type {+ MessageAttachment,+ MessageRequestSnapshot,+} from "@/context/UnifiedChatContext";+import { apiUrl } from "@/lib/api";+import { docIconFor } from "@/lib/doc-attachments";+import { extractMathAnimatorResult } from "@/lib/math-animator-types";+import { extractQuizQuestions } from "@/lib/quiz-types";+import { extractVisualizeResult } from "@/lib/visualize-types";+import type { StreamEvent } from "@/lib/unified-ws";+import { hasVisibleMarkdownContent } from "@/lib/markdown-display";+import type { SelectedBookReference } from "@/lib/book-references";+import {+ buildVisiblePath,+ type SiblingInfo,+} from "@/lib/message-branches";+import type { SpaceMemoryFile } from "@/lib/space-items";+import AutoModeAssistantMessage from "./AutoModeAssistantMessage";+import { TraceSurface } from "./TracePanels";++const MathAnimatorViewer = dynamic(+ () => import("@/components/math-animator/MathAnimatorViewer"),+ { ssr: false },+);+const QuizViewer = dynamic(() => import("@/components/quiz/QuizViewer"), {+ ssr: false,+});+const ResearchOutlineEditor = dynamic(+ () => import("@/components/research/ResearchOutlineEditor"),+ { ssr: false },+);+const VisualizationViewer = dynamic(+ () => import("@/components/visualize/VisualizationViewer"),+ { ssr: false },+);++interface ChatMessageItem {+ id?: number;+ role: "user" | "assistant" | "system";+ content: string;+ capability?: string;+ events?: StreamEvent[];+ attachments?: MessageAttachment[];+ requestSnapshot?: MessageRequestSnapshot;+ parentMessageId?: number | null;+}++interface NotebookReferenceGroup {+ notebookId: string;+ notebookName: string;+ count: number;+}++// Returns the i18n key (and a sensible fallback) for the capability badge+// shown above the user's message. Callers must run `t(...)` on the result.+function getModeBadgeLabel(capability?: string | null): string {+ if (!capability || capability === "chat") return "Chat";+ if (capability === "deep_solve") return "Deep Solve";+ if (capability === "deep_question") return "Quiz Generation";+ if (capability === "deep_research") return "Deep Research";+ if (capability === "math_animator") return "Math Animator";if (capability === "visualize") return "Visualize";return capability;-}--function imageSrcForAttachment(attachment: MessageAttachment): string | null {- if (attachment.url) {- if (- attachment.url.startsWith("http") ||- attachment.url.startsWith("blob:") ||- attachment.url.startsWith("data:")- ) {- return attachment.url;- }- return apiUrl(attachment.url);- }-- const base64 = attachment.base64?.trim();- if (!base64) return null;- if (base64.startsWith("data:")) return base64;- return `data:${attachment.mime_type || "image/png"};base64,${base64}`;-}--const AssistantMessage = memo(function AssistantMessage({- msg,- isStreaming,- outlineStatus,- sessionId,- language,- onConfirmOutline,- onAnswerNow,-}: {- msg: { content: string; capability?: string; events?: StreamEvent[] };- isStreaming?: boolean;- outlineStatus?: "editing" | "researching" | "done";- sessionId?: string | null;- language?: string;- onConfirmOutline?: (- outline: Array<{ title: string; overview: string }>,- topic: string,- researchConfig?: Record<string, unknown> | null,- ) => void;- onAnswerNow?: () => void;-}) {- const events = useMemo(() => msg.events ?? [], [msg.events]);- const hasCallTrace = useMemo(- () => events.some((event) => Boolean(event.metadata?.call_id)),- [events],- );- const resultEvent = useMemo(- () => msg.events?.find((event) => event.type === "result") ?? null,- [msg.events],- );-- const outlinePreview = useMemo(() => {- if (msg.capability !== "deep_research" || !resultEvent) return null;- const meta = resultEvent.metadata as Record<string, unknown> | undefined;- if (!meta?.outline_preview) return null;- return {- sub_topics: (meta.sub_topics ?? []) as Array<{- title: string;- overview: string;- }>,- topic: String(meta.topic ?? ""),- research_config: (meta.research_config ?? null) as Record<- string,- unknown- > | null,- };- }, [msg.capability, resultEvent]);-- const quizQuestions = useMemo(() => {- if (msg.capability !== "deep_question" || !resultEvent) return null;- return extractQuizQuestions(resultEvent.metadata);- }, [msg.capability, resultEvent]);-- const mathAnimatorResult = useMemo(() => {- if (msg.capability !== "math_animator" || !resultEvent) return null;- return extractMathAnimatorResult(resultEvent.metadata);- }, [msg.capability, resultEvent]);-- const visualizeResult = useMemo(() => {- if (msg.capability !== "visualize" || !resultEvent) return null;- return extractVisualizeResult(resultEvent.metadata);- }, [msg.capability, resultEvent]);-- return (- <>- {hasCallTrace ? (- <CallTracePanel events={events} isStreaming={isStreaming} />- ) : null}- {isStreaming && onAnswerNow ? (- <AnswerNowRow onAnswerNow={onAnswerNow} />- ) : null}- {outlinePreview && outlinePreview.sub_topics.length > 0 ? (- <ResearchOutlineEditor- outline={outlinePreview.sub_topics}- topic={outlinePreview.topic}- onConfirm={(items) =>- onConfirmOutline?.(- items,- outlinePreview.topic,- outlinePreview.research_config,- )- }- status={outlineStatus}- />- ) : mathAnimatorResult ? (- <MathAnimatorViewer result={mathAnimatorResult} />- ) : visualizeResult ? (- <VisualizationViewer result={visualizeResult} />- ) : quizQuestions && quizQuestions.length > 0 ? (- <QuizViewer- questions={quizQuestions}- sessionId={sessionId}- language={language}- />- ) : (- <AssistantResponse content={msg.content} />- )}- </>- );-});--AssistantMessage.displayName = "AssistantMessage";--/**- * Inline "Answer now" affordance shown alongside the active assistant turn.- * Lives outside the trace panel so it is visible as soon as the turn starts- * — i.e. even before any tool / reasoning trace has been emitted, which is- * the common case for the very first user message.- */-const AnswerNowRow = memo(function AnswerNowRow({- onAnswerNow,-}: {- onAnswerNow: () => void;-}) {- const { t } = useTranslation();- // Local single-shot guard: once the user has fired "answer now" we lock- // the button so a second click can't queue a duplicate cancel + restart- // race against the in-flight synthesis turn. The next assistant turn- // mounts a fresh ``AnswerNowRow`` with its own state, so this naturally- // resets per turn without any external bookkeeping.- const [triggered, setTriggered] = useState(false);- const handleClick = useCallback(() => {- if (triggered) return;- setTriggered(true);- onAnswerNow();- }, [triggered, onAnswerNow]);-- return (- <div className="mt-1.5 mb-3 flex items-center">- <button- type="button"- onClick={handleClick}- disabled={triggered}- title={t("Skip reasoning and answer now")}- aria-disabled={triggered}- className="group inline-flex items-center gap-1.5 rounded-md border border-[var(--border)]/60 bg-[var(--card)]/60 px-2.5 py-1 text-[11.5px] font-medium text-[var(--muted-foreground)] shadow-sm transition-colors hover:border-[var(--primary)]/40 hover:bg-[var(--primary)]/5 hover:text-[var(--primary)] disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:border-[var(--border)]/60 disabled:hover:bg-[var(--card)]/60 disabled:hover:text-[var(--muted-foreground)]"- >- <Zap- size={12}- strokeWidth={1.8}- className="shrink-0 transition-colors group-hover:text-[var(--primary)] group-disabled:group-hover:text-[var(--muted-foreground)]"- />- <span>{triggered ? t("Answering…") : t("Answer now")}</span>- </button>- </div>- );-});--AnswerNowRow.displayName = "AnswerNowRow";--function CostFooter({- cost,- tokens,- calls,-}: {- cost: number;- tokens: number;- calls: number;-}) {- const { t } = useTranslation();- const formatCost = (usd: number) => {- if (usd < 0.01) return `$${usd.toFixed(4)}`;- return `$${usd.toFixed(2)}`;- };- const formatTokens = (n: number) => {- if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;- return String(n);- };- return (- <div className="flex items-center gap-2 text-[10px] text-[var(--muted-foreground)]/40">- <Coins size={10} strokeWidth={1.5} className="shrink-0" />- <span>{formatCost(cost)}</span>- <span className="opacity-40">·</span>- <span>- {formatTokens(tokens)} {t("tokens")}- </span>- <span className="opacity-40">·</span>- <span>- {calls} {t("calls")}- </span>- </div>- );-}--function RoughActionButton({- icon: Icon,- label,- onClick,- disabled,-}: {- icon: LucideIcon;- label: string;- onClick: () => void;- disabled?: boolean;-}) {- return (- <button- type="button"- onClick={onClick}- disabled={disabled}- className="inline-flex items-center gap-1 px-0.5 py-0.5 text-[11px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-35"- >- <Icon size={11} strokeWidth={1.5} />- <span>{label}</span>- </button>- );-}--const UserMessage = memo(function UserMessage({- msg,- index,- onPreviewAttachment,-}: {- msg: ChatMessageItem;- index: number;- onPreviewAttachment?: (attachment: MessageAttachment) => void;-}) {- const { t } = useTranslation();- if (msg.content.startsWith("[Quiz Performance]")) return null;-- return (- <div key={`${msg.role}-${index}`} className="flex justify-end">- <div className="max-w-[75%] space-y-1.5">- <div className="flex justify-end pr-1">- <span className="text-[10px] tracking-wide text-[var(--muted-foreground)]">- {t(getModeBadgeLabel(msg.capability))}- </span>- </div>- {msg.attachments?.some((a) => a.type === "image") && (- <div className="flex flex-wrap justify-end gap-2">- {msg.attachments- .filter((a) => a.type === "image" && (a.base64 || a.url))- .map((a, ai) => {- const src = imageSrcForAttachment(a);- if (!src) return null;- return (- <button- key={`img-${ai}`}- type="button"- onClick={() => onPreviewAttachment?.(a)}- title={a.filename || t("image")}- className="overflow-hidden rounded-2xl border border-[var(--border)] transition-shadow hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/40"- >- {/* eslint-disable-next-line @next/next/no-img-element */}- <img- src={src}- alt={a.filename || t("image")}- className="max-h-48 max-w-[280px] rounded-2xl object-contain"- />- </button>- );- })}- </div>- )}- {msg.attachments?.some((a) => a.type !== "image") && (- <div className="flex flex-wrap justify-end gap-2">- {msg.attachments- .filter((a) => a.type !== "image")- .map((a, ai) => {- const filename = a.filename || t("Attachment");- const spec = docIconFor(filename);- const Icon = spec.Icon;- const cardClass =- "flex h-14 w-[220px] items-center gap-2.5 rounded-xl border border-[var(--border)] bg-[var(--card)] px-2.5 text-left shadow-sm transition-colors hover:border-[var(--primary)]/40 hover:bg-[var(--muted)]/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/40";- return (- <button- key={`doc-${ai}`}- type="button"- onClick={() => onPreviewAttachment?.(a)}- title={filename}- className={cardClass}- >- <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-[var(--muted)]/60">- <Icon size={20} strokeWidth={1.5} className={spec.tint} />- </div>- <div className="min-w-0 flex-1 text-left">- <div className="truncate text-[12px] font-medium text-[var(--foreground)]">- {filename}- </div>- <div className="truncate text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">- {spec.label}- </div>- </div>- </button>- );- })}- </div>- )}- <div className="rounded-2xl bg-[var(--secondary)] px-4 py-2.5 text-[14px] leading-relaxed text-[var(--foreground)] shadow-sm">- {(() => {- const snap = msg.requestSnapshot;- const hasNotebook = Boolean(snap?.notebookReferences?.length);- const hasBooks = Boolean(snap?.bookReferences?.length);- const hasHistory = Boolean(snap?.historyReferences?.length);- const hasQuestions = Boolean(- snap?.questionNotebookReferences?.length,- );- const hasSkills = Boolean(snap?.skills?.length);- const hasMemory = Boolean(snap?.memoryReferences?.length);- if (- !hasNotebook &&- !hasBooks &&- !hasHistory &&- !hasQuestions &&- !hasSkills &&- !hasMemory- )- return null;- return (- <div className="mb-2 flex flex-wrap gap-1.5">- {snap?.notebookReferences?.map((ref) => (- <span- key={ref.notebook_id}- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"- >- <BookOpen size={11} strokeWidth={1.8} />- {t("Notebook")} · {ref.record_ids.length} {t("records")}- </span>- ))}- {snap?.bookReferences?.map((ref) => (- <span- key={ref.book_id}- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"- >- <BookOpen size={11} strokeWidth={1.8} />- {t("Book")} · {ref.page_ids.length} {t("chapters")}- </span>- ))}- {snap?.historyReferences?.map((sid) => (- <span- key={sid}- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"- >- <MessageSquare size={11} strokeWidth={1.8} />- {t("Chat History")}- </span>- ))}- {hasQuestions && (- <span className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]">- <ClipboardList size={11} strokeWidth={1.8} />- {t("Question Bank")} ·{" "}- {snap?.questionNotebookReferences?.length} {t("items")}- </span>- )}- {snap?.skills?.map((skill) => (- <span- key={skill}- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"- >- <Wand2 size={11} strokeWidth={1.8} />- {skill === "auto" ? t("Skills Auto") : skill}- </span>- ))}- {snap?.memoryReferences?.map((file) => (- <span- key={file}- className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"- >- <Brain size={11} strokeWidth={1.8} />- {t("Memory")} ·{" "}- {file === "summary" ? t("Summary") : t("Profile")}- </span>- ))}- </div>- );- })()}- <div className="whitespace-pre-wrap">{msg.content}</div>- </div>- </div>- </div>- );-});--UserMessage.displayName = "UserMessage";--export const SpaceContextChips = memo(function SpaceContextChips({- historySessions,- bookReferences,- notebookGroups,- questionEntries,- selectedSkills,- skillsAutoMode,- memoryFiles,- onRemoveHistory,- onRemoveBookReference,- onRemoveNotebook,- onRemoveQuestion,- onRemoveSkill,- onClearSkillsAuto,- onRemoveMemoryFile,-}: {- historySessions: SelectedHistorySession[];- bookReferences: SelectedBookReference[];- notebookGroups: NotebookReferenceGroup[];- questionEntries: SelectedQuestionEntry[];- selectedSkills: string[];- skillsAutoMode: boolean;- memoryFiles: SpaceMemoryFile[];- onRemoveHistory: (sessionId: string) => void;- onRemoveBookReference: (bookId: string) => void;- onRemoveNotebook: (notebookId: string) => void;- onRemoveQuestion: (entryId: number) => void;- onRemoveSkill: (skill: string) => void;- onClearSkillsAuto: () => void;- onRemoveMemoryFile: (file: SpaceMemoryFile) => void;-}) {- const { t } = useTranslation();- if (- historySessions.length === 0 &&- bookReferences.length === 0 &&- notebookGroups.length === 0 &&- questionEntries.length === 0 &&- selectedSkills.length === 0 &&- !skillsAutoMode &&- memoryFiles.length === 0- )- return null;-- return (- <div className="mb-3 flex flex-wrap gap-2">- {historySessions.map((session) => (- <span- key={session.sessionId}- className="inline-flex max-w-full items-center gap-2 rounded-xl border border-sky-200 bg-sky-50 px-3 py-1.5 text-[12px] text-sky-800 shadow-sm dark:border-sky-900/60 dark:bg-sky-950/30 dark:text-sky-200"- >- <MessageSquare size={12} strokeWidth={1.8} className="shrink-0" />- <span className="shrink-0 font-medium">{t("Chat History")}</span>- <span className="truncate text-sky-700/90 dark:text-sky-200/90">- {session.title}- </span>- <button- onClick={() => onRemoveHistory(session.sessionId)}- className="shrink-0 opacity-60 transition hover:opacity-100"- >- <X size={12} />- </button>- </span>- ))}- {bookReferences.map((book) => (- <span- key={book.bookId}- className="inline-flex max-w-full items-center gap-2 rounded-xl border border-teal-200 bg-teal-50 px-3 py-1.5 text-[12px] text-teal-800 shadow-sm dark:border-teal-900/60 dark:bg-teal-950/30 dark:text-teal-200"- >- <BookOpen size={12} strokeWidth={1.8} className="shrink-0" />- <span className="shrink-0 font-medium">{t("Book")}</span>- <span className="truncate text-teal-700/90 dark:text-teal-200/90">- {book.bookTitle} ({book.pages.length})- </span>- <button- onClick={() => onRemoveBookReference(book.bookId)}- className="shrink-0 opacity-60 transition hover:opacity-100"- >- <X size={12} />- </button>- </span>- ))}- {notebookGroups.map((group) => (- <span- key={group.notebookId}- className="inline-flex max-w-full items-center gap-2 rounded-xl border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-[12px] text-[var(--foreground)] shadow-sm"- >- <BookOpen size={12} strokeWidth={1.8} className="shrink-0" />- <span className="shrink-0 font-medium">{t("Notebook")}</span>- <span className="truncate text-[var(--muted-foreground)]">- {group.notebookName} ({group.count})- </span>- <button- onClick={() => onRemoveNotebook(group.notebookId)}- className="shrink-0 opacity-60 transition hover:opacity-100"- >- <X size={12} />- </button>- </span>- ))}- {questionEntries.map((entry) => (- <span- key={entry.id}- className="inline-flex max-w-full items-center gap-2 rounded-xl border border-amber-200 bg-amber-50 px-3 py-1.5 text-[12px] text-amber-800 shadow-sm dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-200"- >- <ClipboardList size={12} strokeWidth={1.8} className="shrink-0" />- <span className="shrink-0 font-medium">{t("Question Bank")}</span>- <span className="truncate text-amber-700/90 dark:text-amber-200/90">- {entry.question.length > 40- ? `${entry.question.slice(0, 40)}…`- : entry.question}- </span>- <button- onClick={() => onRemoveQuestion(entry.id)}- className="shrink-0 opacity-60 transition hover:opacity-100"- >- <X size={12} />- </button>- </span>- ))}- {skillsAutoMode && (- <span className="inline-flex max-w-full items-center gap-2 rounded-xl border border-violet-200 bg-violet-50 px-3 py-1.5 text-[12px] text-violet-800 shadow-sm dark:border-violet-900/60 dark:bg-violet-950/30 dark:text-violet-200">- <Wand2 size={12} strokeWidth={1.8} className="shrink-0" />- <span className="shrink-0 font-medium">{t("Skills")}</span>- <span className="truncate text-violet-700/90 dark:text-violet-200/90">- {t("Auto")}- </span>- <button- onClick={onClearSkillsAuto}- className="shrink-0 opacity-60 transition hover:opacity-100"- >- <X size={12} />- </button>- </span>- )}- {selectedSkills.map((skill) => (- <span- key={skill}- className="inline-flex max-w-full items-center gap-2 rounded-xl border border-violet-200 bg-violet-50 px-3 py-1.5 text-[12px] text-violet-800 shadow-sm dark:border-violet-900/60 dark:bg-violet-950/30 dark:text-violet-200"- >- <Wand2 size={12} strokeWidth={1.8} className="shrink-0" />- <span className="shrink-0 font-medium">{t("Skill")}</span>- <span className="truncate text-violet-700/90 dark:text-violet-200/90">- {skill}- </span>- <button- onClick={() => onRemoveSkill(skill)}- className="shrink-0 opacity-60 transition hover:opacity-100"- >- <X size={12} />- </button>- </span>- ))}- {memoryFiles.map((file) => (- <span- key={file}- className="inline-flex max-w-full items-center gap-2 rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-1.5 text-[12px] text-emerald-800 shadow-sm dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-200"- >- <Brain size={12} strokeWidth={1.8} className="shrink-0" />- <span className="shrink-0 font-medium">{t("Memory")}</span>- <span className="truncate text-emerald-700/90 dark:text-emerald-200/90">- {file === "summary" ? t("Summary") : t("Profile")}- </span>- <button- onClick={() => onRemoveMemoryFile(file)}- className="shrink-0 opacity-60 transition hover:opacity-100"- >- <X size={12} />- </button>- </span>- ))}- </div>- );-});--SpaceContextChips.displayName = "SpaceContextChips";--export const ChatMessageList = memo(function ChatMessageList({- messages,- isStreaming,- sessionId,- language,- onAnswerNow,- onCopyAssistantMessage,- onRegenerateMessage,- onConfirmOutline,- onPreviewAttachment,-}: {- messages: ChatMessageItem[];- isStreaming: boolean;- sessionId?: string | null;- language?: string;- onAnswerNow: (- snapshot?: MessageRequestSnapshot,- assistantMsg?: { content: string; events?: StreamEvent[] },- ) => void;- onCopyAssistantMessage: (content: string) => void | Promise<void>;- onRegenerateMessage: () => void;- onConfirmOutline?: (- outline: Array<{ title: string; overview: string }>,- topic: string,- researchConfig?: Record<string, unknown> | null,- ) => void;- onPreviewAttachment?: (attachment: MessageAttachment) => void;-}) {- const { t } = useTranslation();- const outlineStatusByIndex = useMemo(() => {- const map = new Map<number, "editing" | "researching" | "done">();- for (let i = 0; i < messages.length; i++) {- const msg = messages[i];- if (msg.role !== "assistant" || msg.capability !== "deep_research")- continue;- const resultEv = msg.events?.find((e) => e.type === "result");- const meta = resultEv?.metadata as Record<string, unknown> | undefined;- if (!meta?.outline_preview) continue;- const hasFollowup = messages- .slice(i + 1)- .some(- (m) => m.role === "assistant" && m.capability === "deep_research",- );- if (hasFollowup) {- const followup = messages- .slice(i + 1)- .find(- (m) => m.role === "assistant" && m.capability === "deep_research",- );- const followupResult = followup?.events?.find(- (e) => e.type === "result",- );- map.set(i, followupResult ? "done" : "researching");- } else if (isStreaming) {- map.set(i, "researching");- } else {- map.set(i, "editing");- }- }- return map;- }, [messages, isStreaming]);-- const messageRows = useMemo(() => {- // System messages are backend grounding (e.g. quiz follow-up context) and- // must never be rendered as a chat bubble. Filter them out defensively in- // addition to the hydration-time filter in UnifiedChatContext.- return messages- .map((msg, index) => ({ msg, originalIndex: index }))- .filter(({ msg }) => msg.role !== "system")- .map(({ msg, originalIndex }) => {- if (msg.role === "user") {- return {- msg,- originalIndex,- pairedUserMessage: null as ChatMessageItem | null,- };- }- const pairedUserMessage =- [...messages.slice(0, originalIndex)]- .reverse()- .find((previous) => previous.role === "user") ?? null;- return { msg, originalIndex, pairedUserMessage };- });- }, [messages]);-- const lastAssistantIndex = useMemo(() => {- for (let idx = messages.length - 1; idx >= 0; idx -= 1) {- if (messages[idx].role === "assistant") return idx;- }- return -1;- }, [messages]);-- return (- <>- {messageRows.map(({ msg, originalIndex, pairedUserMessage }) => {- const i = originalIndex;- if (msg.role === "user") {- return (- <UserMessage- key={`${msg.role}-${i}`}- msg={msg}- index={i}- onPreviewAttachment={onPreviewAttachment}- />- );- }-- const isActiveAssistant = isStreaming && i === messages.length - 1;- const msgDone = !isActiveAssistant;- const showActions = msgDone && hasVisibleMarkdownContent(msg.content);- const isLastAssistant = i === lastAssistantIndex;- const showRegenerate =- showActions &&- !isStreaming &&- isLastAssistant &&- Boolean(pairedUserMessage) &&- (!pairedUserMessage?.capability ||- pairedUserMessage?.capability === "chat");-- // The "Answer now" affordance lives inside the trace panel for the- // currently-streaming assistant turn. We hand the panel a thin- // closure so it does not need to know about MessageRequestSnapshot.- const handleTraceAnswerNow =- isActiveAssistant && pairedUserMessage?.requestSnapshot- ? () =>- onAnswerNow(pairedUserMessage.requestSnapshot, {- content: msg.content,- events: msg.events,- })- : undefined;-- const costSummary = (() => {- if (!msgDone) return null;- const resultEv = msg.events?.find((e) => e.type === "result");- if (!resultEv) return null;- const meta = resultEv.metadata?.metadata as- | Record<string, unknown>- | undefined;- const cs = meta?.cost_summary as- | {- total_cost_usd?: number;- total_tokens?: number;- total_calls?: number;- }- | undefined;- if (!cs || !cs.total_calls) return null;- return cs;- })();-- return (- <div key={`${msg.role}-${i}`} className="w-full">- <AssistantMessage- msg={msg}- isStreaming={isActiveAssistant}- outlineStatus={outlineStatusByIndex.get(i)}- sessionId={sessionId}- language={language}- onConfirmOutline={onConfirmOutline}- onAnswerNow={handleTraceAnswerNow}- />- {(showActions || costSummary) && (- <div className="mt-2 flex items-center">- {showActions && (- <div className="flex gap-2">- <RoughActionButton- icon={Copy}- label={t("Copy")}- onClick={() => void onCopyAssistantMessage(msg.content)}- />- {showRegenerate && (- <RoughActionButton- icon={RefreshCcw}- label={t("Regenerate")}- onClick={() => onRegenerateMessage()}- />- )}- </div>- )}- {costSummary && (- <div className="ml-auto">- <CostFooter- cost={costSummary.total_cost_usd ?? 0}- tokens={costSummary.total_tokens ?? 0}- calls={costSummary.total_calls ?? 0}- />- </div>- )}- </div>- )}- </div>- );- })}- </>- );-});--ChatMessageList.displayName = "ChatMessageList";+}++function imageSrcForAttachment(attachment: MessageAttachment): string | null {+ if (attachment.url) {+ if (+ attachment.url.startsWith("http") ||+ attachment.url.startsWith("blob:") ||+ attachment.url.startsWith("data:")+ ) {+ return attachment.url;+ }+ return apiUrl(attachment.url);+ }++ const base64 = attachment.base64?.trim();+ if (!base64) return null;+ if (base64.startsWith("data:")) return base64;+ return `data:${attachment.mime_type || "image/png"};base64,${base64}`;+}++const AssistantMessage = memo(function AssistantMessage({+ msg,+ isStreaming,+ outlineStatus,+ sessionId,+ language,+ onConfirmOutline,+ onAnswerNow,+ onRetry,+ onSwitchToManual,+}: {+ msg: { content: string; capability?: string; events?: StreamEvent[] };+ isStreaming?: boolean;+ outlineStatus?: "editing" | "researching" | "done";+ sessionId?: string | null;+ language?: string;+ onConfirmOutline?: (+ outline: Array<{ title: string; overview: string }>,+ topic: string,+ researchConfig?: Record<string, unknown> | null,+ ) => void;+ onAnswerNow?: () => void;+ onRetry?: () => void;+ onSwitchToManual?: () => void;+}) {+ const isAutoTurn = msg.capability === "auto";+ const events = useMemo(() => msg.events ?? [], [msg.events]);+ const resultEvent = useMemo(+ () => msg.events?.find((event) => event.type === "result") ?? null,+ [msg.events],+ );++ const outlinePreview = useMemo(() => {+ if (msg.capability !== "deep_research" || !resultEvent) return null;+ const meta = resultEvent.metadata as Record<string, unknown> | undefined;+ if (!meta?.outline_preview) return null;+ return {+ sub_topics: (meta.sub_topics ?? []) as Array<{+ title: string;+ overview: string;+ }>,+ topic: String(meta.topic ?? ""),+ research_config: (meta.research_config ?? null) as Record<+ string,+ unknown+ > | null,+ };+ }, [msg.capability, resultEvent]);++ const quizQuestions = useMemo(() => {+ if (msg.capability !== "deep_question" || !resultEvent) return null;+ return extractQuizQuestions(resultEvent.metadata);+ }, [msg.capability, resultEvent]);++ const mathAnimatorResult = useMemo(() => {+ if (msg.capability !== "math_animator" || !resultEvent) return null;+ return extractMathAnimatorResult(resultEvent.metadata);+ }, [msg.capability, resultEvent]);++ const visualizeResult = useMemo(() => {+ if (msg.capability !== "visualize" || !resultEvent) return null;+ return extractVisualizeResult(resultEvent.metadata);+ }, [msg.capability, resultEvent]);++ // Auto turns have a fundamentally different layout (interleaved+ // thinking + collapsed delegation cards + final synthesis). Each sub-+ // capability's internal trace is rendered INSIDE its delegation card —+ // we deliberately do NOT show a top-level CallTracePanel here, because+ // grouping by ``call_id`` would mix auto-level routing trace with each+ // sub-capability's stages and produce the visual noise this layout was+ // meant to avoid.+ if (isAutoTurn) {+ return (+ <>+ {isStreaming && onAnswerNow ? (+ <AnswerNowRow onAnswerNow={onAnswerNow} />+ ) : null}+ <AutoModeAssistantMessage+ msg={msg}+ isStreaming={isStreaming}+ sessionId={sessionId}+ language={language}+ onRetry={onRetry}+ onSwitchToManual={onSwitchToManual}+ />+ </>+ );+ }++ return (+ <>+ <TraceSurface+ events={events}+ isStreaming={isStreaming}+ content={msg.content}+ />+ {isStreaming && onAnswerNow ? (+ <AnswerNowRow onAnswerNow={onAnswerNow} />+ ) : null}+ {outlinePreview && outlinePreview.sub_topics.length > 0 ? (+ <ResearchOutlineEditor+ outline={outlinePreview.sub_topics}+ topic={outlinePreview.topic}+ onConfirm={(items) =>+ onConfirmOutline?.(+ items,+ outlinePreview.topic,+ outlinePreview.research_config,+ )+ }+ status={outlineStatus}+ />+ ) : mathAnimatorResult ? (+ <MathAnimatorViewer result={mathAnimatorResult} />+ ) : visualizeResult ? (+ <VisualizationViewer result={visualizeResult} />+ ) : quizQuestions && quizQuestions.length > 0 ? (+ <QuizViewer+ questions={quizQuestions}+ sessionId={sessionId}+ language={language}+ />+ ) : (+ <AssistantResponse content={msg.content} />+ )}+ </>+ );+});++AssistantMessage.displayName = "AssistantMessage";++/**+ * Inline "Answer now" affordance shown alongside the active assistant turn.+ * Lives outside the trace panel so it is visible as soon as the turn starts+ * — i.e. even before any tool / reasoning trace has been emitted, which is+ * the common case for the very first user message.+ */+const AnswerNowRow = memo(function AnswerNowRow({+ onAnswerNow,+}: {+ onAnswerNow: () => void;+}) {+ const { t } = useTranslation();+ // Local single-shot guard: once the user has fired "answer now" we lock+ // the button so a second click can't queue a duplicate cancel + restart+ // race against the in-flight synthesis turn. The next assistant turn+ // mounts a fresh ``AnswerNowRow`` with its own state, so this naturally+ // resets per turn without any external bookkeeping.+ const [triggered, setTriggered] = useState(false);+ const handleClick = useCallback(() => {+ if (triggered) return;+ setTriggered(true);+ onAnswerNow();+ }, [triggered, onAnswerNow]);++ return (+ <div className="mt-1.5 mb-3 flex items-center">+ <button+ type="button"+ onClick={handleClick}+ disabled={triggered}+ title={t("Skip reasoning and answer now")}+ aria-disabled={triggered}+ className="group inline-flex items-center gap-1.5 rounded-md border border-[var(--border)]/60 bg-[var(--card)]/60 px-2.5 py-1 text-[11.5px] font-medium text-[var(--muted-foreground)] shadow-sm transition-colors hover:border-[var(--primary)]/40 hover:bg-[var(--primary)]/5 hover:text-[var(--primary)] disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:border-[var(--border)]/60 disabled:hover:bg-[var(--card)]/60 disabled:hover:text-[var(--muted-foreground)]"+ >+ <Zap+ size={12}+ strokeWidth={1.8}+ className="shrink-0 transition-colors group-hover:text-[var(--primary)] group-disabled:group-hover:text-[var(--muted-foreground)]"+ />+ <span>{triggered ? t("Answering…") : t("Answer now")}</span>+ </button>+ </div>+ );+});++AnswerNowRow.displayName = "AnswerNowRow";++function CostFooter({+ cost,+ tokens,+ calls,+}: {+ cost: number;+ tokens: number;+ calls: number;+}) {+ const { t } = useTranslation();+ const formatCost = (usd: number) => {+ if (usd < 0.01) return `$${usd.toFixed(4)}`;+ return `$${usd.toFixed(2)}`;+ };+ const formatTokens = (n: number) => {+ if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;+ return String(n);+ };+ return (+ <div className="flex items-center gap-2 text-[10px] text-[var(--muted-foreground)]/40">+ <Coins size={10} strokeWidth={1.5} className="shrink-0" />+ <span>{formatCost(cost)}</span>+ <span className="opacity-40">·</span>+ <span>+ {formatTokens(tokens)} {t("tokens")}+ </span>+ <span className="opacity-40">·</span>+ <span>+ {calls} {t("calls")}+ </span>+ </div>+ );+}++function RoughActionButton({+ icon: Icon,+ label,+ onClick,+ disabled,+}: {+ icon: LucideIcon;+ label: string;+ onClick: () => void;+ disabled?: boolean;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ disabled={disabled}+ className="inline-flex items-center gap-1 px-0.5 py-0.5 text-[11px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-35"+ >+ <Icon size={11} strokeWidth={1.5} />+ <span>{label}</span>+ </button>+ );+}++function BranchNavigator({+ info,+ onSwitch,+}: {+ info: SiblingInfo;+ onSwitch: (childId: number) => void;+}) {+ const { t } = useTranslation();+ const prevIdx = info.index - 2; // 0-based prev index+ const nextIdx = info.index; // 0-based next index+ const prevId = prevIdx >= 0 ? info.siblingIds[prevIdx] : null;+ const nextId =+ nextIdx < info.siblingIds.length ? info.siblingIds[nextIdx] : null;+ return (+ <div className="inline-flex items-center gap-0.5 text-[10.5px] text-[var(--muted-foreground)]">+ <button+ type="button"+ onClick={() => prevId !== null && onSwitch(prevId)}+ disabled={prevId === null}+ aria-label={t("Previous branch")}+ className="rounded p-0.5 transition-colors hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-30"+ >+ <ChevronLeft size={12} strokeWidth={1.8} />+ </button>+ <span className="select-none tabular-nums">+ {info.index} / {info.total}+ </span>+ <button+ type="button"+ onClick={() => nextId !== null && onSwitch(nextId)}+ disabled={nextId === null}+ aria-label={t("Next branch")}+ className="rounded p-0.5 transition-colors hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-30"+ >+ <ChevronRight size={12} strokeWidth={1.8} />+ </button>+ </div>+ );+}++function DeleteTurnButton({ onDelete }: { onDelete: () => void }) {+ const { t } = useTranslation();+ const [confirm, setConfirm] = useState(false);+ if (!confirm) {+ return (+ <RoughActionButton+ icon={Trash2}+ label={t("Delete")}+ onClick={() => setConfirm(true)}+ />+ );+ }+ return (+ <div className="inline-flex items-center gap-1.5 text-[11px]">+ <span className="text-[var(--muted-foreground)]">+ {t("Delete this turn?")}+ </span>+ <button+ type="button"+ onClick={() => {+ onDelete();+ setConfirm(false);+ }}+ className="rounded-md px-1.5 py-0.5 font-medium text-[var(--destructive)] hover:bg-[var(--destructive)]/10"+ >+ {t("Delete")}+ </button>+ <button+ type="button"+ onClick={() => setConfirm(false)}+ className="rounded-md px-1.5 py-0.5 font-medium text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40"+ >+ {t("Cancel")}+ </button>+ </div>+ );+}++const UserMessage = memo(function UserMessage({+ msg,+ index,+ onPreviewAttachment,+ onCopy,+ onEdit,+ editDisabled,+ siblingInfo,+ onSwitchBranch,+}: {+ msg: ChatMessageItem;+ index: number;+ onPreviewAttachment?: (attachment: MessageAttachment) => void;+ onCopy?: (content: string) => void | Promise<void>;+ onEdit?: (messageId: number, newContent: string) => void;+ editDisabled?: boolean;+ siblingInfo?: SiblingInfo;+ onSwitchBranch?: (parentMessageId: number | null, childId: number) => void;+}) {+ const { t } = useTranslation();+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState(msg.content);+ if (msg.content.startsWith("[Quiz Performance]")) return null;+ // ``msg.id`` can be a negative client-side sentinel for optimistic+ // (just-sent, not yet reconciled with the server) rows. We still allow+ // the Edit button to surface — ``editMessage`` in the context handles+ // the optimistic case by triggering a session reload to resolve the+ // real id before submitting the branch.+ const canEdit =+ Boolean(onEdit) && typeof msg.id === "number" && !editDisabled;+ const startEdit = () => {+ if (!canEdit) return;+ setDraft(msg.content);+ setEditing(true);+ };+ const cancelEdit = () => {+ setEditing(false);+ setDraft(msg.content);+ };+ const submitEdit = () => {+ const trimmed = draft.trim();+ if (!trimmed || trimmed === msg.content) {+ cancelEdit();+ return;+ }+ if (typeof msg.id !== "number") return;+ onEdit?.(msg.id, trimmed);+ setEditing(false);+ };++ return (+ <div key={`${msg.role}-${index}`} className="group flex justify-end">+ <div className="flex max-w-[75%] flex-col items-end gap-1.5">+ <div className="flex justify-end pr-1">+ <span className="text-[10px] tracking-wide text-[var(--muted-foreground)]">+ {t(getModeBadgeLabel(msg.capability))}+ </span>+ </div>+ {msg.attachments?.some((a) => a.type === "image") && (+ <div className="flex flex-wrap justify-end gap-2">+ {msg.attachments+ .filter((a) => a.type === "image" && (a.base64 || a.url))+ .map((a, ai) => {+ const src = imageSrcForAttachment(a);+ if (!src) return null;+ return (+ <button+ key={`img-${ai}`}+ type="button"+ onClick={() => onPreviewAttachment?.(a)}+ title={a.filename || t("image")}+ className="overflow-hidden rounded-2xl border border-[var(--border)] transition-shadow hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/40"+ >+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img+ src={src}+ alt={a.filename || t("image")}+ className="max-h-48 max-w-[280px] rounded-2xl object-contain"+ />+ </button>+ );+ })}+ </div>+ )}+ {msg.attachments?.some((a) => a.type !== "image") && (+ <div className="flex flex-wrap justify-end gap-2">+ {msg.attachments+ .filter((a) => a.type !== "image")+ .map((a, ai) => {+ const filename = a.filename || t("Attachment");+ const spec = docIconFor(filename);+ const Icon = spec.Icon;+ const cardClass =+ "flex h-14 w-[220px] items-center gap-2.5 rounded-xl border border-[var(--border)] bg-[var(--card)] px-2.5 text-left shadow-sm transition-colors hover:border-[var(--primary)]/40 hover:bg-[var(--muted)]/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/40";+ return (+ <button+ key={`doc-${ai}`}+ type="button"+ onClick={() => onPreviewAttachment?.(a)}+ title={filename}+ className={cardClass}+ >+ <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-[var(--muted)]/60">+ <Icon size={20} strokeWidth={1.5} className={spec.tint} />+ </div>+ <div className="min-w-0 flex-1 text-left">+ <div className="truncate text-[12px] font-medium text-[var(--foreground)]">+ {filename}+ </div>+ <div className="truncate text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">+ {spec.label}+ </div>+ </div>+ </button>+ );+ })}+ </div>+ )}+ {editing ? (+ <div className="w-[min(620px,75vw)] rounded-2xl border border-[var(--primary)]/40 bg-[var(--secondary)] px-3 py-2.5 text-[14px] leading-relaxed text-[var(--foreground)] shadow-sm">+ <textarea+ autoFocus+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Escape") {+ e.preventDefault();+ cancelEdit();+ } else if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ submitEdit();+ }+ }}+ rows={Math.min(8, Math.max(2, draft.split("\n").length))}+ className="w-full resize-none border-0 bg-transparent text-[14px] leading-relaxed text-[var(--foreground)] outline-none focus:outline-none"+ />+ <div className="mt-1 flex items-center justify-between gap-2">+ <span className="text-[10.5px] text-[var(--muted-foreground)]/80">+ {t("Use the arrows below to switch between branches.")}+ </span>+ <div className="flex shrink-0 items-center gap-1.5">+ <button+ type="button"+ onClick={cancelEdit}+ className="rounded-md px-2 py-0.5 text-[11px] font-medium text-[var(--muted-foreground)] hover:bg-[var(--muted)]/40"+ >+ {t("Cancel")}+ </button>+ <button+ type="button"+ onClick={submitEdit}+ disabled={!draft.trim() || draft.trim() === msg.content}+ className="rounded-md bg-[var(--primary)] px-2.5 py-0.5 text-[11px] font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"+ >+ {t("Send")}+ </button>+ </div>+ </div>+ </div>+ ) : (+ <div className="rounded-2xl bg-[var(--secondary)] px-4 py-2.5 text-[14px] leading-relaxed text-[var(--foreground)] shadow-sm">+ {(() => {+ const snap = msg.requestSnapshot;+ const hasNotebook = Boolean(snap?.notebookReferences?.length);+ const hasBooks = Boolean(snap?.bookReferences?.length);+ const hasHistory = Boolean(snap?.historyReferences?.length);+ const hasQuestions = Boolean(+ snap?.questionNotebookReferences?.length,+ );+ const hasSkills = Boolean(snap?.skills?.length);+ const hasMemory = Boolean(snap?.memoryReferences?.length);+ if (+ !hasNotebook &&+ !hasBooks &&+ !hasHistory &&+ !hasQuestions &&+ !hasSkills &&+ !hasMemory+ )+ return null;+ return (+ <div className="mb-2 flex flex-wrap gap-1.5">+ {snap?.notebookReferences?.map((ref) => (+ <span+ key={ref.notebook_id}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"+ >+ <BookOpen size={11} strokeWidth={1.8} />+ {t("Notebook")} · {ref.record_ids.length} {t("records")}+ </span>+ ))}+ {snap?.bookReferences?.map((ref) => (+ <span+ key={ref.book_id}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"+ >+ <BookOpen size={11} strokeWidth={1.8} />+ {t("Book")} · {ref.page_ids.length} {t("chapters")}+ </span>+ ))}+ {snap?.historyReferences?.map((sid) => (+ <span+ key={sid}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"+ >+ <MessageSquare size={11} strokeWidth={1.8} />+ {t("Chat History")}+ </span>+ ))}+ {hasQuestions && (+ <span className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]">+ <ClipboardList size={11} strokeWidth={1.8} />+ {t("Question Bank")} ·{" "}+ {snap?.questionNotebookReferences?.length} {t("items")}+ </span>+ )}+ {snap?.skills?.map((skill) => (+ <span+ key={skill}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"+ >+ <Wand2 size={11} strokeWidth={1.8} />+ {skill === "auto" ? t("Skills Auto") : skill}+ </span>+ ))}+ {snap?.memoryReferences?.map((file) => (+ <span+ key={file}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"+ >+ <Brain size={11} strokeWidth={1.8} />+ {t("Memory")} ·{" "}+ {file === "summary" ? t("Summary") : t("Profile")}+ </span>+ ))}+ </div>+ );+ })()}+ <div className="whitespace-pre-wrap">{msg.content}</div>+ </div>+ )}+ {!editing && (onCopy || canEdit || siblingInfo) && msg.content && (+ <div className="flex h-5 items-center justify-end gap-2 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100">+ {siblingInfo && siblingInfo.total > 1 && (+ <BranchNavigator+ info={siblingInfo}+ onSwitch={(childId) =>+ onSwitchBranch?.(siblingInfo.parentId, childId)+ }+ />+ )}+ {onCopy && (+ <RoughActionButton+ icon={Copy}+ label={t("Copy")}+ onClick={() => void onCopy(msg.content)}+ />+ )}+ {canEdit && (+ <RoughActionButton+ icon={Pencil}+ label={t("Edit")}+ onClick={startEdit}+ />+ )}+ </div>+ )}+ </div>+ </div>+ );+});++UserMessage.displayName = "UserMessage";++export const SpaceContextChips = memo(function SpaceContextChips({+ historySessions,+ bookReferences,+ notebookGroups,+ questionEntries,+ selectedSkills,+ skillsAutoMode,+ memoryFiles,+ onRemoveHistory,+ onRemoveBookReference,+ onRemoveNotebook,+ onRemoveQuestion,+ onRemoveSkill,+ onClearSkillsAuto,+ onRemoveMemoryFile,+}: {+ historySessions: SelectedHistorySession[];+ bookReferences: SelectedBookReference[];+ notebookGroups: NotebookReferenceGroup[];+ questionEntries: SelectedQuestionEntry[];+ selectedSkills: string[];+ skillsAutoMode: boolean;+ memoryFiles: SpaceMemoryFile[];+ onRemoveHistory: (sessionId: string) => void;+ onRemoveBookReference: (bookId: string) => void;+ onRemoveNotebook: (notebookId: string) => void;+ onRemoveQuestion: (entryId: number) => void;+ onRemoveSkill: (skill: string) => void;+ onClearSkillsAuto: () => void;+ onRemoveMemoryFile: (file: SpaceMemoryFile) => void;+}) {+ const { t } = useTranslation();+ if (+ historySessions.length === 0 &&+ bookReferences.length === 0 &&+ notebookGroups.length === 0 &&+ questionEntries.length === 0 &&+ selectedSkills.length === 0 &&+ !skillsAutoMode &&+ memoryFiles.length === 0+ )+ return null;++ return (+ <div className="mb-3 flex flex-wrap gap-2">+ {historySessions.map((session) => (+ <span+ key={session.sessionId}+ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-sky-200 bg-sky-50 px-3 py-1.5 text-[12px] text-sky-800 shadow-sm dark:border-sky-900/60 dark:bg-sky-950/30 dark:text-sky-200"+ >+ <MessageSquare size={12} strokeWidth={1.8} className="shrink-0" />+ <span className="shrink-0 font-medium">{t("Chat History")}</span>+ <span className="truncate text-sky-700/90 dark:text-sky-200/90">+ {session.title}+ </span>+ <button+ onClick={() => onRemoveHistory(session.sessionId)}+ className="shrink-0 opacity-60 transition hover:opacity-100"+ >+ <X size={12} />+ </button>+ </span>+ ))}+ {bookReferences.map((book) => (+ <span+ key={book.bookId}+ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-teal-200 bg-teal-50 px-3 py-1.5 text-[12px] text-teal-800 shadow-sm dark:border-teal-900/60 dark:bg-teal-950/30 dark:text-teal-200"+ >+ <BookOpen size={12} strokeWidth={1.8} className="shrink-0" />+ <span className="shrink-0 font-medium">{t("Book")}</span>+ <span className="truncate text-teal-700/90 dark:text-teal-200/90">+ {book.bookTitle} ({book.pages.length})+ </span>+ <button+ onClick={() => onRemoveBookReference(book.bookId)}+ className="shrink-0 opacity-60 transition hover:opacity-100"+ >+ <X size={12} />+ </button>+ </span>+ ))}+ {notebookGroups.map((group) => (+ <span+ key={group.notebookId}+ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-[12px] text-[var(--foreground)] shadow-sm"+ >+ <BookOpen size={12} strokeWidth={1.8} className="shrink-0" />+ <span className="shrink-0 font-medium">{t("Notebook")}</span>+ <span className="truncate text-[var(--muted-foreground)]">+ {group.notebookName} ({group.count})+ </span>+ <button+ onClick={() => onRemoveNotebook(group.notebookId)}+ className="shrink-0 opacity-60 transition hover:opacity-100"+ >+ <X size={12} />+ </button>+ </span>+ ))}+ {questionEntries.map((entry) => (+ <span+ key={entry.id}+ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-amber-200 bg-amber-50 px-3 py-1.5 text-[12px] text-amber-800 shadow-sm dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-200"+ >+ <ClipboardList size={12} strokeWidth={1.8} className="shrink-0" />+ <span className="shrink-0 font-medium">{t("Question Bank")}</span>+ <span className="truncate text-amber-700/90 dark:text-amber-200/90">+ {entry.question.length > 40+ ? `${entry.question.slice(0, 40)}…`+ : entry.question}+ </span>+ <button+ onClick={() => onRemoveQuestion(entry.id)}+ className="shrink-0 opacity-60 transition hover:opacity-100"+ >+ <X size={12} />+ </button>+ </span>+ ))}+ {skillsAutoMode && (+ <span className="inline-flex max-w-full items-center gap-2 rounded-xl border border-violet-200 bg-violet-50 px-3 py-1.5 text-[12px] text-violet-800 shadow-sm dark:border-violet-900/60 dark:bg-violet-950/30 dark:text-violet-200">+ <Wand2 size={12} strokeWidth={1.8} className="shrink-0" />+ <span className="shrink-0 font-medium">{t("Skills")}</span>+ <span className="truncate text-violet-700/90 dark:text-violet-200/90">+ {t("Auto")}+ </span>+ <button+ onClick={onClearSkillsAuto}+ className="shrink-0 opacity-60 transition hover:opacity-100"+ >+ <X size={12} />+ </button>+ </span>+ )}+ {selectedSkills.map((skill) => (+ <span+ key={skill}+ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-violet-200 bg-violet-50 px-3 py-1.5 text-[12px] text-violet-800 shadow-sm dark:border-violet-900/60 dark:bg-violet-950/30 dark:text-violet-200"+ >+ <Wand2 size={12} strokeWidth={1.8} className="shrink-0" />+ <span className="shrink-0 font-medium">{t("Skill")}</span>+ <span className="truncate text-violet-700/90 dark:text-violet-200/90">+ {skill}+ </span>+ <button+ onClick={() => onRemoveSkill(skill)}+ className="shrink-0 opacity-60 transition hover:opacity-100"+ >+ <X size={12} />+ </button>+ </span>+ ))}+ {memoryFiles.map((file) => (+ <span+ key={file}+ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-1.5 text-[12px] text-emerald-800 shadow-sm dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-200"+ >+ <Brain size={12} strokeWidth={1.8} className="shrink-0" />+ <span className="shrink-0 font-medium">{t("Memory")}</span>+ <span className="truncate text-emerald-700/90 dark:text-emerald-200/90">+ {file === "summary" ? t("Summary") : t("Profile")}+ </span>+ <button+ onClick={() => onRemoveMemoryFile(file)}+ className="shrink-0 opacity-60 transition hover:opacity-100"+ >+ <X size={12} />+ </button>+ </span>+ ))}+ </div>+ );+});++SpaceContextChips.displayName = "SpaceContextChips";++export const ChatMessageList = memo(function ChatMessageList({+ messages,+ isStreaming,+ sessionId,+ language,+ onAnswerNow,+ onCopyAssistantMessage,+ onRegenerateMessage,+ onConfirmOutline,+ onPreviewAttachment,+ onSwitchToManualMode,+ onDeleteTurn,+ selectedBranches,+ onEditMessage,+ onSwitchBranch,+}: {+ messages: ChatMessageItem[];+ isStreaming: boolean;+ sessionId?: string | null;+ language?: string;+ onAnswerNow: (+ snapshot?: MessageRequestSnapshot,+ assistantMsg?: { content: string; events?: StreamEvent[] },+ ) => void;+ onCopyAssistantMessage: (content: string) => void | Promise<void>;+ onRegenerateMessage: () => void;+ onConfirmOutline?: (+ outline: Array<{ title: string; overview: string }>,+ topic: string,+ researchConfig?: Record<string, unknown> | null,+ ) => void;+ onPreviewAttachment?: (attachment: MessageAttachment) => void;+ // Only used by auto-turn ``AutoErrorBlock`` to surface a "back to manual"+ // button after a terminal failure. Optional so non-auto chat surfaces don't+ // have to wire it.+ onSwitchToManualMode?: () => void;+ onDeleteTurn?: (messageId: number) => void;+ /** Edit-branching: selected sibling at each branch point. */+ selectedBranches?: Record<string, number>;+ onEditMessage?: (messageId: number, newContent: string) => void;+ onSwitchBranch?: (parentMessageId: number | null, childId: number) => void;+}) {+ const { t } = useTranslation();+ // Visible path: when no branching has happened the result is identical+ // to the input. After an edit, sibling branches are filtered out so the+ // UI shows exactly one continuous thread, with arrow nav exposed on the+ // user message where branching diverges.+ const { messages: visibleMessages, siblingsByMessageId } = useMemo(+ () => buildVisiblePath(messages, selectedBranches),+ [messages, selectedBranches],+ );+ const outlineStatusByIndex = useMemo(() => {+ const map = new Map<number, "editing" | "researching" | "done">();+ for (let i = 0; i < visibleMessages.length; i++) {+ const msg = visibleMessages[i];+ if (msg.role !== "assistant" || msg.capability !== "deep_research")+ continue;+ const resultEv = msg.events?.find((e) => e.type === "result");+ const meta = resultEv?.metadata as Record<string, unknown> | undefined;+ if (!meta?.outline_preview) continue;+ const hasFollowup = visibleMessages+ .slice(i + 1)+ .some(+ (m) => m.role === "assistant" && m.capability === "deep_research",+ );+ if (hasFollowup) {+ const followup = visibleMessages+ .slice(i + 1)+ .find(+ (m) => m.role === "assistant" && m.capability === "deep_research",+ );+ const followupResult = followup?.events?.find(+ (e) => e.type === "result",+ );+ map.set(i, followupResult ? "done" : "researching");+ } else if (isStreaming) {+ map.set(i, "researching");+ } else {+ map.set(i, "editing");+ }+ }+ return map;+ }, [visibleMessages, isStreaming]);++ const messageRows = useMemo(() => {+ // System messages are backend grounding (e.g. quiz follow-up context) and+ // must never be rendered as a chat bubble. Filter them out defensively in+ // addition to the hydration-time filter in UnifiedChatContext.+ return visibleMessages+ .map((msg, index) => ({ msg, originalIndex: index }))+ .filter(({ msg }) => msg.role !== "system")+ .map(({ msg, originalIndex }) => {+ if (msg.role === "user") {+ return {+ msg,+ originalIndex,+ pairedUserMessage: null as ChatMessageItem | null,+ };+ }+ const pairedUserMessage =+ [...visibleMessages.slice(0, originalIndex)]+ .reverse()+ .find((previous) => previous.role === "user") ?? null;+ return { msg, originalIndex, pairedUserMessage };+ });+ }, [visibleMessages]);++ const lastAssistantIndex = useMemo(() => {+ for (let idx = visibleMessages.length - 1; idx >= 0; idx -= 1) {+ if (visibleMessages[idx].role === "assistant") return idx;+ }+ return -1;+ }, [visibleMessages]);++ return (+ <>+ {messageRows.map(({ msg, originalIndex, pairedUserMessage }) => {+ const i = originalIndex;+ if (msg.role === "user") {+ const sib =+ msg.id !== undefined ? siblingsByMessageId.get(msg.id) : undefined;+ return (+ <UserMessage+ key={`${msg.role}-${i}`}+ msg={msg}+ index={i}+ onPreviewAttachment={onPreviewAttachment}+ onCopy={onCopyAssistantMessage}+ onEdit={onEditMessage}+ editDisabled={isStreaming}+ siblingInfo={sib}+ onSwitchBranch={onSwitchBranch}+ />+ );+ }++ const isActiveAssistant =+ isStreaming && i === visibleMessages.length - 1;+ const msgDone = !isActiveAssistant;+ const showActions = msgDone && hasVisibleMarkdownContent(msg.content);+ const isLastAssistant = i === lastAssistantIndex;+ const showRegenerate =+ showActions &&+ !isStreaming &&+ isLastAssistant &&+ Boolean(pairedUserMessage) &&+ (!pairedUserMessage?.capability ||+ pairedUserMessage?.capability === "chat");+ const deletableTurnUserId =+ msgDone && pairedUserMessage?.id != null && onDeleteTurn+ ? pairedUserMessage.id+ : null;+ const showDelete = deletableTurnUserId != null;++ // The "Answer now" affordance lives inside the trace panel for the+ // currently-streaming assistant turn. We hand the panel a thin+ // closure so it does not need to know about MessageRequestSnapshot.+ const handleTraceAnswerNow =+ isActiveAssistant && pairedUserMessage?.requestSnapshot+ ? () =>+ onAnswerNow(pairedUserMessage.requestSnapshot, {+ content: msg.content,+ events: msg.events,+ })+ : undefined;++ const costSummary = (() => {+ if (!msgDone) return null;+ const resultEv = msg.events?.find((e) => e.type === "result");+ if (!resultEv) return null;+ const meta = resultEv.metadata?.metadata as+ | Record<string, unknown>+ | undefined;+ const cs = meta?.cost_summary as+ | {+ total_cost_usd?: number;+ total_tokens?: number;+ total_calls?: number;+ }+ | undefined;+ if (!cs || !cs.total_calls) return null;+ return cs;+ })();++ return (+ <div key={`${msg.role}-${i}`} className="w-full">+ <AssistantMessage+ msg={msg}+ isStreaming={isActiveAssistant}+ outlineStatus={outlineStatusByIndex.get(i)}+ sessionId={sessionId}+ language={language}+ onConfirmOutline={onConfirmOutline}+ onAnswerNow={handleTraceAnswerNow}+ onRetry={onRegenerateMessage}+ onSwitchToManual={onSwitchToManualMode}+ />+ {(showActions || costSummary || showDelete) && (+ <div className="mt-2 flex items-center">+ {(showActions || showDelete) && (+ <div className="flex items-center gap-2">+ {showActions && (+ <RoughActionButton+ icon={Copy}+ label={t("Copy")}+ onClick={() => void onCopyAssistantMessage(msg.content)}+ />+ )}+ {showActions && showRegenerate && (+ <RoughActionButton+ icon={RefreshCcw}+ label={t("Regenerate")}+ onClick={() => onRegenerateMessage()}+ />+ )}+ {showDelete && (+ <DeleteTurnButton+ onDelete={() => onDeleteTurn?.(deletableTurnUserId)}+ />+ )}+ </div>+ )}+ {costSummary && (+ <div className="ml-auto">+ <CostFooter+ cost={costSummary.total_cost_usd ?? 0}+ tokens={costSummary.total_tokens ?? 0}+ calls={costSummary.total_calls ?? 0}+ />+ </div>+ )}+ </div>+ )}+ </div>+ );+ })}+ </>+ );+});++ChatMessageList.displayName = "ChatMessageList";++"use client";++++import dynamic from "next/dynamic";++import { memo, useCallback, useMemo, useState } from "react";++import {++ BookOpen,++ Brain,++ ClipboardList,++ Coins,++ Copy,++ MessageSquare,++ RefreshCcw,++ Wand2,++ X,++ Zap,++ type LucideIcon,++} from "lucide-react";++import { useTranslation } from "react-i18next";++import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";++import type { SelectedQuestionEntry } from "@/components/chat/QuestionBankPicker";++import AssistantResponse from "@/components/common/AssistantResponse";++import type {++ MessageAttachment,++ MessageRequestSnapshot,++} from "@/context/UnifiedChatContext";++import { apiUrl } from "@/lib/api";++import { docIconFor } from "@/lib/doc-attachments";++import { extractMathAnimatorResult } from "@/lib/math-animator-types";++import { extractQuizQuestions } from "@/lib/quiz-types";++import { extractVisualizeResult } from "@/lib/visualize-types";++import type { StreamEvent } from "@/lib/unified-ws";++import { hasVisibleMarkdownContent } from "@/lib/markdown-display";++import type { SelectedBookReference } from "@/lib/book-references";++import type { SpaceMemoryFile } from "@/lib/space-items";++import { CallTracePanel } from "./TracePanels";++++const MathAnimatorViewer = dynamic(++ () => import("@/components/math-animator/MathAnimatorViewer"),++ { ssr: false },++);++const QuizViewer = dynamic(() => import("@/components/quiz/QuizViewer"), {++ ssr: false,++});++const ResearchOutlineEditor = dynamic(++ () => import("@/components/research/ResearchOutlineEditor"),++ { ssr: false },++);++const VisualizationViewer = dynamic(++ () => import("@/components/visualize/VisualizationViewer"),++ { ssr: false },++);++++interface ChatMessageItem {++ role: "user" | "assistant" | "system";++ content: string;++ capability?: string;++ events?: StreamEvent[];++ attachments?: MessageAttachment[];++ requestSnapshot?: MessageRequestSnapshot;++}++++interface NotebookReferenceGroup {++ notebookId: string;++ notebookName: string;++ count: number;++}++++// Returns the i18n key (and a sensible fallback) for the capability badge++// shown above the user's message. Callers must run `t(...)` on the result.++function getModeBadgeLabel(capability?: string | null): string {++ if (!capability || capability === "chat") return "Chat";++ if (capability === "deep_solve") return "Deep Solve";++ if (capability === "deep_question") return "Quiz Generation";++ if (capability === "deep_research") return "Deep Research";++ if (capability === "math_animator") return "Math Animator";++ if (capability === "visualize") return "Visualize";++ return capability;++}++++function imageSrcForAttachment(attachment: MessageAttachment): string | null {++ if (attachment.url) {++ if (++ attachment.url.startsWith("http") ||++ attachment.url.startsWith("blob:") ||++ attachment.url.startsWith("data:")++ ) {++ return attachment.url;++ }++ return apiUrl(attachment.url);++ }++++ const base64 = attachment.base64?.trim();++ if (!base64) return null;++ if (base64.startsWith("data:")) return base64;++ return `data:${attachment.mime_type || "image/png"};base64,${base64}`;++}++++const AssistantMessage = memo(function AssistantMessage({++ msg,++ isStreaming,++ outlineStatus,++ sessionId,++ language,++ onConfirmOutline,++ onAnswerNow,++}: {++ msg: { content: string; capability?: string; events?: StreamEvent[] };++ isStreaming?: boolean;++ outlineStatus?: "editing" | "researching" | "done";++ sessionId?: string | null;++ language?: string;++ onConfirmOutline?: (++ outline: Array<{ title: string; overview: string }>,++ topic: string,++ researchConfig?: Record<string, unknown> | null,++ ) => void;++ onAnswerNow?: () => void;++}) {++ const events = useMemo(() => msg.events ?? [], [msg.events]);++ const hasCallTrace = useMemo(++ () => events.some((event) => Boolean(event.metadata?.call_id)),++ [events],++ );++ const resultEvent = useMemo(++ () => msg.events?.find((event) => event.type === "result") ?? null,++ [msg.events],++ );++++ const outlinePreview = useMemo(() => {++ if (msg.capability !== "deep_research" || !resultEvent) return null;++ const meta = resultEvent.metadata as Record<string, unknown> | undefined;++ if (!meta?.outline_preview) return null;++ return {++ sub_topics: (meta.sub_topics ?? []) as Array<{++ title: string;++ overview: string;++ }>,++ topic: String(meta.topic ?? ""),++ research_config: (meta.research_config ?? null) as Record<++ string,++ unknown++ > | null,++ };++ }, [msg.capability, resultEvent]);++++ const quizQuestions = useMemo(() => {++ if (msg.capability !== "deep_question" || !resultEvent) return null;++ return extractQuizQuestions(resultEvent.metadata);++ }, [msg.capability, resultEvent]);++++ const mathAnimatorResult = useMemo(() => {++ if (msg.capability !== "math_animator" || !resultEvent) return null;++ return extractMathAnimatorResult(resultEvent.metadata);++ }, [msg.capability, resultEvent]);++++ const visualizeResult = useMemo(() => {++ if (msg.capability !== "visualize" || !resultEvent) return null;++ return extractVisualizeResult(resultEvent.metadata);++ }, [msg.capability, resultEvent]);++++ return (++ <>++ {hasCallTrace ? (++ <CallTracePanel events={events} isStreaming={isStreaming} />++ ) : null}++ {isStreaming && onAnswerNow ? (++ <AnswerNowRow onAnswerNow={onAnswerNow} />++ ) : null}++ {outlinePreview && outlinePreview.sub_topics.length > 0 ? (++ <ResearchOutlineEditor++ outline={outlinePreview.sub_topics}++ topic={outlinePreview.topic}++ onConfirm={(items) =>++ onConfirmOutline?.(++ items,++ outlinePreview.topic,++ outlinePreview.research_config,++ )++ }++ status={outlineStatus}++ />++ ) : mathAnimatorResult ? (++ <MathAnimatorViewer result={mathAnimatorResult} />++ ) : visualizeResult ? (++ <VisualizationViewer result={visualizeResult} />++ ) : quizQuestions && quizQuestions.length > 0 ? (++ <QuizViewer++ questions={quizQuestions}++ sessionId={sessionId}++ language={language}++ />++ ) : (++ <AssistantResponse content={msg.content} />++ )}++ </>++ );++});++++AssistantMessage.displayName = "AssistantMessage";++++/**++ * Inline "Answer now" affordance shown alongside the active assistant turn.++ * Lives outside the trace panel so it is visible as soon as the turn starts++ * — i.e. even before any tool / reasoning trace has been emitted, which is++ * the common case for the very first user message.++ */++const AnswerNowRow = memo(function AnswerNowRow({++ onAnswerNow,++}: {++ onAnswerNow: () => void;++}) {++ const { t } = useTranslation();++ // Local single-shot guard: once the user has fired "answer now" we lock++ // the button so a second click can't queue a duplicate cancel + restart++ // race against the in-flight synthesis turn. The next assistant turn++ // mounts a fresh ``AnswerNowRow`` with its own state, so this naturally++ // resets per turn without any external bookkeeping.++ const [triggered, setTriggered] = useState(false);++ const handleClick = useCallback(() => {++ if (triggered) return;++ setTriggered(true);++ onAnswerNow();++ }, [triggered, onAnswerNow]);++++ return (++ <div className="mt-1.5 mb-3 flex items-center">++ <button++ type="button"++ onClick={handleClick}++ disabled={triggered}++ title={t("Skip reasoning and answer now")}++ aria-disabled={triggered}++ className="group inline-flex items-center gap-1.5 rounded-md border border-[var(--border)]/60 bg-[var(--card)]/60 px-2.5 py-1 text-[11.5px] font-medium text-[var(--muted-foreground)] shadow-sm transition-colors hover:border-[var(--primary)]/40 hover:bg-[var(--primary)]/5 hover:text-[var(--primary)] disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:border-[var(--border)]/60 disabled:hover:bg-[var(--card)]/60 disabled:hover:text-[var(--muted-foreground)]"++ >++ <Zap++ size={12}++ strokeWidth={1.8}++ className="shrink-0 transition-colors group-hover:text-[var(--primary)] group-disabled:group-hover:text-[var(--muted-foreground)]"++ />++ <span>{triggered ? t("Answering…") : t("Answer now")}</span>++ </button>++ </div>++ );++});++++AnswerNowRow.displayName = "AnswerNowRow";++++function CostFooter({++ cost,++ tokens,++ calls,++}: {++ cost: number;++ tokens: number;++ calls: number;++}) {++ const { t } = useTranslation();++ const formatCost = (usd: number) => {++ if (usd < 0.01) return `$${usd.toFixed(4)}`;++ return `$${usd.toFixed(2)}`;++ };++ const formatTokens = (n: number) => {++ if (n >= 1000) return `${(n / 1000).toFixed(1)}k`;++ return String(n);++ };++ return (++ <div className="flex items-center gap-2 text-[10px] text-[var(--muted-foreground)]/40">++ <Coins size={10} strokeWidth={1.5} className="shrink-0" />++ <span>{formatCost(cost)}</span>++ <span className="opacity-40">·</span>++ <span>++ {formatTokens(tokens)} {t("tokens")}++ </span>++ <span className="opacity-40">·</span>++ <span>++ {calls} {t("calls")}++ </span>++ </div>++ );++}++++function RoughActionButton({++ icon: Icon,++ label,++ onClick,++ disabled,++}: {++ icon: LucideIcon;++ label: string;++ onClick: () => void;++ disabled?: boolean;++}) {++ return (++ <button++ type="button"++ onClick={onClick}++ disabled={disabled}++ className="inline-flex items-center gap-1 px-0.5 py-0.5 text-[11px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-35"++ >++ <Icon size={11} strokeWidth={1.5} />++ <span>{label}</span>++ </button>++ );++}++++const UserMessage = memo(function UserMessage({++ msg,++ index,++ onPreviewAttachment,++}: {++ msg: ChatMessageItem;++ index: number;++ onPreviewAttachment?: (attachment: MessageAttachment) => void;++}) {++ const { t } = useTranslation();++ if (msg.content.startsWith("[Quiz Performance]")) return null;++++ return (++ <div key={`${msg.role}-${index}`} className="flex justify-end">++ <div className="max-w-[75%] space-y-1.5">++ <div className="flex justify-end pr-1">++ <span className="text-[10px] tracking-wide text-[var(--muted-foreground)]">++ {t(getModeBadgeLabel(msg.capability))}++ </span>++ </div>++ {msg.attachments?.some((a) => a.type === "image") && (++ <div className="flex flex-wrap justify-end gap-2">++ {msg.attachments++ .filter((a) => a.type === "image" && (a.base64 || a.url))++ .map((a, ai) => {++ const src = imageSrcForAttachment(a);++ if (!src) return null;++ return (++ <button++ key={`img-${ai}`}++ type="button"++ onClick={() => onPreviewAttachment?.(a)}++ title={a.filename || t("image")}++ className="overflow-hidden rounded-2xl border border-[var(--border)] transition-shadow hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/40"++ >++ {/* eslint-disable-next-line @next/next/no-img-element */}++ <img++ src={src}++ alt={a.filename || t("image")}++ className="max-h-48 max-w-[280px] rounded-2xl object-contain"++ />++ </button>++ );++ })}++ </div>++ )}++ {msg.attachments?.some((a) => a.type !== "image") && (++ <div className="flex flex-wrap justify-end gap-2">++ {msg.attachments++ .filter((a) => a.type !== "image")++ .map((a, ai) => {++ const filename = a.filename || t("Attachment");++ const spec = docIconFor(filename);++ const Icon = spec.Icon;++ const cardClass =++ "flex h-14 w-[220px] items-center gap-2.5 rounded-xl border border-[var(--border)] bg-[var(--card)] px-2.5 text-left shadow-sm transition-colors hover:border-[var(--primary)]/40 hover:bg-[var(--muted)]/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]/40";++ return (++ <button++ key={`doc-${ai}`}++ type="button"++ onClick={() => onPreviewAttachment?.(a)}++ title={filename}++ className={cardClass}++ >++ <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-[var(--muted)]/60">++ <Icon size={20} strokeWidth={1.5} className={spec.tint} />++ </div>++ <div className="min-w-0 flex-1 text-left">++ <div className="truncate text-[12px] font-medium text-[var(--foreground)]">++ {filename}++ </div>++ <div className="truncate text-[10px] uppercase tracking-wide text-[var(--muted-foreground)]">++ {spec.label}++ </div>++ </div>++ </button>++ );++ })}++ </div>++ )}++ <div className="rounded-2xl bg-[var(--secondary)] px-4 py-2.5 text-[14px] leading-relaxed text-[var(--foreground)] shadow-sm">++ {(() => {++ const snap = msg.requestSnapshot;++ const hasNotebook = Boolean(snap?.notebookReferences?.length);++ const hasBooks = Boolean(snap?.bookReferences?.length);++ const hasHistory = Boolean(snap?.historyReferences?.length);++ const hasQuestions = Boolean(++ snap?.questionNotebookReferences?.length,++ );++ const hasSkills = Boolean(snap?.skills?.length);++ const hasMemory = Boolean(snap?.memoryReferences?.length);++ if (++ !hasNotebook &&++ !hasBooks &&++ !hasHistory &&++ !hasQuestions &&++ !hasSkills &&++ !hasMemory++ )++ return null;++ return (++ <div className="mb-2 flex flex-wrap gap-1.5">++ {snap?.notebookReferences?.map((ref) => (++ <span++ key={ref.notebook_id}++ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"++ >++ <BookOpen size={11} strokeWidth={1.8} />++ {t("Notebook")} · {ref.record_ids.length} {t("records")}++ </span>++ ))}++ {snap?.bookReferences?.map((ref) => (++ <span++ key={ref.book_id}++ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"++ >++ <BookOpen size={11} strokeWidth={1.8} />++ {t("Book")} · {ref.page_ids.length} {t("chapters")}++ </span>++ ))}++ {snap?.historyReferences?.map((sid) => (++ <span++ key={sid}++ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"++ >++ <MessageSquare size={11} strokeWidth={1.8} />++ {t("Chat History")}++ </span>++ ))}++ {hasQuestions && (++ <span className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]">++ <ClipboardList size={11} strokeWidth={1.8} />++ {t("Question Bank")} ·{" "}++ {snap?.questionNotebookReferences?.length} {t("items")}++ </span>++ )}++ {snap?.skills?.map((skill) => (++ <span++ key={skill}++ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"++ >++ <Wand2 size={11} strokeWidth={1.8} />++ {skill === "auto" ? t("Skills Auto") : skill}++ </span>++ ))}++ {snap?.memoryReferences?.map((file) => (++ <span++ key={file}++ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)]/60 px-2 py-1 text-[11px] font-medium text-[var(--muted-foreground)]"++ >++ <Brain size={11} strokeWidth={1.8} />++ {t("Memory")} ·{" "}++ {file === "summary" ? t("Summary") : t("Profile")}++ </span>++ ))}++ </div>++ );++ })()}++ <div className="whitespace-pre-wrap">{msg.content}</div>++ </div>++ </div>++ </div>++ );++});++++UserMessage.displayName = "UserMessage";++++export const SpaceContextChips = memo(function SpaceContextChips({++ historySessions,++ bookReferences,++ notebookGroups,++ questionEntries,++ selectedSkills,++ skillsAutoMode,++ memoryFiles,++ onRemoveHistory,++ onRemoveBookReference,++ onRemoveNotebook,++ onRemoveQuestion,++ onRemoveSkill,++ onClearSkillsAuto,++ onRemoveMemoryFile,++}: {++ historySessions: SelectedHistorySession[];++ bookReferences: SelectedBookReference[];++ notebookGroups: NotebookReferenceGroup[];++ questionEntries: SelectedQuestionEntry[];++ selectedSkills: string[];++ skillsAutoMode: boolean;++ memoryFiles: SpaceMemoryFile[];++ onRemoveHistory: (sessionId: string) => void;++ onRemoveBookReference: (bookId: string) => void;++ onRemoveNotebook: (notebookId: string) => void;++ onRemoveQuestion: (entryId: number) => void;++ onRemoveSkill: (skill: string) => void;++ onClearSkillsAuto: () => void;++ onRemoveMemoryFile: (file: SpaceMemoryFile) => void;++}) {++ const { t } = useTranslation();++ if (++ historySessions.length === 0 &&++ bookReferences.length === 0 &&++ notebookGroups.length === 0 &&++ questionEntries.length === 0 &&++ selectedSkills.length === 0 &&++ !skillsAutoMode &&++ memoryFiles.length === 0++ )++ return null;++++ return (++ <div className="mb-3 flex flex-wrap gap-2">++ {historySessions.map((session) => (++ <span++ key={session.sessionId}++ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-sky-200 bg-sky-50 px-3 py-1.5 text-[12px] text-sky-800 shadow-sm dark:border-sky-900/60 dark:bg-sky-950/30 dark:text-sky-200"++ >++ <MessageSquare size={12} strokeWidth={1.8} className="shrink-0" />++ <span className="shrink-0 font-medium">{t("Chat History")}</span>++ <span className="truncate text-sky-700/90 dark:text-sky-200/90">++ {session.title}++ </span>++ <button++ onClick={() => onRemoveHistory(session.sessionId)}++ className="shrink-0 opacity-60 transition hover:opacity-100"++ >++ <X size={12} />++ </button>++ </span>++ ))}++ {bookReferences.map((book) => (++ <span++ key={book.bookId}++ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-teal-200 bg-teal-50 px-3 py-1.5 text-[12px] text-teal-800 shadow-sm dark:border-teal-900/60 dark:bg-teal-950/30 dark:text-teal-200"++ >++ <BookOpen size={12} strokeWidth={1.8} className="shrink-0" />++ <span className="shrink-0 font-medium">{t("Book")}</span>++ <span className="truncate text-teal-700/90 dark:text-teal-200/90">++ {book.bookTitle} ({book.pages.length})++ </span>++ <button++ onClick={() => onRemoveBookReference(book.bookId)}++ className="shrink-0 opacity-60 transition hover:opacity-100"++ >++ <X size={12} />++ </button>++ </span>++ ))}++ {notebookGroups.map((group) => (++ <span++ key={group.notebookId}++ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-[12px] text-[var(--foreground)] shadow-sm"++ >++ <BookOpen size={12} strokeWidth={1.8} className="shrink-0" />++ <span className="shrink-0 font-medium">{t("Notebook")}</span>++ <span className="truncate text-[var(--muted-foreground)]">++ {group.notebookName} ({group.count})++ </span>++ <button++ onClick={() => onRemoveNotebook(group.notebookId)}++ className="shrink-0 opacity-60 transition hover:opacity-100"++ >++ <X size={12} />++ </button>++ </span>++ ))}++ {questionEntries.map((entry) => (++ <span++ key={entry.id}++ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-amber-200 bg-amber-50 px-3 py-1.5 text-[12px] text-amber-800 shadow-sm dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-200"++ >++ <ClipboardList size={12} strokeWidth={1.8} className="shrink-0" />++ <span className="shrink-0 font-medium">{t("Question Bank")}</span>++ <span className="truncate text-amber-700/90 dark:text-amber-200/90">++ {entry.question.length > 40++ ? `${entry.question.slice(0, 40)}…`++ : entry.question}++ </span>++ <button++ onClick={() => onRemoveQuestion(entry.id)}++ className="shrink-0 opacity-60 transition hover:opacity-100"++ >++ <X size={12} />++ </button>++ </span>++ ))}++ {skillsAutoMode && (++ <span className="inline-flex max-w-full items-center gap-2 rounded-xl border border-violet-200 bg-violet-50 px-3 py-1.5 text-[12px] text-violet-800 shadow-sm dark:border-violet-900/60 dark:bg-violet-950/30 dark:text-violet-200">++ <Wand2 size={12} strokeWidth={1.8} className="shrink-0" />++ <span className="shrink-0 font-medium">{t("Skills")}</span>++ <span className="truncate text-violet-700/90 dark:text-violet-200/90">++ {t("Auto")}++ </span>++ <button++ onClick={onClearSkillsAuto}++ className="shrink-0 opacity-60 transition hover:opacity-100"++ >++ <X size={12} />++ </button>++ </span>++ )}++ {selectedSkills.map((skill) => (++ <span++ key={skill}++ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-violet-200 bg-violet-50 px-3 py-1.5 text-[12px] text-violet-800 shadow-sm dark:border-violet-900/60 dark:bg-violet-950/30 dark:text-violet-200"++ >++ <Wand2 size={12} strokeWidth={1.8} className="shrink-0" />++ <span className="shrink-0 font-medium">{t("Skill")}</span>++ <span className="truncate text-violet-700/90 dark:text-violet-200/90">++ {skill}++ </span>++ <button++ onClick={() => onRemoveSkill(skill)}++ className="shrink-0 opacity-60 transition hover:opacity-100"++ >++ <X size={12} />++ </button>++ </span>++ ))}++ {memoryFiles.map((file) => (++ <span++ key={file}++ className="inline-flex max-w-full items-center gap-2 rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-1.5 text-[12px] text-emerald-800 shadow-sm dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-200"++ >++ <Brain size={12} strokeWidth={1.8} className="shrink-0" />++ <span className="shrink-0 font-medium">{t("Memory")}</span>++ <span className="truncate text-emerald-700/90 dark:text-emerald-200/90">++ {file === "summary" ? t("Summary") : t("Profile")}++ </span>++ <button++ onClick={() => onRemoveMemoryFile(file)}++ className="shrink-0 opacity-60 transition hover:opacity-100"++ >++ <X size={12} />++ </button>++ </span>++ ))}++ </div>++ );++});++++SpaceContextChips.displayName = "SpaceContextChips";++++export const ChatMessageList = memo(function ChatMessageList({++ messages,++ isStreaming,++ sessionId,++ language,++ onAnswerNow,++ onCopyAssistantMessage,++ onRegenerateMessage,++ onConfirmOutline,++ onPreviewAttachment,++}: {++ messages: ChatMessageItem[];++ isStreaming: boolean;++ sessionId?: string | null;++ language?: string;++ onAnswerNow: (++ snapshot?: MessageRequestSnapshot,++ assistantMsg?: { content: string; events?: StreamEvent[] },++ ) => void;++ onCopyAssistantMessage: (content: string) => void | Promise<void>;++ onRegenerateMessage: () => void;++ onConfirmOutline?: (++ outline: Array<{ title: string; overview: string }>,++ topic: string,++ researchConfig?: Record<string, unknown> | null,++ ) => void;++ onPreviewAttachment?: (attachment: MessageAttachment) => void;++}) {++ const { t } = useTranslation();++ const outlineStatusByIndex = useMemo(() => {++ const map = new Map<number, "editing" | "researching" | "done">();++ for (let i = 0; i < messages.length; i++) {++ const msg = messages[i];++ if (msg.role !== "assistant" || msg.capability !== "deep_research")++ continue;++ const resultEv = msg.events?.find((e) => e.type === "result");++ const meta = resultEv?.metadata as Record<string, unknown> | undefined;++ if (!meta?.outline_preview) continue;++ const hasFollowup = messages++ .slice(i + 1)++ .some(++ (m) => m.role === "assistant" && m.capability === "deep_research",++ );++ if (hasFollowup) {++ const followup = messages++ .slice(i + 1)++ .find(++ (m) => m.role === "assistant" && m.capability === "deep_research",++ );++ const followupResult = followup?.events?.find(++ (e) => e.type === "result",++ );++ map.set(i, followupResult ? "done" : "researching");++ } else if (isStreaming) {++ map.set(i, "researching");++ } else {++ map.set(i, "editing");++ }++ }++ return map;++ }, [messages, isStreaming]);++++ const messageRows = useMemo(() => {++ // System messages are backend grounding (e.g. quiz follow-up context) and++ // must never be rendered as a chat bubble. Filter them out defensively in++ // addition to the hydration-time filter in UnifiedChatContext.++ return messages++ .map((msg, index) => ({ msg, originalIndex: index }))++ .filter(({ msg }) => msg.role !== "system")++ .map(({ msg, originalIndex }) => {++ if (msg.role === "user") {++ return {++ msg,++ originalIndex,++ pairedUserMessage: null as ChatMessageItem | null,++ };++ }++ const pairedUserMessage =++ [...messages.slice(0, originalIndex)]++ .reverse()++ .find((previous) => previous.role === "user") ?? null;++ return { msg, originalIndex, pairedUserMessage };++ });++ }, [messages]);++++ const lastAssistantIndex = useMemo(() => {++ for (let idx = messages.length - 1; idx >= 0; idx -= 1) {++ if (messages[idx].role === "assistant") return idx;++ }++ return -1;++ }, [messages]);++++ return (++ <>++ {messageRows.map(({ msg, originalIndex, pairedUserMessage }) => {++ const i = originalIndex;++ if (msg.role === "user") {++ return (++ <UserMessage++ key={`${msg.role}-${i}`}++ msg={msg}++ index={i}++ onPreviewAttachment={onPreviewAttachment}++ />++ );++ }++++ const isActiveAssistant = isStreaming && i === messages.length - 1;++ const msgDone = !isActiveAssistant;++ const showActions = msgDone && hasVisibleMarkdownContent(msg.content);++ const isLastAssistant = i === lastAssistantIndex;++ const showRegenerate =++ showActions &&++ !isStreaming &&++ isLastAssistant &&++ Boolean(pairedUserMessage) &&++ (!pairedUserMessage?.capability ||++ pairedUserMessage?.capability === "chat");++++ // The "Answer now" affordance lives inside the trace panel for the++ // currently-streaming assistant turn. We hand the panel a thin++ // closure so it does not need to know about MessageRequestSnapshot.++ const handleTraceAnswerNow =++ isActiveAssistant && pairedUserMessage?.requestSnapshot++ ? () =>++ onAnswerNow(pairedUserMessage.requestSnapshot, {++ content: msg.content,++ events: msg.events,++ })++ : undefined;++++ const costSummary = (() => {++ if (!msgDone) return null;++ const resultEv = msg.events?.find((e) => e.type === "result");++ if (!resultEv) return null;++ const meta = resultEv.metadata?.metadata as++ | Record<string, unknown>++ | undefined;++ const cs = meta?.cost_summary as++ | {++ total_cost_usd?: number;++ total_tokens?: number;++ total_calls?: number;++ }++ | undefined;++ if (!cs || !cs.total_calls) return null;++ return cs;++ })();++++ return (++ <div key={`${msg.role}-${i}`} className="w-full">++ <AssistantMessage++ msg={msg}++ isStreaming={isActiveAssistant}++ outlineStatus={outlineStatusByIndex.get(i)}++ sessionId={sessionId}++ language={language}++ onConfirmOutline={onConfirmOutline}++ onAnswerNow={handleTraceAnswerNow}++ />++ {(showActions || costSummary) && (++ <div className="mt-2 flex items-center">++ {showActions && (++ <div className="flex gap-2">++ <RoughActionButton++ icon={Copy}++ label={t("Copy")}++ onClick={() => void onCopyAssistantMessage(msg.content)}++ />++ {showRegenerate && (++ <RoughActionButton++ icon={RefreshCcw}++ label={t("Regenerate")}++ onClick={() => onRegenerateMessage()}++ />++ )}++ </div>++ )}++ {costSummary && (++ <div className="ml-auto">++ <CostFooter++ cost={costSummary.total_cost_usd ?? 0}++ tokens={costSummary.total_tokens ?? 0}++ calls={costSummary.total_calls ?? 0}++ />++ </div>++ )}++ </div>++ )}++ </div>++ );++ })}++ </>++ );++});++++ChatMessageList.displayName = "ChatMessageList";diff --cc web/components/sidebar/WorkspaceSidebar.tsxindex 5d254dc14,bb065c3d1..9342fa428--- a/web/components/sidebar/WorkspaceSidebar.tsx+++ b/web/components/sidebar/WorkspaceSidebar.tsx@@@ -18,10 -17,9 +18,11 @@@ import { surfaceForPath } from "@/lib/sexport default function WorkspaceSidebar() {const { t } = useTranslation();const router = useRouter();+ const pathname = usePathname();+ const surface = useMemo(() => surfaceForPath(pathname), [pathname]);const {newSession,+ cancelStreamingTurn,selectedSessionId,sessionStatuses,sidebarRefreshToken,@@@ -76,8 -69,9 +77,9 @@@.map(({ session }) => session);const handleNewChat = () => {+ cancelStreamingTurn();newSession();- router.push("/chat");+ router.push(surface.basePath);};const handleSelectSession = useCallback(@@@ -113,11 -107,12 +115,13 @@@prev.filter((session) => session.session_id !== sessionId),);if (selectedSessionId === sessionId) {+ cancelStreamingTurn();newSession();- router.push("/chat");+ router.push(surface.basePath);}},+ [newSession, router, selectedSessionId, surface.basePath, t],+ [cancelStreamingTurn, newSession, router, selectedSessionId, t],);return (diff --cc web/locales/en/app.jsonindex 3c69a8595,12601439d..1c40e8cf6--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@@ -1634,14 -1605,103 +1636,113 @@@"Co-Writer tooltip": "AI-powered document editor.","Book tooltip": "Create AI-powered books.","Knowledge tooltip": "Manage learning personas.",+ "Space tooltip": "Your personal learning library.",+ "Quiz settings": "Quiz settings",+ "Animator settings": "Animator settings",+ "Visualize settings": "Visualize settings",+ "Research settings": "Research settings",+ "Confirm": "Confirm",+ "Confirmed": "Confirmed",+ "Edit any field to update settings.": "Edit any field to update settings.",+ "Confirm settings to enable sending.": "Confirm settings to enable sending.",- "Confirm settings on the right to send.": "Confirm settings on the right to send."++ "Confirm settings on the right to send.": "Confirm settings on the right to send.",+ "Learning": "Learning",+ "Learning tooltip": "Structured mastery-based guided learning.",+ "Space tooltip": "Your personal learning library.",+ "guidedLearning.title": "Guided Learning",+ "guidedLearning.description": "Framework v1.8.2 — structured mastery-based learning",+ "guidedLearning.noModules": "No modules yet",+ "guidedLearning.startLearning": "Start Learning",+ "guidedLearning.modules": "Modules",+ "guidedLearning.knowledgePoints": "knowledge points",+ "guidedLearning.knowledgePointsLabel": "Knowledge Points",+ "guidedLearning.mastered": "mastered",+ "guidedLearning.stages": "Learning Stages",+ "guidedLearning.ready": "Ready to start learning",+ "guidedLearning.selectModule": "Select a Module",+ "guidedLearning.selectModuleDesc": "Choose a module to start guided learning",+ "guidedLearning.generatingDiagnostic": "Generating diagnostic questions...",+ "guidedLearning.connectionError": "Connection error",+ "guidedLearning.stageFailed": "Stage execution failed. Progress saved, will retry this stage.",+ "guidedLearning.moduleProgress": "{{count}} knowledge point(s)",+ "guidedLearning.masteredProgress": "{{mastered}}/{{total}} mastered",+ "guidedLearning.inputPlaceholder": "Type your answer...",+ "guidedLearning.submit": "Submit",+ "guidedLearning.noModulesLoaded": "No modules loaded",+ "guidedLearning.createModule": "Create Module",+ "guidedLearning.tabCurrent": "In Progress",+ "guidedLearning.tabCompleted": "Completed",+ "guidedLearning.tabAll": "All",+ "guidedLearning.mastered": "Mastered",+ "guidedLearning.continueLearning": "Continue Learning",+ "guidedLearning.redo": "Redo",+ "guidedLearning.redoConfirm": "This will reset your progress but keep modules. Continue?",+ "guidedLearning.redoFailed": "Failed to redo progress",+ "guidedLearning.delete": "Delete",+ "guidedLearning.deleteConfirm": "This will permanently delete all progress and modules. Continue?",+ "guidedLearning.deleteFailed": "Failed to delete progress",+ "guidedLearning.stage.diagnostic_phase1": "Diagnostic Phase 1",+ "guidedLearning.stage.diagnostic_phase2": "Diagnostic Phase 2",+ "guidedLearning.stage.metacognitive_intro": "Metacognitive Intro",+ "guidedLearning.stage.plan": "Learning Plan",+ "guidedLearning.stage.pretest": "Pretest",+ "guidedLearning.stage.explain": "Explain",+ "guidedLearning.stage.feynman_check": "Feynman Check",+ "guidedLearning.stage.practice_quiz": "Practice Quiz",+ "guidedLearning.stage.practice": "Practice",+ "guidedLearning.stage.error_diagnosis": "Error Diagnosis",+ "guidedLearning.stage.module_test": "Module Test",+ "guidedLearning.stage.review": "Review",+ "guidedLearning.stage.completed": "Completed",+ "Start learning": "Start learning",+ "guidedLearning.alreadyHasProgress": "You already have learning progress for this book. Continuing...",+ "guidedLearning.tabManual": "Manual",+ "guidedLearning.tabBook": "From Book",+ "guidedLearning.tabKb": "From KB",+ "guidedLearning.tabNotebook": "From Notebook",+ "guidedLearning.bookId": "Book ID",+ "guidedLearning.moduleName": "Module Name",+ "guidedLearning.moduleNamePlaceholder": "e.g. Introduction to Algebra",+ "guidedLearning.kpNamePlaceholder": "Knowledge point name",+ "guidedLearning.addKp": "Add knowledge point",+ "guidedLearning.noBooks": "No books available",+ "guidedLearning.chapters": "chapters",+ "guidedLearning.loadingChapters": "Loading chapters...",+ "guidedLearning.noChapters": "No chapters found in this book",+ "guidedLearning.chaptersToImport": "{{count}} chapters to import",+ "guidedLearning.kps": "KPs",+ "guidedLearning.noKb": "No knowledge bases available",+ "guidedLearning.noNotebooks": "No notebooks available",+ "guidedLearning.records": "records",+ "guidedLearning.loadingRecords": "Loading records...",+ "guidedLearning.noRecords": "This notebook has no records",+ "guidedLearning.selectRecords": "Select records to import",+ "guidedLearning.selected": "selected",+ "guidedLearning.recordsLimited": "Only the first 20 records are shown.",+ "guidedLearning.cancel": "Cancel",+ "guidedLearning.create": "Create",+ "guidedLearning.generateModules": "Generate Modules",+ "guidedLearning.moduleNameRequired": "Please enter at least one knowledge point.",+ "guidedLearning.untitledModule": "Untitled Module",+ "guidedLearning.createModuleFailed": "Failed to create module",+ "guidedLearning.importBookFailed": "Failed to import from book",+ "guidedLearning.importKbFailed": "Failed to import from knowledge base",+ "guidedLearning.importNotebookFailed": "Failed to generate modules from notebook",+ "guidedLearning.loadBooksFailed": "Failed to load books",+ "guidedLearning.loadKbFailed": "Failed to load knowledge bases",+ "guidedLearning.loadNotebooksFailed": "Failed to load notebooks",+ "guidedLearning.loadChaptersFailed": "Failed to load chapters",+ "guidedLearning.loadRecordsFailed": "Failed to load notebook records",+ "guidedLearning.comingSoon": "coming soon",+ "guidedLearning.kbComingSoon": "Knowledge Base import coming soon",+ "guidedLearning.kbComingSoonDesc": "This feature will use AI to extract learning modules from your knowledge base.",+ "guidedLearning.startLearningFailed": "Failed to start learning for this book",+ "knowledgeType.memory": "Rote Memory",+ "knowledgeType.concept": "Conceptual",+ "knowledgeType.procedure": "Procedural",+ "knowledgeType.design": "Design",+ "errorType.structural": "Knowledge Structure Gap",+ "errorType.deviation": "Misunderstanding",+ "errorType.application": "Application Error",+ "errorType.metacognitive": "Metacognitive Error"}diff --cc web/locales/zh/app.jsonindex 095ed8514,f956c59a3..e1f5f6a4f--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@@ -1634,14 -1605,103 +1636,113 @@@"Co-Writer tooltip": "AI 驱动的协作文档编辑器。","Book tooltip": "生成交互式 AI 书籍。","Knowledge tooltip": "管理文档与教学人设。",+ "Space tooltip": "你的个人学习空间。",+ "Quiz settings": "测验设置",+ "Animator settings": "动画设置",+ "Visualize settings": "可视化设置",+ "Research settings": "研究设置",+ "Confirm": "确定",+ "Confirmed": "已确认",+ "Edit any field to update settings.": "修改任意字段即可更新设置。",+ "Confirm settings to enable sending.": "确认设置后即可发送。",- "Confirm settings on the right to send.": "请先在右侧确认设置后再发送。"++ "Confirm settings on the right to send.": "请先在右侧确认设置后再发送。",+ "Learning": "学习",+ "Learning tooltip": "结构化掌握式引导学习。",+ "Space tooltip": "你的个人学习空间。",+ "guidedLearning.title": "引导式学习",+ "guidedLearning.description": "框架 v1.8.2 — 结构化掌握式学习",+ "guidedLearning.noModules": "暂无模块",+ "guidedLearning.startLearning": "开始学习",+ "guidedLearning.modules": "学习模块",+ "guidedLearning.knowledgePoints": "个知识点",+ "guidedLearning.knowledgePointsLabel": "知识点",+ "guidedLearning.mastered": "已掌握",+ "guidedLearning.stages": "学习阶段",+ "guidedLearning.ready": "准备开始学习",+ "guidedLearning.selectModule": "选择模块",+ "guidedLearning.selectModuleDesc": "选择一个模块开始引导学习",+ "guidedLearning.generatingDiagnostic": "正在生成诊断题...",+ "guidedLearning.connectionError": "连接错误",+ "guidedLearning.stageFailed": "阶段执行失败。进度已保存,将重试该阶段。",+ "guidedLearning.moduleProgress": "{{count}} 个知识点",+ "guidedLearning.masteredProgress": "已掌握 {{mastered}}/{{total}}",+ "guidedLearning.inputPlaceholder": "输入你的答案...",+ "guidedLearning.submit": "提交",+ "guidedLearning.noModulesLoaded": "暂无模块",+ "guidedLearning.createModule": "创建模块",+ "guidedLearning.tabCurrent": "当前学习",+ "guidedLearning.tabCompleted": "已完成",+ "guidedLearning.tabAll": "全部",+ "guidedLearning.mastered": "已掌握",+ "guidedLearning.continueLearning": "继续学习",+ "guidedLearning.redo": "重做",+ "guidedLearning.redoConfirm": "将重置学习进度但保留模块结构,确认继续?",+ "guidedLearning.redoFailed": "重做失败",+ "guidedLearning.delete": "删除",+ "guidedLearning.deleteConfirm": "将永久删除所有进度和模块,确认继续?",+ "guidedLearning.deleteFailed": "删除失败",+ "guidedLearning.stage.diagnostic_phase1": "诊断阶段一",+ "guidedLearning.stage.diagnostic_phase2": "诊断阶段二",+ "guidedLearning.stage.metacognitive_intro": "元认知导入",+ "guidedLearning.stage.plan": "学习计划",+ "guidedLearning.stage.pretest": "预测试",+ "guidedLearning.stage.explain": "讲解",+ "guidedLearning.stage.feynman_check": "费曼检验",+ "guidedLearning.stage.practice_quiz": "练习测验",+ "guidedLearning.stage.practice": "练习",+ "guidedLearning.stage.error_diagnosis": "错因诊断",+ "guidedLearning.stage.module_test": "模块测试",+ "guidedLearning.stage.review": "复习",+ "guidedLearning.stage.completed": "已完成",+ "Start learning": "开始学习",+ "guidedLearning.alreadyHasProgress": "该书已有学习进度,将直接继续学习。",+ "guidedLearning.tabManual": "手动创建",+ "guidedLearning.tabBook": "从书籍导入",+ "guidedLearning.tabKb": "从知识库导入",+ "guidedLearning.tabNotebook": "从笔记本导入",+ "guidedLearning.bookId": "书籍 ID",+ "guidedLearning.moduleName": "模块名称",+ "guidedLearning.moduleNamePlaceholder": "如:线性代数入门",+ "guidedLearning.kpNamePlaceholder": "知识点名称",+ "guidedLearning.addKp": "添加知识点",+ "guidedLearning.noBooks": "暂无可用书籍",+ "guidedLearning.chapters": "章节",+ "guidedLearning.loadingChapters": "加载章节中...",+ "guidedLearning.noChapters": "该书未找到章节",+ "guidedLearning.chaptersToImport": "将导入 {{count}} 个章节",+ "guidedLearning.kps": "知识点",+ "guidedLearning.noKb": "暂无可用知识库",+ "guidedLearning.noNotebooks": "暂无可用笔记本",+ "guidedLearning.records": "条记录",+ "guidedLearning.loadingRecords": "加载记录中...",+ "guidedLearning.noRecords": "该笔记本暂无记录",+ "guidedLearning.selectRecords": "选择要导入的记录",+ "guidedLearning.selected": "已选",+ "guidedLearning.recordsLimited": "仅显示前 20 条记录。",+ "guidedLearning.cancel": "取消",+ "guidedLearning.create": "创建",+ "guidedLearning.generateModules": "生成模块",+ "guidedLearning.moduleNameRequired": "请至少输入一个知识点。",+ "guidedLearning.untitledModule": "未命名模块",+ "guidedLearning.createModuleFailed": "创建模块失败",+ "guidedLearning.importBookFailed": "从书籍导入失败",+ "guidedLearning.importKbFailed": "从知识库导入失败",+ "guidedLearning.importNotebookFailed": "从笔记本生成模块失败",+ "guidedLearning.loadBooksFailed": "加载书籍失败",+ "guidedLearning.loadKbFailed": "加载知识库失败",+ "guidedLearning.loadNotebooksFailed": "加载笔记本失败",+ "guidedLearning.loadChaptersFailed": "加载章节失败",+ "guidedLearning.loadRecordsFailed": "加载笔记本记录失败",+ "guidedLearning.comingSoon": "即将推出",+ "guidedLearning.kbComingSoon": "知识库导入即将推出",+ "guidedLearning.kbComingSoonDesc": "此功能将使用 AI 从知识库中提取学习模块。",+ "guidedLearning.startLearningFailed": "启动学习失败",+ "knowledgeType.memory": "记忆型",+ "knowledgeType.concept": "概念型",+ "knowledgeType.procedure": "程序型",+ "knowledgeType.design": "设计型",+ "errorType.structural": "知识结构性",+ "errorType.deviation": "理解偏差型",+ "errorType.application": "应用错误",+ "errorType.metacognitive": "元认知型"}