DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Add new development files: RAG diagnostics, chat session detail, text parser
Pancake99ae39fcecba
diff --git a/scripts/diagnose_rag_pipelines.py b/scripts/diagnose_rag_pipelines.pynew file mode 100644index 000000000..b15b4e59f--- /dev/null+++ b/scripts/diagnose_rag_pipelines.py@@ -0,0 +1,364 @@+#!/usr/bin/env python+"""+RAG Pipeline Diagnostic Script+Run with: python scripts/diagnose_rag_pipelines.py+"""++import asyncio+import os+import sys+from pathlib import Path++# Add project root to path+project_root = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(project_root))++from dotenv import load_dotenv+load_dotenv(project_root / "DeepTutor.env", override=False)+load_dotenv(project_root / ".env", override=False)+++class Colors:+ """Terminal colors"""+ GREEN = "\033[92m"+ YELLOW = "\033[93m"+ RED = "\033[91m"+ BLUE = "\033[94m"+ BOLD = "\033[1m"+ END = "\033[0m"+++def print_header(text: str):+ """Print formatted header"""+ print(f"\n{Colors.BOLD}{Colors.BLUE}{'=' * 60}")+ print(f" {text}")+ print(f"{'=' * 60}{Colors.END}\n")+++def print_success(text: str):+ """Print success message"""+ print(f" {Colors.GREEN}✓{Colors.END} {text}")+++def print_warning(text: str):+ """Print warning message"""+ print(f" {Colors.YELLOW}⚠{Colors.END} {text}")+++def print_error(text: str):+ """Print error message"""+ print(f" {Colors.RED}✗{Colors.END} {text}")+++def print_info(text: str):+ """Print info message"""+ print(f" {Colors.BLUE}ℹ{Colors.END} {text}")+++def check_rag_anything_availability():+ """Check if RAG-Anything is available"""+ print_header("RAG-Anything 依赖检查")++ # Check sys.path setup+ raganything_path = project_root.parent / "raganything" / "RAG-Anything"+ if raganything_path.exists():+ print_success(f"RAG-Anything 路径存在: {raganything_path}")+ sys.path.insert(0, str(raganything_path))+ else:+ print_warning(f"RAG-Anything 路径不存在: {raganything_path}")+ print_info("这会影响 raganything, lightrag, academic pipeline")++ # Try importing+ try:+ from raganything import RAGAnything, RAGAnythingConfig+ print_success("可以导入 raganything 库")+ return True+ except ImportError as e:+ print_error(f"无法导入 raganything: {e}")+ return False+++def check_lightrag_availability():+ """Check if LightRAG is available"""+ print_header("LightRAG 依赖检查")++ try:+ from lightrag import LightRAG+ print_success("可以导入 lightrag 库")+ return True+ except ImportError as e:+ print_error(f"无法导入 lightrag: {e}")+ return False+++def check_embedding_service():+ """Check embedding service availability"""+ print_header("Embedding 服务检查")++ try:+ from src.services.embedding import get_embedding_client+ client = get_embedding_client()+ print_success(f"Embedding 客户端可用")+ print_info(f"Model: {client.config.model if hasattr(client, 'config') else 'unknown'}")+ return True+ except Exception as e:+ print_error(f"Embedding 服务错误: {e}")+ return False+++def check_llm_service():+ """Check LLM service availability"""+ print_header("LLM 服务检查")++ try:+ from src.services.llm import get_llm_client, get_llm_config+ config = get_llm_config()+ print_success(f"LLM 配置可用")+ print_info(f"Model: {config.model}")+ print_info(f"Base URL: {config.base_url[:50]}..." if len(config.base_url) > 50 else f"Base URL: {config.base_url}")+ return True+ except Exception as e:+ print_error(f"LLM 服务错误: {e}")+ return False+++def check_pipelines():+ """Check all pipeline availability"""+ print_header("Pipeline 可用性检查")++ from src.services.rag.factory import list_pipelines, get_pipeline, has_pipeline++ pipelines = list_pipelines()+ print_info(f"已注册 {len(pipelines)} 个 pipeline\n")++ results = {}+ for p in pipelines:+ pid = p["id"]+ print(f"\n{Colors.BOLD} [{pid}]{Colors.END} {p['name']}")+ print(f" 描述: {p['description']}")++ try:+ pipeline = get_pipeline(pid)+ print_success(f"Pipeline 实例创建成功")++ # Check components for RAGPipeline types+ if hasattr(pipeline, '_parser'):+ components = []+ if pipeline._parser:+ components.append(f"Parser: {pipeline._parser.name}")+ if pipeline._chunkers:+ components.append(f"Chunkers: {[c.name for c in pipeline._chunkers]}")+ if pipeline._embedder:+ components.append(f"Embedder: {pipeline._embedder.name}")+ if pipeline._indexers:+ components.append(f"Indexers: {[i.name for i in pipeline._indexers]}")+ if pipeline._retriever:+ components.append(f"Retriever: {pipeline._retriever.name}")++ for comp in components:+ print_info(comp)++ results[pid] = "available"++ except Exception as e:+ print_error(f"Pipeline 创建失败: {e}")+ results[pid] = f"error: {e}"++ return results+++async def test_pipeline_search(pipeline_id: str, kb_name: str = None):+ """Test a specific pipeline's search capability"""+ from src.tools.rag_tool import rag_search+ from src.services.rag.factory import get_pipeline++ print(f"\n 测试 {pipeline_id} 搜索功能...")++ # Find an existing KB+ if kb_name is None:+ kb_base = project_root / "data" / "knowledge_bases"+ if kb_base.exists():+ kbs = [d.name for d in kb_base.iterdir() if d.is_dir() and (d / "rag_storage").exists()]+ if kbs:+ kb_name = kbs[0]+ print_info(f"使用已有知识库: {kb_name}")++ if kb_name is None:+ print_warning("没有找到可用的知识库,跳过搜索测试")+ return False++ try:+ result = await rag_search(+ query="What is the main topic?",+ kb_name=kb_name,+ mode="naive",+ provider=pipeline_id+ )++ answer_len = len(result.get("answer", ""))+ if answer_len > 0:+ print_success(f"搜索成功,返回 {answer_len} 字符")+ return True+ else:+ print_warning("搜索返回空结果")+ return False++ except Exception as e:+ print_error(f"搜索失败: {e}")+ return False+++def check_existing_knowledge_bases():+ """Check existing knowledge bases"""+ print_header("已有知识库检查")++ kb_base = project_root / "data" / "knowledge_bases"+ if not kb_base.exists():+ print_warning(f"知识库目录不存在: {kb_base}")+ return []++ kbs = []+ for kb_dir in kb_base.iterdir():+ if kb_dir.is_dir():+ kb_name = kb_dir.name+ rag_storage = kb_dir / "rag_storage"+ content_list = kb_dir / "content_list"+ numbered_items = kb_dir / "numbered_items.json"++ status = []+ if rag_storage.exists():+ status.append("rag_storage")+ if content_list.exists():+ status.append("content_list")+ if numbered_items.exists():+ status.append("numbered_items")++ if status:+ kbs.append(kb_name)+ print_success(f"{kb_name}: {', '.join(status)}")+ else:+ print_warning(f"{kb_name}: 空知识库")++ if not kbs:+ print_warning("没有找到已初始化的知识库")++ return kbs+++def check_environment():+ """Check environment variables"""+ print_header("环境变量检查")++ env_vars = [+ ("RAG_PROVIDER", "raganything"),+ ("OPENAI_API_KEY", None),+ ("OPENAI_BASE_URL", None),+ ("LLM_MODEL", None),+ ("EMBEDDING_MODEL", None),+ ]++ for var, default in env_vars:+ value = os.getenv(var, default)+ if value:+ # Mask API keys+ if "KEY" in var and value:+ masked = value[:8] + "..." + value[-4:] if len(value) > 12 else "***"+ print_success(f"{var}: {masked}")+ else:+ print_success(f"{var}: {value}")+ else:+ print_warning(f"{var}: 未设置")+++def print_summary(results: dict):+ """Print diagnostic summary"""+ print_header("诊断总结")++ for key, value in results.items():+ if value is True or value == "available":+ print_success(f"{key}: 可用")+ elif value is False:+ print_error(f"{key}: 不可用")+ elif isinstance(value, str) and value.startswith("error"):+ print_error(f"{key}: {value}")+ else:+ print_warning(f"{key}: {value}")+++def print_recommendations(results: dict):+ """Print recommendations based on results"""+ print_header("建议")++ recommendations = []++ if not results.get("rag_anything_lib"):+ recommendations.append(+ "安装 RAG-Anything:\n"+ " git clone https://github.com/HKUDS/RAG-Anything.git ../raganything/RAG-Anything\n"+ " pip install -r ../raganything/RAG-Anything/requirements.txt"+ )++ if not results.get("embedding_service"):+ recommendations.append(+ "配置 Embedding 服务:\n"+ " 确保在 DeepTutor.env 或 .env 中设置了正确的 API key 和 base URL"+ )++ if not results.get("llm_service"):+ recommendations.append(+ "配置 LLM 服务:\n"+ " 确保在 DeepTutor.env 或 .env 中设置了正确的 OPENAI_API_KEY"+ )++ if results.get("pipelines", {}).get("llamaindex") == "available":+ print_success("llamaindex pipeline 可以在没有 RAG-Anything 的情况下使用 (轻量级向量搜索)")++ if recommendations:+ for i, rec in enumerate(recommendations, 1):+ print(f"\n {i}. {rec}")+ else:+ print_success("所有服务正常运行!")+++async def main():+ """Main diagnostic function"""+ print(f"\n{Colors.BOLD}DeepTutor RAG Pipeline 诊断工具{Colors.END}")+ print(f"项目根目录: {project_root}\n")++ results = {}++ # Check environment+ check_environment()++ # Check services+ results["embedding_service"] = check_embedding_service()+ results["llm_service"] = check_llm_service()++ # Check external dependencies+ results["rag_anything_lib"] = check_rag_anything_availability()+ results["lightrag_lib"] = check_lightrag_availability()++ # Check pipelines+ results["pipelines"] = check_pipelines()++ # Check existing KBs+ kbs = check_existing_knowledge_bases()+ results["knowledge_bases"] = kbs++ # Print summary and recommendations+ print_summary(results)+ print_recommendations(results)++ # Optional: Run search tests+ if kbs and results.get("rag_anything_lib"):+ print_header("搜索功能测试")+ for pipeline_id in ["raganything"]:+ await test_pipeline_search(pipeline_id, kbs[0])+++if __name__ == "__main__":+ if sys.platform == "win32":+ # Windows needs special handling for asyncio+ asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())++ asyncio.run(main())diff --git a/src/agents/guide/agents/base_guide_agent.py b/src/agents/guide/agents/base_guide_agent.pynew file mode 100644index 000000000..cd8723deb--- /dev/null+++ b/src/agents/guide/agents/base_guide_agent.py@@ -0,0 +1,160 @@+#!/usr/bin/env python+"""+BaseGuideAgent - Base class for guided learning agents.+Uses unified PromptManager for prompt loading.+"""++from abc import ABC, abstractmethod+import os+from pathlib import Path+import sys+from typing import Any++# Add project root to path+_project_root = Path(__file__).parent.parent.parent.parent+if str(_project_root) not in sys.path:+ sys.path.insert(0, str(_project_root))++from src.core.llm_factory import llm_complete++from src.core.core import get_agent_params, get_token_limit_kwargs, load_config_with_main+from src.core.logging import LLMStats, get_logger+from src.core.prompt_manager import get_prompt_manager+++class BaseGuideAgent(ABC):+ """Base class for Guided Learning Agents."""++ # Shared stats tracker for all guide agents+ _shared_stats: LLMStats | None = None++ def __init__(self, api_key: str, base_url: str, agent_name: str, language: str = "zh", binding: str = "openai"):+ """+ Initialize base Agent.++ Args:+ api_key: API key+ base_url: API endpoint+ agent_name: Agent name+ language: Language setting ('zh' | 'en')+ binding: LLM provider binding+ """+ self.api_key = api_key+ self.base_url = base_url+ self.agent_name = agent_name+ self.language = language+ self.binding = binding++ # Load agent parameters from unified config (agents.yaml)+ self._agent_params = get_agent_params("guide")++ # Initialize logger (from config)+ try:+ config = load_config_with_main("guide_config.yaml", _project_root)+ log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get(+ "log_dir"+ )+ self.logger = get_logger(f"Guide.{agent_name}", log_dir=log_dir)+ except Exception:+ # Fallback logger+ self.logger = get_logger(f"Guide.{agent_name}")++ # Load prompts using unified PromptManager+ self.prompts = get_prompt_manager().load_prompts(+ module_name="guide",+ agent_name=self.agent_name,+ language=self.language,+ )+ if self.prompts:+ self.logger.info(f"Loaded prompts: {self.agent_name} ({self.language})")++ @classmethod+ def get_stats(cls) -> LLMStats:+ """Get or create shared stats tracker."""+ if cls._shared_stats is None:+ cls._shared_stats = LLMStats(module_name="GuidedLearning")+ return cls._shared_stats++ @classmethod+ def reset_stats(cls):+ """Reset shared stats."""+ if cls._shared_stats:+ cls._shared_stats.reset()++ @classmethod+ def print_stats(cls):+ """Print stats summary."""+ if cls._shared_stats:+ cls._shared_stats.print_summary()++ def get_model(self) -> str:+ """Get model name."""+ model = os.getenv("LLM_MODEL")+ if not model:+ raise ValueError("Environment variable LLM_MODEL not set")+ return model++ async def call_llm(+ self,+ user_prompt: str,+ system_prompt: str,+ response_format: dict[str, str] | None = None,+ temperature: float | None = None,+ max_tokens: int | None = None,+ ) -> str:+ """+ Unified LLM call interface.++ Args:+ user_prompt: User prompt+ system_prompt: System prompt+ response_format: Response format+ temperature: Temperature parameter (uses config default if None)+ max_tokens: Maximum tokens (uses config default if None)++ Returns:+ LLM response text+ """+ model = self.get_model()++ # Use parameters from unified config (agents.yaml) if not explicitly provided+ if temperature is None:+ temperature = self._agent_params["temperature"]+ if max_tokens is None:+ max_tokens = self._agent_params["max_tokens"]++ kwargs = {+ "model": model,+ "prompt": user_prompt,+ "system_prompt": system_prompt,+ "api_key": self.api_key,+ "base_url": self.base_url,+ "temperature": temperature,+ "binding": self.binding,+ }++ if max_tokens:+ kwargs.update(get_token_limit_kwargs(model, max_tokens))++ if response_format:+ kwargs["response_format"] = response_format++ response = await llm_complete(**kwargs)++ # Track token usage+ stats = self.get_stats()+ stats.add_call(+ model=model, system_prompt=system_prompt, user_prompt=user_prompt, response=response+ )++ return response++ def get_prompt(self, prompt_type: str = "system") -> str | None:+ """Get prompt"""+ if self.prompts and prompt_type in self.prompts:+ return self.prompts[prompt_type]+ return None++ @abstractmethod+ async def process(self, *args, **kwargs) -> Any:+ """Main processing logic of the agent (must be implemented by subclasses)"""diff --git a/src/services/rag/components/parsers/text.py b/src/services/rag/components/parsers/text.pynew file mode 100644index 000000000..fe95a3f00--- /dev/null+++ b/src/services/rag/components/parsers/text.py@@ -0,0 +1,86 @@+"""+Text Parser+===========++Parser for plain text documents (.txt files).+"""++from pathlib import Path+from typing import Union++from ..base import BaseComponent+from ...types import Document+++class TextParser(BaseComponent):+ """+ Plain text parser.++ Parses text files (.txt) into Document objects.+ Also handles common text-based formats.+ """++ name = "text_parser"++ # Supported extensions+ SUPPORTED_EXTENSIONS = {".txt", ".text", ".log", ".csv", ".tsv"}++ async def process(self, file_path: Union[str, Path], **kwargs) -> Document:+ """+ Parse a text file into a Document.++ Args:+ file_path: Path to the text file+ **kwargs: Additional arguments++ Returns:+ Parsed Document+ """+ file_path = Path(file_path)++ if not file_path.exists():+ raise FileNotFoundError(f"Text file not found: {file_path}")++ self.logger.info(f"Parsing text file: {file_path.name}")++ # Try different encodings+ content = None+ encodings = ["utf-8", "utf-8-sig", "gbk", "gb2312", "latin-1"]++ for encoding in encodings:+ try:+ with open(file_path, "r", encoding=encoding) as f:+ content = f.read()+ break+ except UnicodeDecodeError:+ continue++ if content is None:+ # Last resort: read as binary and decode with error handling+ with open(file_path, "rb") as f:+ content = f.read().decode("utf-8", errors="replace")++ return Document(+ content=content,+ file_path=str(file_path),+ metadata={+ "filename": file_path.name,+ "parser": self.name,+ "extension": file_path.suffix.lower(),+ "size_bytes": file_path.stat().st_size,+ },+ )++ @classmethod+ def can_parse(cls, file_path: Union[str, Path]) -> bool:+ """+ Check if this parser can handle the given file.++ Args:+ file_path: Path to check++ Returns:+ True if file can be parsed+ """+ suffix = Path(file_path).suffix.lower()+ return suffix in cls.SUPPORTED_EXTENSIONSdiff --git a/src/services/rag/service.py b/src/services/rag/service.pynew file mode 100644index 000000000..ba813b1df--- /dev/null+++ b/src/services/rag/service.py@@ -0,0 +1,206 @@+"""+RAG Service+===========++Unified RAG service providing a single entry point for all RAG operations.+"""++import os+from pathlib import Path+from typing import Any, Dict, List, Optional++from src.logging import get_logger++# Default knowledge base directory+DEFAULT_KB_BASE_DIR = str(+ Path(__file__).resolve().parent.parent.parent.parent / "data" / "knowledge_bases"+)+++class RAGService:+ """+ Unified RAG service entry point.++ Provides a clean interface for RAG operations:+ - Knowledge base initialization+ - Search/retrieval+ - Knowledge base deletion++ Usage:+ # Default configuration+ service = RAGService()+ await service.initialize("my_kb", ["doc1.pdf"])+ result = await service.search("query", "my_kb")++ # Custom configuration for testing+ service = RAGService(kb_base_dir="/tmp/test_kb", provider="llamaindex")+ await service.initialize("test", ["test.txt"])+ """++ def __init__(+ self,+ kb_base_dir: Optional[str] = None,+ provider: Optional[str] = None,+ ):+ """+ Initialize RAG service.++ Args:+ kb_base_dir: Base directory for knowledge bases.+ Defaults to data/knowledge_bases.+ provider: RAG pipeline provider to use.+ Defaults to RAG_PROVIDER env var or "raganything".+ """+ self.logger = get_logger("RAGService")+ self.kb_base_dir = kb_base_dir or DEFAULT_KB_BASE_DIR+ self.provider = provider or os.getenv("RAG_PROVIDER", "raganything")+ self._pipeline = None++ def _get_pipeline(self):+ """Get or create pipeline instance."""+ if self._pipeline is None:+ from .factory import get_pipeline+ self._pipeline = get_pipeline(self.provider, kb_base_dir=self.kb_base_dir)+ return self._pipeline++ async def initialize(+ self,+ kb_name: str,+ file_paths: List[str],+ **kwargs+ ) -> bool:+ """+ Initialize a knowledge base with documents.++ Args:+ kb_name: Knowledge base name+ file_paths: List of file paths to process+ **kwargs: Additional arguments passed to pipeline++ Returns:+ True if successful++ Example:+ service = RAGService()+ success = await service.initialize("my_kb", ["doc1.pdf", "doc2.txt"])+ """+ self.logger.info(f"Initializing KB '{kb_name}' with provider '{self.provider}'")+ pipeline = self._get_pipeline()+ return await pipeline.initialize(kb_name=kb_name, file_paths=file_paths, **kwargs)++ async def search(+ self,+ query: str,+ kb_name: str,+ mode: str = "hybrid",+ **kwargs+ ) -> Dict[str, Any]:+ """+ Search a knowledge base.++ Args:+ query: Search query+ kb_name: Knowledge base name+ mode: Search mode (hybrid, local, global, naive)+ **kwargs: Additional arguments passed to pipeline++ Returns:+ Search results dictionary with keys:+ - query: Original query+ - answer: Generated answer+ - content: Retrieved content+ - mode: Search mode used+ - provider: Pipeline provider used++ Example:+ service = RAGService()+ result = await service.search("What is ML?", "textbook")+ print(result["answer"])+ """+ self.logger.info(f"Searching KB '{kb_name}' with query: {query[:50]}...")+ pipeline = self._get_pipeline()++ result = await pipeline.search(query=query, kb_name=kb_name, mode=mode, **kwargs)++ # Ensure consistent return format+ if "query" not in result:+ result["query"] = query+ if "answer" not in result and "content" in result:+ result["answer"] = result["content"]+ if "content" not in result and "answer" in result:+ result["content"] = result["answer"]+ if "provider" not in result:+ result["provider"] = self.provider+ if "mode" not in result:+ result["mode"] = mode++ return result++ async def delete(self, kb_name: str) -> bool:+ """+ Delete a knowledge base.++ Args:+ kb_name: Knowledge base name++ Returns:+ True if successful++ Example:+ service = RAGService()+ success = await service.delete("old_kb")+ """+ self.logger.info(f"Deleting KB '{kb_name}'")+ pipeline = self._get_pipeline()++ if hasattr(pipeline, 'delete'):+ return await pipeline.delete(kb_name=kb_name)++ # Fallback: delete directory manually+ import shutil+ kb_dir = Path(self.kb_base_dir) / kb_name+ if kb_dir.exists():+ shutil.rmtree(kb_dir)+ self.logger.info(f"Deleted KB directory: {kb_dir}")+ return True+ return False++ @staticmethod+ def list_providers() -> List[Dict[str, str]]:+ """+ List available RAG pipeline providers.++ Returns:+ List of provider info dictionaries++ Example:+ providers = RAGService.list_providers()+ for p in providers:+ print(f"{p['id']}: {p['description']}")+ """+ from .factory import list_pipelines+ return list_pipelines()++ @staticmethod+ def get_current_provider() -> str:+ """+ Get the currently configured default provider.++ Returns:+ Provider name from RAG_PROVIDER env var or default+ """+ return os.getenv("RAG_PROVIDER", "raganything")++ @staticmethod+ def has_provider(name: str) -> bool:+ """+ Check if a provider is available.++ Args:+ name: Provider name++ Returns:+ True if provider exists+ """+ from .factory import has_pipeline+ return has_pipeline(name)diff --git a/web/components/ChatSessionDetail.tsx b/web/components/ChatSessionDetail.tsxnew file mode 100644index 000000000..a56ed18f3--- /dev/null+++ b/web/components/ChatSessionDetail.tsx@@ -0,0 +1,282 @@+"use client";++import { useState, useEffect } from "react";+import { createPortal } from "react-dom";+import { X, MessageCircle, User, Bot, Clock, Loader2, MessageSquare, ExternalLink } from "lucide-react";+import ReactMarkdown from "react-markdown";+import remarkMath from "remark-math";+import rehypeKatex from "rehype-katex";+import "katex/dist/katex.min.css";+import { apiUrl } from "@/lib/api";+import { processLatexContent } from "@/lib/latex";+import { useGlobal } from "@/context/GlobalContext";+import { getTranslation } from "@/lib/i18n";++interface ChatMessage {+ role: "user" | "assistant";+ content: string;+ timestamp?: number;+ sources?: {+ rag?: Array<{ kb_name: string; content: string }>;+ web?: Array<{ url: string; title?: string }>;+ };+}++interface ChatSession {+ session_id: string;+ title: string;+ messages: ChatMessage[];+ settings?: {+ kb_name?: string;+ enable_rag?: boolean;+ enable_web_search?: boolean;+ };+ created_at: number;+ updated_at: number;+}++interface ChatSessionDetailProps {+ sessionId: string;+ onClose: () => void;+ onContinue: () => void;+}++export default function ChatSessionDetail({+ sessionId,+ onClose,+ onContinue,+}: ChatSessionDetailProps) {+ const { uiSettings } = useGlobal();+ const t = (key: string) => getTranslation(uiSettings.language, key);++ const [session, setSession] = useState<ChatSession | null>(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);+ const [mounted, setMounted] = useState(false);++ // Ensure we're on the client before rendering portal+ useEffect(() => {+ setMounted(true);+ return () => setMounted(false);+ }, []);++ useEffect(() => {+ const fetchSession = async () => {+ setLoading(true);+ setError(null);+ try {+ const response = await fetch(apiUrl(`/api/v1/chat/sessions/${sessionId}`));+ if (!response.ok) {+ throw new Error("Failed to load session");+ }+ const data = await response.json();+ setSession(data);+ } catch (err) {+ setError(err instanceof Error ? err.message : "Unknown error");+ } finally {+ setLoading(false);+ }+ };++ fetchSession();+ }, [sessionId]);++ // Handle escape key to close modal+ useEffect(() => {+ const handleEscape = (e: KeyboardEvent) => {+ if (e.key === "Escape") {+ onClose();+ }+ };+ document.addEventListener("keydown", handleEscape);+ return () => document.removeEventListener("keydown", handleEscape);+ }, [onClose]);++ // Don't render until mounted (client-side only)+ if (!mounted) return null;++ const modalContent = (+ <div+ className="fixed inset-0 z-[9999] flex items-center justify-center p-4"+ onClick={onClose}+ >+ {/* Backdrop */}+ <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" />++ {/* Modal */}+ <div+ className="relative bg-white dark:bg-slate-800 rounded-2xl shadow-2xl w-full max-w-3xl max-h-[85vh] flex flex-col animate-in zoom-in-95 duration-300"+ onClick={(e) => e.stopPropagation()}+ >+ {/* Header */}+ <div className="p-6 border-b border-slate-100 dark:border-slate-700 flex justify-between items-center shrink-0">+ <div className="flex items-center gap-4">+ <div className="w-10 h-10 rounded-xl bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center">+ <MessageCircle className="w-5 h-5 text-amber-600 dark:text-amber-400" />+ </div>+ <div>+ <h2 className="font-bold text-slate-900 dark:text-slate-100 text-lg">+ {session?.title || t("Chat History")}+ </h2>+ {session && (+ <p className="text-xs text-slate-500 dark:text-slate-400 flex items-center gap-2">+ <Clock className="w-3 h-3" />+ {new Date(session.created_at * 1000).toLocaleString(+ uiSettings.language === "zh" ? "zh-CN" : "en-US"+ )}+ <span className="mx-1">•</span>+ {session.messages.length} {t("messages")}+ </p>+ )}+ </div>+ </div>+ <button+ onClick={onClose}+ className="w-8 h-8 rounded-full bg-slate-100 dark:bg-slate-700 hover:bg-slate-200 dark:hover:bg-slate-600 flex items-center justify-center text-slate-500 dark:text-slate-400 transition-colors"+ >+ <X className="w-4 h-4" />+ </button>+ </div>++ {/* Content */}+ <div className="flex-1 overflow-y-auto p-6">+ {loading ? (+ <div className="flex items-center justify-center py-12">+ <Loader2 className="w-8 h-8 animate-spin text-amber-500" />+ </div>+ ) : error ? (+ <div className="text-center py-12">+ <p className="text-red-500 dark:text-red-400">{error}</p>+ </div>+ ) : session ? (+ <div className="space-y-4">+ {/* Settings Info */}+ {session.settings && (session.settings.kb_name || session.settings.enable_rag || session.settings.enable_web_search) && (+ <div className="flex flex-wrap gap-2 mb-4 pb-4 border-b border-slate-100 dark:border-slate-700">+ {session.settings.kb_name && (+ <span className="px-2.5 py-1 text-xs font-medium bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-full">+ KB: {session.settings.kb_name}+ </span>+ )}+ {session.settings.enable_rag && (+ <span className="px-2.5 py-1 text-xs font-medium bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300 rounded-full">+ RAG Enabled+ </span>+ )}+ {session.settings.enable_web_search && (+ <span className="px-2.5 py-1 text-xs font-medium bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 rounded-full">+ Web Search Enabled+ </span>+ )}+ </div>+ )}++ {/* Messages */}+ {session.messages.map((msg, idx) => (+ <div+ key={idx}+ className={`flex gap-3 ${msg.role === "user" ? "justify-end" : "justify-start"}`}+ >+ {msg.role === "assistant" && (+ <div className="w-8 h-8 rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center shrink-0">+ <Bot className="w-4 h-4 text-amber-600 dark:text-amber-400" />+ </div>+ )}+ <div+ className={`max-w-[80%] rounded-2xl px-4 py-3 ${+ msg.role === "user"+ ? "bg-blue-500 text-white rounded-br-none"+ : "bg-slate-100 dark:bg-slate-700 text-slate-800 dark:text-slate-200 rounded-bl-none"+ }`}+ >+ {msg.role === "user" ? (+ <p className="whitespace-pre-wrap">{msg.content}</p>+ ) : (+ <div className="prose prose-sm dark:prose-invert max-w-none prose-p:my-2 prose-headings:my-2">+ <ReactMarkdown+ remarkPlugins={[remarkMath]}+ rehypePlugins={[rehypeKatex]}+ >+ {processLatexContent(msg.content)}+ </ReactMarkdown>+ </div>+ )}++ {/* Sources */}+ {msg.sources && (msg.sources.rag?.length || msg.sources.web?.length) && (+ <div className="mt-3 pt-3 border-t border-slate-200 dark:border-slate-600">+ <p className="text-xs font-medium text-slate-500 dark:text-slate-400 mb-2">+ {t("Sources")}:+ </p>+ <div className="flex flex-wrap gap-1">+ {msg.sources.rag?.map((src, i) => (+ <span+ key={`rag-${i}`}+ className="px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded"+ >+ 📚 {src.kb_name}+ </span>+ ))}+ {msg.sources.web?.map((src, i) => (+ <a+ key={`web-${i}`}+ href={src.url}+ target="_blank"+ rel="noopener noreferrer"+ className="px-2 py-0.5 text-xs bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 rounded hover:bg-purple-200 dark:hover:bg-purple-900/50 flex items-center gap-1"+ >+ 🌐 {src.title || new URL(src.url).hostname}+ <ExternalLink className="w-2.5 h-2.5" />+ </a>+ ))}+ </div>+ </div>+ )}++ {/* Timestamp */}+ {msg.timestamp && (+ <p className={`text-xs mt-2 ${+ msg.role === "user"+ ? "text-blue-200"+ : "text-slate-400 dark:text-slate-500"+ }`}>+ {new Date(msg.timestamp * 1000).toLocaleTimeString(+ uiSettings.language === "zh" ? "zh-CN" : "en-US",+ { hour: "2-digit", minute: "2-digit" }+ )}+ </p>+ )}+ </div>+ {msg.role === "user" && (+ <div className="w-8 h-8 rounded-full bg-blue-500 flex items-center justify-center shrink-0">+ <User className="w-4 h-4 text-white" />+ </div>+ )}+ </div>+ ))}+ </div>+ ) : null}+ </div>++ {/* Footer */}+ <div className="p-6 border-t border-slate-100 dark:border-slate-700 bg-slate-50 dark:bg-slate-900/50 rounded-b-2xl flex justify-between items-center shrink-0">+ <button+ onClick={onClose}+ className="px-6 py-2.5 bg-slate-200 dark:bg-slate-700 text-slate-700 dark:text-slate-300 rounded-xl font-medium hover:bg-slate-300 dark:hover:bg-slate-600 transition-colors"+ >+ {t("Close")}+ </button>+ <button+ onClick={onContinue}+ className="px-6 py-2.5 bg-amber-500 text-white rounded-xl font-medium hover:bg-amber-600 transition-colors flex items-center gap-2"+ >+ <MessageSquare className="w-4 h-4" />+ {t("Continue")}+ </button>+ </div>+ </div>+ </div>+ );++ return createPortal(modalContent, document.body);+}